--- /dev/null
+/* IOEngine.h - IOMultiplexer
+ * Copyright (C) 2012 Philipp Kreil (pk910)
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+#ifndef _IOEngine_h
+#define _IOEngine_h
+#include "IOHandler.h"
+
+#ifdef HAVE_PTHREAD_H
+#include <pthread.h>
+#ifdef PTHREAD_MUTEX_RECURSIVE_NP
+#define PTHREAD_MUTEX_RECURSIVE_VAL PTHREAD_MUTEX_RECURSIVE_NP
+#else
+#define PTHREAD_MUTEX_RECURSIVE_VAL PTHREAD_MUTEX_RECURSIVE
+#endif
+#define IOTHREAD_MUTEX_INIT(var) { \
+ pthread_mutexattr_t mutex_attr; \
+ pthread_mutexattr_init(&mutex_attr);\
+ pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_RECURSIVE_VAL);\
+ pthread_mutex_init(&var, &mutex_attr); \
+}
+#define IOSYNCHRONIZE(var) pthread_mutex_lock(&var)
+#define IODESYNCHRONIZE(var) pthread_mutex_unlock(&var)
+#else
+#define IOTHREAD_MUTEX_INIT(var)
+#define IOSYNCHRONIZE(var)
+#define IODESYNCHRONIZE(var)
+#endif
+
+struct IODescriptor;
+enum IOType;
+enum IOStatus;
+enum IOEventType;
+
+#define timeval_is_bigger(x,y) ((x->tv_sec > y->tv_sec) || (x->tv_sec == y->tv_sec && x->tv_usec > y->tv_usec))
+#define timeval_is_smaler(x,y) ((x->tv_sec < y->tv_sec) || (x->tv_sec == y->tv_sec && x->tv_usec < y->tv_usec))
+
+extern struct IODescriptor *first_descriptor;
+extern struct IODescriptor *timer_priority;
+
+struct IOEngine {
+ const char *name;
+ int (*init)(void);
+ void (*add)(struct IODescriptor *iofd);
+ void (*remove)(struct IODescriptor *iofd);
+ void (*update)(struct IODescriptor *iofd);
+ void (*loop)(struct timeval *timeout);
+ void (*cleanup)(void);
+};
+
+#define iohandler_wants_writes(IOFD) ((IOFD->writebuf.bufpos && !IOFD->ssl_hs_read) || IOFD->state == IO_CONNECTING || IOFD->ssl_hs_write)
+
+void iohandler_log(enum IOLogType type, char *text, ...);
+void iohandler_events(struct IODescriptor *iofd, int readable, int writeable);
+char *iohandler_iotype_name(enum IOType type);
+char *iohandler_iostatus_name(enum IOStatus status);
+char *iohandler_ioeventtype_name(enum IOEventType type);
+
+#endif
--- /dev/null
+/* IOEngine_epoll.c - IOMultiplexer
+ * Copyright (C) 2012 Philipp Kreil (pk910)
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+#include "IOEngine.h"
+
+#ifdef HAVE_SYS_EPOLL_H
+#include <sys/epoll.h>
+#include <errno.h>
+#include <string.h>
+#include <unistd.h>
+
+#define MAX_EVENTS 32
+
+static int epoll_fd;
+
+static int engine_epoll_init() {
+ epoll_fd = epoll_create(1024);
+ if (epoll_fd < 0)
+ return 0;
+ return 1;
+}
+
+static void engine_epoll_add(struct IODescriptor *iofd) {
+ if(iofd->type == IOTYPE_TIMER) return;
+ //add descriptor to the epoll queue
+ struct epoll_event evt;
+ int res;
+
+ evt.events = EPOLLHUP | EPOLLIN | (iohandler_wants_writes(iofd) ? EPOLLOUT : 0);
+ evt.data.ptr = iofd;
+ res = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, iofd->fd, &evt);
+ if(res < 0) {
+ iohandler_log(IOLOG_ERROR, "could not add IODescriptor %d to epoll queue. (returned: %d)", iofd->fd, res);
+ }
+}
+
+static void engine_epoll_remove(struct IODescriptor *iofd) {
+ if(iofd->type == IOTYPE_TIMER) return;
+ struct epoll_event evt;
+ epoll_ctl(epoll_fd, EPOLL_CTL_DEL, iofd->fd, &evt);
+}
+
+static void engine_epoll_update(struct IODescriptor *iofd) {
+ if(iofd->type == IOTYPE_TIMER) return;
+ if(iofd->state == IO_CLOSED) {
+ engine_epoll_remove(iofd);
+ return;
+ }
+ struct epoll_event evt;
+ int res;
+
+ evt.events = EPOLLHUP | EPOLLIN | (iohandler_wants_writes(iofd) ? EPOLLOUT : 0);
+ evt.data.ptr = iofd;
+ res = epoll_ctl(epoll_fd, EPOLL_CTL_MOD, iofd->fd, &evt);
+ if(res < 0) {
+ iohandler_log(IOLOG_ERROR, "could not update IODescriptor %d in epoll queue. (returned: %d)", iofd->fd, res);
+ }
+}
+
+static void engine_epoll_loop(struct timeval *timeout) {
+ struct epoll_event evts[MAX_EVENTS];
+ struct timeval now, tdiff;
+ int msec;
+ int events;
+ int epoll_result;
+
+ gettimeofday(&now, NULL);
+
+ while(timer_priority) {
+ tdiff.tv_sec = timer_priority->timeout.tv_sec - now.tv_sec;
+ tdiff.tv_usec = timer_priority->timeout.tv_usec - now.tv_usec;
+ if(tdiff.tv_sec < 0 || (tdiff.tv_sec == 0 && tdiff.tv_usec <= 0)) {
+ if(timer_priority->constant_timeout) {
+ tdiff.tv_sec = 0;
+ iohandler_set_timeout(timer_priority, &tdiff);
+ iohandler_events(timer_priority, 0, 0);
+ } else {
+ iohandler_events(timer_priority, 0, 0);
+ iohandler_close(timer_priority); //also sets timer_priority to the next timed element
+ }
+ continue;
+ } else if(tdiff.tv_usec < 0) {
+ tdiff.tv_sec--;
+ tdiff.tv_usec += 1000000; //1 sec
+ }
+ if(timeval_is_smaler((&tdiff), timeout)) {
+ timeout->tv_sec = tdiff.tv_sec;
+ timeout->tv_usec = tdiff.tv_usec;
+ }
+ break;
+ }
+
+ msec = timeout ? ((timeout->tv_sec * 1000 + timeout->tv_usec / 1000) + (timeout->tv_usec % 1000 != 0 ? 1 : 0)) : -1;
+
+ //select system call
+ epoll_result = epoll_wait(epoll_fd, evts, MAX_EVENTS, msec);
+
+ if (epoll_result < 0) {
+ if (errno != EINTR) {
+ iohandler_log(IOLOG_FATAL, "epoll_wait() failed with errno %d: %s", errno, strerror(errno));
+ return;
+ }
+ } else {
+ int i;
+ for(i = 0; i < epoll_result; i++) {
+ events = evts[i].events;
+ iohandler_events(evts[i].data.ptr, (events & (EPOLLIN | EPOLLHUP)), (events & EPOLLOUT));
+ }
+ }
+
+ //check timers
+ while(timer_priority) {
+ tdiff.tv_sec = timer_priority->timeout.tv_sec - now.tv_sec;
+ tdiff.tv_usec = timer_priority->timeout.tv_usec - now.tv_usec;
+ if(tdiff.tv_sec < 0 || (tdiff.tv_sec == 0 && tdiff.tv_usec <= 0)) {
+ if(timer_priority->constant_timeout) {
+ tdiff.tv_sec = 0;
+ iohandler_set_timeout(timer_priority, &tdiff);
+ iohandler_events(timer_priority, 0, 0);
+ } else {
+ iohandler_events(timer_priority, 0, 0);
+ iohandler_close(timer_priority); //also sets timer_priority to the next timed element
+ }
+ continue;
+ }
+ break;
+ }
+
+}
+
+static void engine_epoll_cleanup() {
+ close(epoll_fd);
+}
+
+struct IOEngine engine_epoll = {
+ .name = "epoll",
+ .init = engine_epoll_init,
+ .add = engine_epoll_add,
+ .remove = engine_epoll_remove,
+ .update = engine_epoll_update,
+ .loop = engine_epoll_loop,
+ .cleanup = engine_epoll_cleanup,
+};
+
+#else
+
+struct IOEngine engine_epoll = {
+ .name = "epoll",
+ .init = NULL,
+ .add = NULL,
+ .remove = NULL,
+ .update = NULL,
+ .loop = NULL,
+ .cleanup = NULL,
+};
+
+#endif
--- /dev/null
+/* IOengine_kevent.c - IOMultiplexer
+ * Copyright (C) 2012 Philipp Kreil (pk910)
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+#include "IOEngine.h"
+
+#ifdef HAVE_SYS_EVENT_H
+#include <sys/event.h>
+#include <errno.h>
+
+#define MAX_EVENTS 32
+
+static int kevent_fd;
+
+static int engine_kevent_init() {
+ kevent_fd = kqueue();
+ if (kevent_fd < 0)
+ return 0;
+ return 1;
+}
+
+static void engine_kevent_add(struct IODescriptor *iofd) {
+ if(iofd->type == IOTYPE_TIMER) return;
+ //add descriptor to the kevent queue
+ struct kevent changes[2];
+ int nchanges = 0;
+ int res;
+
+ EV_SET(&changes[nchanges++], iofd->fd, EVFILT_READ, EV_ADD, 0, 0, iofd);
+ if (iohandler_wants_writes(iofd))
+ EV_SET(&changes[nchanges++], iofd->fd, EVFILT_WRITE, EV_ADD, 0, 0, iofd);
+
+ res = kevent(kevent_fd, changes, nchanges, NULL, 0, NULL);
+ if(res < 0)
+ iohandler_log(IOLOG_ERROR, "could not add IODescriptor %d to kevent queue. (returned: %d)", res);
+}
+
+static void engine_kevent_remove(struct IODescriptor *iofd) {
+ if(iofd->type == IOTYPE_TIMER) return;
+ struct kevent changes[2];
+ int nchanges = 0;
+
+ EV_SET(&changes[nchanges++], iofd->fd, EVFILT_READ, EV_DELETE, 0, 0, iofd);
+ EV_SET(&changes[nchanges++], iofd->fd, EVFILT_WRITE, EV_DELETE, 0, 0, iofd);
+ kevent(kevent_fd, changes, nchanges, NULL, 0, NULL);
+}
+
+static void engine_kevent_update(struct IODescriptor *iofd) {
+ if(iofd->type == IOTYPE_TIMER) return;
+ if(iofd->state == IO_CLOSED) {
+ engine_kevent_remove(iofd);
+ return;
+ }
+ struct kevent changes[2];
+ int nchanges = 0;
+ int res;
+
+ EV_SET(&changes[nchanges++], iofd->fd, EVFILT_READ, EV_ADD, 0, 0, iofd);
+ EV_SET(&changes[nchanges++], iofd->fd, EVFILT_WRITE, iohandler_wants_writes(iofd) ? EV_ADD : EV_DELETE, 0, 0, iofd);
+
+ res = kevent(kevent_fd, changes, nchanges, NULL, 0, NULL);
+ if(res < 0) {
+ iohandler_log(IOLOG_ERROR, "could not update IODescriptor %d in kevent queue. (returned: %d)", res);
+ }
+}
+
+static void engine_kevent_loop(struct timeval *timeout) {
+ struct kevent events[MAX_EVENTS];
+ struct timeval now, tdiff;
+ struct timespec ts, *pts;
+ int msec;
+ int kevent_result;
+
+ gettimeofday(&now, NULL);
+
+ while(timer_priority) {
+ tdiff.tv_sec = timer_priority->timeout.tv_sec - now.tv_sec;
+ tdiff.tv_usec = timer_priority->timeout.tv_usec - now.tv_usec;
+ if(tdiff.tv_sec < 0 || (tdiff.tv_sec == 0 && tdiff.tv_usec <= 0)) {
+ if(timer_priority->constant_timeout) {
+ tdiff.tv_sec = 0;
+ iohandler_set_timeout(timer_priority, &tdiff);
+ iohandler_events(timer_priority, 0, 0);
+ } else {
+ iohandler_events(timer_priority, 0, 0);
+ iohandler_close(timer_priority); //also sets timer_priority to the next timed element
+ }
+ continue;
+ } else if(tdiff.tv_usec < 0) {
+ tdiff.tv_sec--;
+ tdiff.tv_usec += 1000000; //1 sec
+ }
+ if(timeval_is_smaler((&tdiff), timeout)) {
+ timeout->tv_sec = tdiff.tv_sec;
+ timeout->tv_usec = tdiff.tv_usec;
+ }
+ break;
+ }
+
+ if (timeout) {
+ ts.tv_sec = timeout->tv_sec;
+ ts.tv_nsec = timeout->tv_usec * 1000;
+ pts = &ts;
+ } else {
+ pts = NULL;
+ }
+
+ //select system call
+ kevent_result = kevent(kevent_fd, NULL, 0, events, MAX_EVENTS, pts);
+
+ if (kevent_result < 0) {
+ if (errno != EINTR) {
+ iohandler_log(IOLOG_FATAL, "kevent() failed with errno %d: %s", errno, strerror(errno));
+ return;
+ }
+ } else {
+ int i;
+ for(i = 0; i < kevent_result; i++)
+ iohandler_events(events[i].udata, (events[i].filter == EVFILT_READ), (events[i].filter == EVFILT_WRITE));
+ }
+
+ //check timers
+ while(timer_priority) {
+ tdiff.tv_sec = timer_priority->timeout.tv_sec - now.tv_sec;
+ tdiff.tv_usec = timer_priority->timeout.tv_usec - now.tv_usec;
+ if(tdiff.tv_sec < 0 || (tdiff.tv_sec == 0 && tdiff.tv_usec <= 0)) {
+ if(timer_priority->constant_timeout) {
+ tdiff.tv_sec = 0;
+ iohandler_set_timeout(timer_priority, &tdiff);
+ iohandler_events(timer_priority, 0, 0);
+ } else {
+ iohandler_events(timer_priority, 0, 0);
+ iohandler_close(timer_priority); //also sets timer_priority to the next timed element
+ }
+ continue;
+ }
+ break;
+ }
+
+}
+
+static void engine_kevent_cleanup() {
+ close(kevent_fd);
+}
+
+struct IOEngine engine_kevent = {
+ .name = "kevent",
+ .init = engine_kevent_init,
+ .add = engine_kevent_add,
+ .remove = engine_kevent_remove,
+ .update = engine_kevent_update,
+ .loop = engine_kevent_loop,
+ .cleanup = engine_kevent_cleanup,
+};
+
+#else
+
+struct IOEngine engine_kevent = {
+ .name = "kevent",
+ .init = NULL,
+ .add = NULL,
+ .remove = NULL,
+ .update = NULL,
+ .loop = NULL,
+ .cleanup = NULL,
+};
+
+#endif
--- /dev/null
+/* IOEngine_select.c - IOMultiplexer
+ * Copyright (C) 2012 Philipp Kreil (pk910)
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+#include "IOEngine.h"
+#include <errno.h>
+#include <time.h>
+#ifdef WIN32
+#define _WIN32_WINNT 0x501
+#include <windows.h>
+#include <winsock2.h>
+#else
+#include <string.h>
+#include <stdio.h>
+#endif
+
+static int engine_select_timer_delay_fix;
+
+static int engine_select_init() {
+ engine_select_timer_delay_fix = 0;
+ return 1;
+}
+
+static void engine_select_add(struct IODescriptor *iofd) {
+ #ifdef WIN32
+ if(iofd->type == IOTYPE_STDIN)
+ SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE),ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT);
+ #endif
+ /* empty */
+}
+
+static void engine_select_remove(struct IODescriptor *iofd) {
+ /* empty */
+}
+
+static void engine_select_update(struct IODescriptor *iofd) {
+ /* empty */
+}
+
+static void engine_select_loop(struct timeval *timeout) {
+ fd_set read_fds;
+ fd_set write_fds;
+ unsigned int fds_size = 0;
+ struct IODescriptor *iofd, *tmp_iofd;
+ struct timeval now, tdiff;
+ int select_result;
+ int timer_fix;
+
+ gettimeofday(&now, NULL);
+
+ //clear fds
+ FD_ZERO(&read_fds);
+ FD_ZERO(&write_fds);
+
+ select_result = 0;
+ for(iofd = first_descriptor; iofd; iofd = tmp_iofd) {
+ tmp_iofd = iofd->next;
+ if(iofd->type == IOTYPE_STDIN) {
+ #ifdef WIN32
+ //WIN32 doesn't support stdin within select
+ //just try to read the single events from the console
+ DWORD dwRead;
+ INPUT_RECORD inRecords[128];
+ unsigned int i;
+ int read_bytes = 0;
+ GetNumberOfConsoleInputEvents(GetStdHandle(STD_INPUT_HANDLE), &dwRead);
+ if(dwRead)
+ ReadConsoleInput(GetStdHandle(STD_INPUT_HANDLE), &inRecords[0], 128, &dwRead);
+ for (i = 0; i < dwRead; ++i) {
+ if (inRecords[i].EventType == KEY_EVENT) {
+ const char c = inRecords[i].Event.KeyEvent.uChar.AsciiChar;
+ if (inRecords[i].Event.KeyEvent.bKeyDown && c != 0) {
+ iofd->readbuf.buffer[iofd->readbuf.bufpos + read_bytes] = c;
+ read_bytes++;
+ }
+ }
+ }
+ if(read_bytes)
+ iohandler_events(iofd, read_bytes, 0);
+ if(read_bytes >= 128) {
+ timeout->tv_sec = 0;
+ timeout->tv_usec = 1;
+ //minimal timeout
+ } else {
+ timeout->tv_sec = 0;
+ timeout->tv_usec = 100000;
+ }
+ #else
+ if(iofd->fd > fds_size)
+ fds_size = iofd->fd;
+ FD_SET(iofd->fd, &read_fds);
+ select_result++;
+ #endif
+ }
+ else if(iofd->type == IOTYPE_SERVER || iofd->type == IOTYPE_CLIENT) {
+ if(iofd->state == IO_CLOSED)
+ continue;
+ if(iofd->fd > fds_size)
+ fds_size = iofd->fd;
+ FD_SET(iofd->fd, &read_fds);
+ select_result++;
+ if(iohandler_wants_writes(iofd))
+ FD_SET(iofd->fd, &write_fds);
+ }
+ }
+
+ while(timer_priority) {
+ tdiff.tv_sec = timer_priority->timeout.tv_sec - now.tv_sec;
+ tdiff.tv_usec = timer_priority->timeout.tv_usec - now.tv_usec;
+ if(tdiff.tv_sec < 0 || (tdiff.tv_sec == 0 && tdiff.tv_usec <= 0)) {
+ if(timer_priority->constant_timeout) {
+ tdiff.tv_sec = 0;
+ iohandler_set_timeout(timer_priority, &tdiff);
+ iohandler_events(timer_priority, 0, 0);
+ } else {
+ iohandler_events(timer_priority, 0, 0);
+ iohandler_close(timer_priority); //also sets timer_priority to the next timed element
+ }
+ continue;
+ } else if(tdiff.tv_usec < 0) {
+ tdiff.tv_sec--;
+ tdiff.tv_usec += 1000000; //1 sec
+ }
+ if(timeval_is_smaler((&tdiff), timeout)) {
+ timeout->tv_sec = tdiff.tv_sec;
+ timeout->tv_usec = tdiff.tv_usec + engine_select_timer_delay_fix;
+ if(timeout->tv_usec < 0) {
+ timeout->tv_sec--;
+ timeout->tv_usec += 1000000;
+ }
+ }
+ break;
+ }
+
+ if(select_result) {
+ //select system call
+ select_result = select(fds_size + 1, &read_fds, &write_fds, NULL, timeout);
+ } else {
+ #ifdef WIN32
+ Sleep((timeout->tv_sec * 1000) + (timeout->tv_usec / 1000) + 1);
+ #else
+ struct timespec usleep_time;
+ usleep_time.tv_sec = timeout->tv_sec;
+ usleep_time.tv_nsec = timeout->tv_usec * 1000;
+ nanosleep(&usleep_time, NULL);
+ #endif
+ }
+
+ if (select_result < 0) {
+ if (errno != EINTR) {
+ iohandler_log(IOLOG_FATAL, "select() failed with errno %d %d: %s", select_result, errno, strerror(errno));
+ return;
+ }
+ }
+
+ gettimeofday(&now, NULL);
+
+ //check all descriptors
+ for(iofd = first_descriptor; iofd; iofd = tmp_iofd) {
+ tmp_iofd = iofd->next;
+ if(iofd->type == IOTYPE_SERVER || iofd->type == IOTYPE_CLIENT || iofd->type == IOTYPE_STDIN) {
+ if(FD_ISSET(iofd->fd, &read_fds) || FD_ISSET(iofd->fd, &write_fds)) {
+ iohandler_events(iofd, FD_ISSET(iofd->fd, &read_fds), FD_ISSET(iofd->fd, &write_fds));
+ continue;
+ }
+ }
+ }
+
+ //check timers
+ while(timer_priority) {
+ tdiff.tv_sec = timer_priority->timeout.tv_sec - now.tv_sec;
+ tdiff.tv_usec = timer_priority->timeout.tv_usec - now.tv_usec;
+ timer_fix = (tdiff.tv_sec * 1000000) + tdiff.tv_usec;
+ if(timer_fix <= 100) {
+ if(timer_fix + 100 < engine_select_timer_delay_fix || timer_fix - 100 > engine_select_timer_delay_fix) {
+ engine_select_timer_delay_fix = ((engine_select_timer_delay_fix * 19) + timer_fix) / 20;
+ iohandler_log(IOLOG_DEBUG, "timer delay fix set to: %d us", engine_select_timer_delay_fix);
+ }
+ if(timer_priority->constant_timeout) {
+ tdiff.tv_sec = 0;
+ iohandler_set_timeout(timer_priority, &tdiff);
+ iohandler_events(timer_priority, 0, 0);
+ } else {
+ iohandler_events(timer_priority, 0, 0);
+ iohandler_close(timer_priority); //also sets timer_priority to the next timed element
+ }
+ continue;
+ }
+ break;
+ }
+
+}
+
+static void engine_select_cleanup() {
+ /* empty */
+}
+
+struct IOEngine engine_select = {
+ .name = "select",
+ .init = engine_select_init,
+ .add = engine_select_add,
+ .remove = engine_select_remove,
+ .update = engine_select_update,
+ .loop = engine_select_loop,
+ .cleanup = engine_select_cleanup,
+};
--- /dev/null
+/* IOEngine_win32.c - IOMultiplexer
+ * Copyright (C) 2012 Philipp Kreil (pk910)
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+#include "IOEngine.h"
+
+#ifdef WIN32
+
+#define _WIN32_WINNT 0x501
+#include <windows.h>
+#include <winsock2.h>
+
+/* This is massively kludgy. Unfortunately, the only performant I/O
+ * multiplexer with halfway decent semantics under Windows is
+ * WSAAsyncSelect() -- which requires a window that can receive
+ * messages.
+ *
+ * So ioset_win32_init() creates a hidden window and sets it up for
+ * asynchronous socket notifications.
+ */
+
+#define IDT_TIMER1 1000
+#define IDT_TIMER2 1001
+#define IDT_SOCKET 1002
+
+static HWND ioset_window;
+
+static struct IODescriptor *engine_win32_get_iofd(int fd) {
+ struct IODescriptor *iofd;
+ for(iofd = first_descriptor; iofd; iofd = iofd->next) {
+ if(iofd->fd == fd)
+ return iofd;
+ }
+ return NULL;
+}
+
+static LRESULT CALLBACK engine_win32_wndproc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
+ struct IODescriptor *iofd;
+ int events;
+ struct timeval now, tdiff;
+
+ gettimeofday(&now, NULL);
+
+ if (hWnd == ioset_window) switch (uMsg)
+ {
+ case IDT_TIMER1:
+ return 0;
+ case IDT_TIMER2:
+ //User Timer
+ while(timer_priority) {
+ tdiff.tv_sec = timer_priority->timeout.tv_sec - now.tv_sec;
+ tdiff.tv_usec = timer_priority->timeout.tv_usec - now.tv_usec;
+ if(tdiff.tv_sec < 0 || (tdiff.tv_sec == 0 && tdiff.tv_usec <= 0)) {
+ if(timer_priority->constant_timeout) {
+ tdiff.tv_sec = 0;
+ iohandler_set_timeout(timer_priority, &tdiff);
+ iohandler_events(timer_priority, 0, 0);
+ } else {
+ iohandler_events(timer_priority, 0, 0);
+ iohandler_close(timer_priority); //also sets timer_priority to the next timed element
+ }
+ continue;
+ }
+ break;
+ }
+ return 0;
+ case IDT_SOCKET:
+ iofd = engine_win32_get_iofd(wParam);
+ events = WSAGETSELECTEVENT(lParam);
+
+ iohandler_events(iofd, (events & (FD_READ | FD_ACCEPT | FD_CLOSE)) != 0, (events & (FD_WRITE | FD_CONNECT)) != 0);
+ return 0;
+ case WM_QUIT:
+ return 0;
+ }
+ return DefWindowProc(hWnd, uMsg, wParam, lParam);
+}
+
+static int engine_win32_init() {
+ WNDCLASSEX wcx;
+ HINSTANCE hinst;
+ WSADATA wsadata;
+
+ // Start Windows Sockets.
+ if (WSAStartup(MAKEWORD(2, 0), &wsadata)) {
+ iohandler_log(IOLOG_FATAL, "Unable to start Windows Sockets");
+ return 0;
+ }
+
+ // Get Windows HINSTANCE.
+ hinst = GetModuleHandle(NULL);
+
+ // Describe and register a window class.
+ memset(&wcx, 0, sizeof(wcx));
+ wcx.cbSize = sizeof(wcx);
+ wcx.lpfnWndProc = engine_win32_wndproc;
+ wcx.hInstance = hinst;
+ wcx.lpszClassName = "IOMultiplexerMainWindow";
+ if (!RegisterClassEx(&wcx))
+ return 0;
+
+ ioset_window = CreateWindow("IOMultiplexerMainWindow", "IOMultiplexer", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hinst, NULL);
+ if (!ioset_window)
+ return 0;
+ return 1;
+}
+
+static long engine_win32_events(struct IODescriptor *iofd) {
+ switch (iofd->state) {
+ case IO_CLOSED:
+ return 0;
+ case IO_LISTENING:
+ return FD_ACCEPT;
+ case IO_CONNECTING:
+ return FD_CONNECT;
+ case IO_CONNECTED:
+ case IO_SSLWAIT:
+ return FD_READ | FD_CLOSE | (iohandler_wants_writes(iofd) ? FD_WRITE : 0);
+ }
+ return 0;
+}
+
+static void engine_win32_update(struct IODescriptor *iofd) {
+ long events;
+
+ if(iofd->type == IOTYPE_STDIN)
+ return;
+
+ events = engine_win32_events(iofd);
+ WSAAsyncSelect(iofd->fd, ioset_window, IDT_SOCKET, events);
+}
+
+static void engine_win32_add(struct IODescriptor *iofd) {
+ if(iofd->type == IOTYPE_STDIN)
+ return;
+
+ engine_win32_update(iofd);
+}
+
+static void engine_win32_remove(struct IODescriptor *iofd) {
+ unsigned long ulong;
+
+ if(iofd->type == IOTYPE_STDIN)
+ return;
+
+ WSAAsyncSelect(iofd->fd, ioset_window, IDT_SOCKET, 0);
+
+ ulong = 0;
+ ioctlsocket(iofd->fd, FIONBIO, &ulong);
+}
+
+static void engine_win32_loop(struct timeval *timeout) {
+ MSG msg;
+ BOOL not_really_bool;
+ int msec, cmsec, sett2;
+ struct timeval now, tdiff;
+ struct IODescriptor *iofd, *tmp_iofd;
+
+ gettimeofday(&now, NULL);
+
+ for(iofd = first_descriptor; iofd; iofd = tmp_iofd) {
+ tmp_iofd = iofd->next;
+ if(iofd->type == IOTYPE_STDIN) {
+ #ifdef WIN32
+ //WIN32 doesn't support stdin within select
+ //just try to read the single events from the console
+ DWORD dwRead;
+ INPUT_RECORD inRecords[128];
+ unsigned int i;
+ int read_bytes = 0;
+ GetNumberOfConsoleInputEvents(GetStdHandle(STD_INPUT_HANDLE), &dwRead);
+ if(dwRead)
+ ReadConsoleInput(GetStdHandle(STD_INPUT_HANDLE), &inRecords[0], 128, &dwRead);
+ for (i = 0; i < dwRead; ++i) {
+ if (inRecords[i].EventType == KEY_EVENT) {
+ const char c = inRecords[i].Event.KeyEvent.uChar.AsciiChar;
+ if (inRecords[i].Event.KeyEvent.bKeyDown && c != 0) {
+ iofd->readbuf.buffer[iofd->readbuf.bufpos + read_bytes] = c;
+ read_bytes++;
+ }
+ }
+ }
+ if(read_bytes)
+ iohandler_events(iofd, read_bytes, 0);
+ if(read_bytes >= 128) {
+ timeout->tv_sec = 0;
+ timeout->tv_usec = 1;
+ //minimal timeout
+ } else {
+ timeout->tv_sec = 0;
+ timeout->tv_usec = 100000;
+ }
+ #else
+ if(iofd->fd > fds_size)
+ fds_size = iofd->fd;
+ FD_SET(iofd->fd, &read_fds);
+ #endif
+ }
+ }
+
+ // Make sure we are woken up after the appropriate time.
+ msec = (timeout->tv_sec * 1000) + (timeout->tv_usec / 1000);
+ SetTimer(ioset_window, IDT_TIMER1, msec, NULL);
+
+ //set additional User Timer (if ther's one)
+ sett2 = 0;
+ while(timer_priority) {
+ tdiff.tv_sec = timer_priority->timeout.tv_sec - now.tv_sec;
+ tdiff.tv_usec = timer_priority->timeout.tv_usec - now.tv_usec;
+ if(tdiff.tv_sec < 0 || (tdiff.tv_sec == 0 && tdiff.tv_usec < 100)) {
+ if(timer_priority->constant_timeout) {
+ tdiff.tv_sec = 0;
+ iohandler_set_timeout(timer_priority, &tdiff);
+ iohandler_events(timer_priority, 0, 0);
+ } else {
+ iohandler_events(timer_priority, 0, 0);
+ iohandler_close(timer_priority); //also sets timer_priority to the next timed element
+ }
+ continue;
+ } else if(tdiff.tv_usec < 0) {
+ tdiff.tv_sec--;
+ tdiff.tv_usec += 1000000; //1 sec
+ }
+ cmsec = (tdiff.tv_sec * 1000) + (tdiff.tv_usec / 1000);
+ if(cmsec < msec) {
+ sett2 = 1;
+ msec = cmsec;
+ }
+ break;
+ }
+ if(sett2)
+ SetTimer(ioset_window, IDT_TIMER2, msec, NULL);
+
+ // Do a blocking read of the message queue.
+ not_really_bool = GetMessage(&msg, NULL, 0, 0);
+ KillTimer(ioset_window, IDT_TIMER1);
+ if(sett2)
+ KillTimer(ioset_window, IDT_TIMER2);
+ if (not_really_bool <=0)
+ return;
+ else {
+ TranslateMessage(&msg);
+ DispatchMessage(&msg);
+ }
+}
+
+static void engine_win32_cleanup() {
+ DestroyWindow(ioset_window);
+ ioset_window = NULL;
+ WSACleanup();
+}
+
+struct IOEngine engine_win32 = {
+ .name = "win32",
+ .init = engine_win32_init,
+ .add = engine_win32_add,
+ .remove = engine_win32_remove,
+ .update = engine_win32_update,
+ .loop = engine_win32_loop,
+ .cleanup = engine_win32_cleanup,
+};
+
+#else
+
+struct IOEngine engine_win32 = {
+ .name = "win32",
+ .init = NULL,
+ .add = NULL,
+ .remove = NULL,
+ .update = NULL,
+ .loop = NULL,
+ .cleanup = NULL,
+};
+
+#endif
--- /dev/null
+/* IOHandler.c - IOMultiplexer
+ * Copyright (C) 2012 Philipp Kreil (pk910)
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+#include "IOHandler.h"
+#include "IOEngine.h"
+#include "IOHandler_SSL.h"
+#include <errno.h>
+#include <stdio.h>
+#include <unistd.h>
+#ifdef WIN32
+#define _WIN32_WINNT 0x501
+#include <windows.h>
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#else
+#include <signal.h>
+#include <stdarg.h>
+#include <stdlib.h>
+#include <string.h>
+#include <netdb.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <netinet/tcp.h>
+#include <fcntl.h>
+#endif
+
+#ifndef EWOULDBLOCK
+#define EWOULDBLOCK EAGAIN
+#endif
+
+#define MAXLOG 1024
+iohandler_log_callback *iolog_backend = NULL;
+
+struct IODescriptor *first_descriptor = NULL;
+struct IODescriptor *timer_priority = NULL;
+
+#ifdef HAVE_PTHREAD_H
+static pthread_mutex_t io_thread_sync;
+static pthread_mutex_t io_poll_sync;
+#endif
+
+void iohandler_log(enum IOLogType type, char *text, ...) {
+ va_list arg_list;
+ char logBuf[MAXLOG+1];
+ int pos;
+ logBuf[0] = '\0';
+ va_start(arg_list, text);
+ pos = vsnprintf(logBuf, MAXLOG - 1, text, arg_list);
+ va_end(arg_list);
+ if (pos < 0 || pos > (MAXLOG - 1)) pos = MAXLOG - 1;
+ logBuf[pos] = '\n';
+ logBuf[pos+1] = '\0';
+
+ if(iolog_backend)
+ iolog_backend(type, logBuf);
+}
+
+/* IO Engines */
+extern struct IOEngine engine_select; /* select system call (should always be useable) */
+extern struct IOEngine engine_kevent;
+extern struct IOEngine engine_epoll;
+extern struct IOEngine engine_win32;
+
+int iohandler_settings = 0;
+struct IOEngine *engine = NULL;
+
+void iohandler_set(int setting, int value) {
+ if(value)
+ iohandler_settings |= setting;
+ else
+ iohandler_settings &= ~setting;
+}
+
+static void iohandler_init_engine() {
+ if(engine) return;
+ IOTHREAD_MUTEX_INIT(io_thread_sync);
+ IOTHREAD_MUTEX_INIT(io_poll_sync);
+
+ //try other engines
+ if(!(iohandler_settings & IOHANDLER_SETTING_HIGH_PRECISION_TIMER)) {
+ if(!engine && engine_kevent.init && engine_kevent.init())
+ engine = &engine_kevent;
+ if(!engine && engine_epoll.init && engine_epoll.init())
+ engine = &engine_epoll;
+ if(!engine && engine_win32.init && engine_win32.init())
+ engine = &engine_win32;
+ }
+
+ if (!engine) {
+ if(engine_select.init())
+ engine = &engine_select;
+ else {
+ iohandler_log(IOLOG_FATAL, "found no useable IO engine");
+ return;
+ }
+ }
+ iohandler_log(IOLOG_DEBUG, "using %s IO engine", engine->name);
+ iohandler_ssl_init();
+}
+
+static void iohandler_append(struct IODescriptor *descriptor) {
+ IOSYNCHRONIZE(io_thread_sync);
+ struct timeval *timeout = ((descriptor->timeout.tv_sec || descriptor->timeout.tv_usec) ? &descriptor->timeout : NULL);
+ if(timeout) {
+ struct IODescriptor *iofd;
+ int set_priority = 1;
+ descriptor->timeout = *timeout;
+ if(timer_priority)
+ iofd = timer_priority;
+ else
+ iofd = first_descriptor;
+ if(iofd) {
+ for(;;iofd = iofd->next) {
+ if(timeval_is_smaler(timeout, (&iofd->timeout))) {
+ descriptor->prev = iofd->prev;
+ descriptor->next = iofd;
+ if(iofd->prev)
+ iofd->prev->next = descriptor;
+ iofd->prev = descriptor;
+ if(set_priority)
+ timer_priority = descriptor;
+ break;
+ }
+ if(iofd == timer_priority)
+ set_priority = 0;
+ if(iofd->next == NULL) {
+ descriptor->next = NULL;
+ descriptor->prev = iofd;
+ iofd->next = descriptor;
+ if(set_priority)
+ timer_priority = descriptor;
+ break;
+ }
+ }
+ } else {
+ descriptor->prev = NULL;
+ descriptor->next = NULL;
+ first_descriptor = descriptor;
+ timer_priority = descriptor;
+ }
+
+ } else {
+ descriptor->prev = NULL;
+ descriptor->next = first_descriptor;
+ if(first_descriptor)
+ first_descriptor->prev = descriptor;
+ first_descriptor = descriptor;
+ }
+ IODESYNCHRONIZE(io_thread_sync);
+}
+
+static void iohandler_remove(struct IODescriptor *descriptor, int engine_remove) {
+ //remove IODescriptor from the list
+ IOSYNCHRONIZE(io_thread_sync);
+ if(descriptor->prev)
+ descriptor->prev->next = descriptor->next;
+ else
+ first_descriptor = descriptor->next;
+ if(descriptor->next)
+ descriptor->next->prev = descriptor->prev;
+ if(descriptor == timer_priority)
+ timer_priority = descriptor->next;
+
+ if(engine_remove)
+ engine->remove(descriptor);
+ if(descriptor->readbuf.buffer)
+ free(descriptor->readbuf.buffer);
+ if(descriptor->writebuf.buffer)
+ free(descriptor->writebuf.buffer);
+ iohandler_log(IOLOG_DEBUG, "removed IODescriptor (%d) of type `%s`", descriptor->fd, iohandler_iotype_name(descriptor->type));
+ free(descriptor);
+ IODESYNCHRONIZE(io_thread_sync);
+}
+
+struct IODescriptor *iohandler_add(int sockfd, enum IOType type, struct timeval *timeout, iohandler_callback *callback) {
+ //just add a new IODescriptor
+ struct IODescriptor *descriptor = calloc(1, sizeof(*descriptor));
+ if(!descriptor) {
+ iohandler_log(IOLOG_ERROR, "could not allocate memory for IODescriptor in %s:%d", __FILE__, __LINE__);
+ return NULL;
+ }
+ descriptor->fd = (type == IOTYPE_STDIN ? fileno(stdin) : sockfd);
+ descriptor->type = type;
+ descriptor->state = (type == IOTYPE_STDIN ? IO_CONNECTED : IO_CLOSED);
+ descriptor->callback = callback;
+ if(timeout) {
+ descriptor->timeout = *timeout;
+ if(descriptor->timeout.tv_usec > 1000000) {
+ descriptor->timeout.tv_usec -= 1000000;
+ descriptor->timeout.tv_sec++;
+ }
+ }
+ if(type != IOTYPE_TIMER) {
+ descriptor->readbuf.buffer = malloc(IO_READ_BUFLEN + 2);
+ descriptor->readbuf.bufpos = 0;
+ descriptor->readbuf.buflen = IO_READ_BUFLEN;
+ descriptor->writebuf.buffer = malloc(IO_READ_BUFLEN + 2);
+ descriptor->writebuf.bufpos = 0;
+ descriptor->writebuf.buflen = IO_READ_BUFLEN;
+ }
+
+ if(!engine) {
+ iohandler_init_engine();
+ if(!engine) {
+ return NULL;
+ }
+ }
+ engine->add(descriptor);
+
+ //add IODescriptor to the list
+ iohandler_append(descriptor);
+
+ iohandler_log(IOLOG_DEBUG, "added custom socket descriptor (%d) as type `%s`", sockfd, iohandler_iotype_name(type));
+ return descriptor;
+}
+
+void iohandler_set_timeout(struct IODescriptor *descriptor, struct timeval *timeout) {
+ if(descriptor->prev)
+ descriptor->prev->next = descriptor->next;
+ else
+ first_descriptor = descriptor->next;
+ if(descriptor->next)
+ descriptor->next->prev = descriptor->prev;
+ if(descriptor == timer_priority)
+ timer_priority = descriptor->next;
+ if(timeout && timeout->tv_sec == 0 && descriptor->constant_timeout) {
+ descriptor->timeout.tv_usec += (descriptor->constant_timeout % 1000) * 1000;
+ descriptor->timeout.tv_sec += (descriptor->constant_timeout / 1000);
+ if(descriptor->timeout.tv_usec > 1000000) {
+ descriptor->timeout.tv_sec += (descriptor->timeout.tv_usec / 1000000);
+ descriptor->timeout.tv_usec %= 1000000;
+ }
+ } else if(timeout) {
+ descriptor->timeout = *timeout;
+ if(descriptor->timeout.tv_usec > 1000000) {
+ descriptor->timeout.tv_usec -= 1000000;
+ descriptor->timeout.tv_sec++;
+ }
+ } else {
+ descriptor->timeout.tv_sec = 0;
+ descriptor->timeout.tv_usec = 0;
+ }
+ iohandler_append(descriptor);
+}
+
+static void iohandler_increase_iobuf(struct IOBuffer *iobuf, size_t required) {
+ if(iobuf->buflen >= required) return;
+ char *new_buf = realloc(iobuf->buffer, required + 2);
+ if(new_buf) {
+ iobuf->buffer = new_buf;
+ iobuf->buflen = required;
+ }
+}
+
+struct IODescriptor *iohandler_timer(struct timeval timeout, iohandler_callback *callback) {
+ struct IODescriptor *descriptor;
+ descriptor = iohandler_add(-1, IOTYPE_TIMER, &timeout, callback);
+ if(!descriptor) {
+ iohandler_log(IOLOG_ERROR, "could not allocate memory for IODescriptor in %s:%d", __FILE__, __LINE__);
+ return NULL;
+ }
+ iohandler_log(IOLOG_DEBUG, "added timer descriptor (sec: %d; usec: %d)", timeout.tv_sec, timeout.tv_usec);
+ return descriptor;
+}
+
+struct IODescriptor *iohandler_constant_timer(int msec, iohandler_callback *callback) {
+ struct IODescriptor *descriptor;
+ struct timeval timeout;
+ gettimeofday(&timeout, NULL);
+ timeout.tv_usec += (msec % 1000) * 1000;
+ timeout.tv_sec += (msec / 1000);
+ if(timeout.tv_usec > 1000000) {
+ timeout.tv_sec += (timeout.tv_usec / 1000000);
+ timeout.tv_usec %= 1000000;
+ }
+ descriptor = iohandler_add(-1, IOTYPE_TIMER, &timeout, callback);
+ if(!descriptor) {
+ iohandler_log(IOLOG_ERROR, "could not allocate memory for IODescriptor in %s:%d", __FILE__, __LINE__);
+ return NULL;
+ }
+ descriptor->constant_timeout = msec;
+ iohandler_log(IOLOG_DEBUG, "added timer descriptor (sec: %d; usec: %d)", timeout.tv_sec, timeout.tv_usec);
+ return descriptor;
+}
+
+struct IODescriptor *iohandler_connect(const char *hostname, unsigned int port, int ssl, const char *bindhost, iohandler_callback *callback) {
+ return iohandler_connect_flags(hostname, port, ssl, bindhost, callback, IOHANDLER_CONNECT_IPV4 | IOHANDLER_CONNECT_IPV6);
+}
+
+struct IODescriptor *iohandler_connect_flags(const char *hostname, unsigned int port, int ssl, const char *bindhost, iohandler_callback *callback, int flags) {
+ //non-blocking connect
+ int sockfd, result;
+ struct addrinfo hints, *res;
+ struct sockaddr_in *ip4 = NULL;
+ struct sockaddr_in6 *ip6 = NULL;
+ size_t dstaddrlen;
+ struct sockaddr *dstaddr = NULL;
+ struct IODescriptor *descriptor;
+
+ if(!engine) {
+ iohandler_init_engine();
+ if(!engine) return NULL;
+ }
+ memset (&hints, 0, sizeof (hints));
+ hints.ai_family = PF_UNSPEC;
+ hints.ai_socktype = SOCK_STREAM;
+ hints.ai_flags |= AI_CANONNAME;
+ if ((result = getaddrinfo (hostname, NULL, &hints, &res))) {
+ iohandler_log(IOLOG_ERROR, "could not resolve %s to an IP address (%d)", hostname, result);
+ return NULL;
+ }
+ while (res) {
+ switch (res->ai_family) {
+ case AF_INET:
+ ip4 = (struct sockaddr_in *) res->ai_addr;
+ break;
+ case AF_INET6:
+ ip6 = (struct sockaddr_in6 *) res->ai_addr;
+ break;
+ }
+ res = res->ai_next;
+ freeaddrinfo(res);
+ }
+
+ if(ip6 && (flags & IOHANDLER_CONNECT_IPV6)) {
+ sockfd = socket(AF_INET6, SOCK_STREAM, 0);
+ if(sockfd == -1) {
+ iohandler_log(IOLOG_ERROR, "could not create socket in %s:%d", __FILE__, __LINE__);
+ return NULL;
+ }
+
+ ip6->sin6_family = AF_INET6;
+ ip6->sin6_port = htons(port);
+
+ struct sockaddr_in6 *ip6vhost = NULL;
+ if (bindhost && !getaddrinfo(bindhost, NULL, &hints, &res)) {
+ while (res) {
+ switch (res->ai_family) {
+ case AF_INET6:
+ ip6vhost = (struct sockaddr_in6 *) res->ai_addr;
+ break;
+ }
+ res = res->ai_next;
+ freeaddrinfo(res);
+ }
+ }
+ if(ip6vhost) {
+ ip6vhost->sin6_family = AF_INET6;
+ ip6vhost->sin6_port = htons(0);
+ bind(sockfd, (struct sockaddr*)ip6vhost, sizeof(*ip6vhost));
+ }
+ dstaddr = (struct sockaddr*)ip6;
+ dstaddrlen = sizeof(*ip6);
+ } else if(ip4 && (flags & IOHANDLER_CONNECT_IPV4)) {
+ sockfd = socket(AF_INET, SOCK_STREAM, 0);
+ if(sockfd == -1) {
+ iohandler_log(IOLOG_ERROR, "could not create socket in %s:%d", __FILE__, __LINE__);
+ return NULL;
+ }
+
+ ip4->sin_family = AF_INET;
+ ip4->sin_port = htons(port);
+
+ struct sockaddr_in *ip4vhost = NULL;
+ if (bindhost && !getaddrinfo(bindhost, NULL, &hints, &res)) {
+ while (res) {
+ switch (res->ai_family) {
+ case AF_INET:
+ ip4vhost = (struct sockaddr_in *) res->ai_addr;
+ break;
+ }
+ res = res->ai_next;
+ freeaddrinfo(res);
+ }
+ }
+ if(ip4vhost) {
+ ip4vhost->sin_family = AF_INET;
+ ip4vhost->sin_port = htons(0);
+ bind(sockfd, (struct sockaddr*)ip4vhost, sizeof(*ip4vhost));
+ }
+ dstaddr = (struct sockaddr*)ip4;
+ dstaddrlen = sizeof(*ip4);
+ } else
+ return NULL;
+ //prevent SIGPIPE
+ #ifndef WIN32
+ #if defined(SO_NOSIGPIPE)
+ {
+ int set = 1;
+ setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&set, sizeof(int));
+ }
+ #else
+ signal(SIGPIPE, SIG_IGN);
+ #endif
+ #endif
+ //make sockfd unblocking
+ #if defined(F_GETFL)
+ {
+ int fcntl_flags;
+ fcntl_flags = fcntl(sockfd, F_GETFL);
+ fcntl(sockfd, F_SETFL, fcntl_flags|O_NONBLOCK);
+ fcntl_flags = fcntl(sockfd, F_GETFD);
+ fcntl(sockfd, F_SETFD, fcntl_flags|FD_CLOEXEC);
+ }
+ #else
+ /* I hope you're using the Win32 backend or something else that
+ * automatically marks the file descriptor non-blocking...
+ */
+ #endif
+ descriptor = iohandler_add(sockfd, IOTYPE_CLIENT, NULL, callback);
+ if(!descriptor) {
+ close(sockfd);
+ return NULL;
+ }
+ connect(sockfd, dstaddr, dstaddrlen); //returns EINPROGRESS here (nonblocking)
+ descriptor->state = IO_CONNECTING;
+ descriptor->ssl = (ssl ? 1 : 0);
+ descriptor->read_lines = 1;
+ engine->update(descriptor);
+ iohandler_log(IOLOG_DEBUG, "added client socket (%d) connecting to %s:%d", sockfd, hostname, port);
+ return descriptor;
+}
+
+struct IODescriptor *iohandler_listen(const char *hostname, unsigned int port, iohandler_callback *callback) {
+ return iohandler_listen_flags(hostname, port, callback, IOHANDLER_LISTEN_IPV4 | IOHANDLER_LISTEN_IPV6);
+}
+
+struct IODescriptor *iohandler_listen_flags(const char *hostname, unsigned int port, iohandler_callback *callback, int flags) {
+ int sockfd;
+ struct addrinfo hints, *res;
+ struct sockaddr_in *ip4 = NULL;
+ struct sockaddr_in6 *ip6 = NULL;
+ struct IODescriptor *descriptor;
+ unsigned int opt;
+
+ if(!engine) {
+ iohandler_init_engine();
+ if(!engine) return NULL;
+ }
+ memset (&hints, 0, sizeof (hints));
+ hints.ai_family = PF_UNSPEC;
+ hints.ai_socktype = SOCK_STREAM;
+ hints.ai_flags |= AI_CANONNAME;
+ if (getaddrinfo (hostname, NULL, &hints, &res)) {
+ return NULL;
+ }
+ while (res) {
+ switch (res->ai_family) {
+ case AF_INET:
+ ip4 = (struct sockaddr_in *) res->ai_addr;
+ break;
+ case AF_INET6:
+ ip6 = (struct sockaddr_in6 *) res->ai_addr;
+ break;
+ }
+ res = res->ai_next;
+ freeaddrinfo(res);
+ }
+
+ if(ip6 && (flags & IOHANDLER_LISTEN_IPV6)) {
+ sockfd = socket(AF_INET6, SOCK_STREAM, 0);
+ if(sockfd == -1) return NULL;
+
+ opt = 1;
+ setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt));
+
+ ip6->sin6_family = AF_INET6;
+ ip6->sin6_port = htons(port);
+
+ bind(sockfd, (struct sockaddr*)ip6, sizeof(*ip6));
+ } else if(ip4 && (flags & IOHANDLER_LISTEN_IPV4)) {
+ sockfd = socket(AF_INET, SOCK_STREAM, 0);
+ if(sockfd == -1) return NULL;
+
+ opt = 1;
+ setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt));
+
+ ip4->sin_family = AF_INET;
+ ip4->sin_port = htons(port);
+
+ bind(sockfd, (struct sockaddr*)ip4, sizeof(*ip4));
+ } else
+ return NULL;
+ //prevent SIGPIPE
+ #ifndef WIN32
+ #if defined(SO_NOSIGPIPE)
+ {
+ int set = 1;
+ setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&set, sizeof(int));
+ }
+ #else
+ signal(SIGPIPE, SIG_IGN);
+ #endif
+ #endif
+ //make sockfd unblocking
+ #if defined(F_GETFL)
+ {
+ int flag;
+ flag = fcntl(sockfd, F_GETFL);
+ fcntl(sockfd, F_SETFL, flag|O_NONBLOCK);
+ flag = fcntl(sockfd, F_GETFD);
+ fcntl(sockfd, F_SETFD, flag|FD_CLOEXEC);
+ }
+ #else
+ /* I hope you're using the Win32 backend or something else that
+ * automatically marks the file descriptor non-blocking...
+ */
+ #endif
+ descriptor = iohandler_add(sockfd, IOTYPE_SERVER, NULL, callback);
+ if(!descriptor) {
+ close(sockfd);
+ return NULL;
+ }
+ listen(sockfd, 1);
+ descriptor->state = IO_LISTENING;
+ engine->update(descriptor);
+ iohandler_log(IOLOG_DEBUG, "added server socket (%d) listening on %s:%d", sockfd, hostname, port);
+ return descriptor;
+}
+
+struct IODescriptor *iohandler_listen_ssl(const char *hostname, unsigned int port, const char *certfile, const char *keyfile, iohandler_callback *callback) {
+ return iohandler_listen_ssl_flags(hostname, port, certfile, keyfile, callback, IOHANDLER_LISTEN_IPV4 | IOHANDLER_LISTEN_IPV6);
+}
+
+struct IODescriptor *iohandler_listen_ssl_flags(const char *hostname, unsigned int port, const char *certfile, const char *keyfile, iohandler_callback *callback, int flags) {
+ struct IODescriptor *descriptor = iohandler_listen_flags(hostname, port, callback, flags);
+ if(!descriptor)
+ return NULL;
+ //SSL Server Socket
+ iohandler_ssl_listen(descriptor, certfile, keyfile);
+ if(descriptor->sslnode)
+ descriptor->ssl = 1;
+ return descriptor;
+}
+
+void iohandler_write(struct IODescriptor *iofd, const char *line) {
+ size_t linelen = strlen(line);
+ iohandler_send(iofd, line, linelen);
+}
+
+void iohandler_send(struct IODescriptor *iofd, const char *data, size_t datalen) {
+ if(iofd->type == IOTYPE_TIMER || iofd->state == IO_CLOSED) {
+ iohandler_log(IOLOG_ERROR, "could not write to socket (%s)", (iofd->type == IOTYPE_TIMER ? "IOTYPE_TIMER" : "IO_CLOSED"));
+ return;
+ }
+ iohandler_log(IOLOG_DEBUG, "add %d to writebuf (fd: %d): %s", datalen, iofd->fd, data);
+ if(iofd->writebuf.buflen < iofd->writebuf.bufpos + datalen) {
+ iohandler_log(IOLOG_DEBUG, "increase writebuf (curr: %d) to %d (+%d bytes)", iofd->writebuf.buflen, iofd->writebuf.bufpos + datalen, (iofd->writebuf.bufpos + datalen - iofd->writebuf.buflen));
+ iohandler_increase_iobuf(&iofd->writebuf, iofd->writebuf.bufpos + datalen);
+ if(iofd->writebuf.buflen < iofd->writebuf.bufpos + datalen) {
+ iohandler_log(IOLOG_ERROR, "increase writebuf (curr: %d) to %d (+%d bytes) FAILED", iofd->writebuf.buflen, iofd->writebuf.bufpos + datalen, (iofd->writebuf.bufpos + datalen - iofd->writebuf.buflen));
+ return;
+ }
+ }
+ memcpy(iofd->writebuf.buffer + iofd->writebuf.bufpos, data, datalen);
+ iofd->writebuf.bufpos += datalen;
+ engine->update(iofd);
+}
+
+void iohandler_printf(struct IODescriptor *iofd, const char *text, ...) {
+ va_list arg_list;
+ char sendBuf[IO_LINE_LEN];
+ int pos;
+ sendBuf[0] = '\0';
+ va_start(arg_list, text);
+ pos = vsnprintf(sendBuf, IO_LINE_LEN - 2, text, arg_list);
+ va_end(arg_list);
+ if (pos < 0 || pos > (IO_LINE_LEN - 2)) pos = IO_LINE_LEN - 2;
+ sendBuf[pos] = '\n';
+ sendBuf[pos+1] = '\0';
+ iohandler_send(iofd, sendBuf, pos+1);
+}
+
+static int iohandler_try_write(struct IODescriptor *iofd) {
+ if(!iofd->writebuf.bufpos) return 0;
+ iohandler_log(IOLOG_DEBUG, "write writebuf (%d bytes) to socket (fd: %d)", iofd->writebuf.bufpos, iofd->fd);
+ int res;
+ if(iofd->ssl_active)
+ res = iohandler_ssl_write(iofd, iofd->writebuf.buffer, iofd->writebuf.bufpos);
+ else
+ res = send(iofd->fd, iofd->writebuf.buffer, iofd->writebuf.bufpos, 0);
+ if(res < 0) {
+ if (errno != EAGAIN && errno != EWOULDBLOCK)
+ iohandler_log(IOLOG_ERROR, "could not write to socket (fd: %d): %d - %s", iofd->fd, errno, strerror(errno));
+ else
+ res = 0;
+ } else {
+ iofd->writebuf.bufpos -= res;
+ if(iofd->state != IO_CLOSED)
+ engine->update(iofd);
+ }
+ return res;
+}
+
+void iohandler_close(struct IODescriptor *iofd) {
+ int engine_remove = 1;
+ iofd->state = IO_CLOSED;
+ if(iofd->writebuf.bufpos) {
+ //try to send everything before closing
+#if defined(F_GETFL)
+ {
+ int flags;
+ flags = fcntl(iofd->fd, F_GETFL);
+ fcntl(iofd->fd, F_SETFL, flags & ~O_NONBLOCK);
+ flags = fcntl(iofd->fd, F_GETFD);
+ fcntl(iofd->fd, F_SETFD, flags|FD_CLOEXEC);
+ }
+#else
+ engine_remove = 0;
+ engine->remove(iofd);
+#endif
+ iohandler_try_write(iofd);
+ }
+ //close IODescriptor
+ if(iofd->ssl)
+ iohandler_ssl_disconnect(iofd);
+ if(iofd->type == IOTYPE_SERVER || iofd->type == IOTYPE_CLIENT || iofd->type == IOTYPE_STDIN)
+ close(iofd->fd);
+ iohandler_remove(iofd, engine_remove);
+}
+
+void iohandler_update(struct IODescriptor *iofd) {
+ iohandler_log(IOLOG_DEBUG, "external call to iohandler_update (fd: %d)", iofd->fd);
+ engine->update(iofd);
+}
+
+static void iohandler_trigger_event(struct IOEvent *event) {
+ if(!event->iofd->callback) return;
+ iohandler_log(IOLOG_DEBUG, "triggering event (%s) for %s (fd: %d)", iohandler_ioeventtype_name(event->type), iohandler_iotype_name(event->iofd->type), event->iofd->fd);
+ event->iofd->callback(event);
+}
+
+void iohandler_events(struct IODescriptor *iofd, int readable, int writeable) {
+ struct IOEvent callback_event;
+ callback_event.type = IOEVENT_IGNORE;
+ callback_event.iofd = iofd;
+ switch(iofd->state) {
+ case IO_SSLWAIT:
+ if(!readable && !writeable) {
+ if(!iofd->ssl_server_hs) {
+ callback_event.type = IOEVENT_SSLFAILED;
+ iofd->state = IO_CLOSED;
+ engine->update(iofd);
+ } else
+ iohandler_close(iofd);
+ } else if(iofd->ssl_server_hs) {
+ iohandler_log(IOLOG_DEBUG, "triggering iohandler_ssl_server_handshake for %s (fd: %d)", iohandler_iotype_name(iofd->type), iofd->fd);
+ iohandler_ssl_server_handshake(iofd);
+ } else {
+ iohandler_log(IOLOG_DEBUG, "triggering iohandler_ssl_client_handshake for %s (fd: %d)", iohandler_iotype_name(iofd->type), iofd->fd);
+ iohandler_ssl_client_handshake(iofd);
+ }
+ break;
+ case IO_CLOSED:
+ if(iofd->type == IOTYPE_TIMER)
+ callback_event.type = IOEVENT_TIMEOUT;
+ break;
+ case IO_LISTENING:
+ if(readable) {
+ callback_event.data.accept_fd = accept(iofd->fd, NULL, 0);
+ if(callback_event.data.accept_fd < 0) {
+ iohandler_log(IOLOG_ERROR, "could not accept client (server fd: %d): %d - %s", iofd->fd, errno, strerror(errno));
+ } else if(iofd->ssl) {
+ struct IODescriptor *client_iofd = iohandler_add(callback_event.data.accept_fd, IOTYPE_CLIENT, NULL, NULL);
+ iohandler_ssl_client_accepted(iofd, client_iofd);
+ } else
+ callback_event.type = IOEVENT_ACCEPT;
+ }
+ break;
+ case IO_CONNECTING:
+ if(readable) { //could not connect
+ callback_event.type = IOEVENT_NOTCONNECTED;
+ //socklen_t arglen;
+ //arglen = sizeof(callback_event.data.errid);
+ //if (getsockopt(iofd->fd, SOL_SOCKET, SO_ERROR, &callback_event.data.errid, &arglen) < 0)
+ // callback_event.data.errid = errno;
+ iofd->state = IO_CLOSED;
+ engine->update(iofd);
+ } else if(writeable) {
+ if(iofd->ssl && !iofd->ssl_active) {
+ iohandler_log(IOLOG_DEBUG, "triggering iohandler_ssl_connect for %s (fd: %d)", iohandler_iotype_name(iofd->type), iofd->fd);
+ iohandler_ssl_connect(iofd);
+ return;
+ }
+ if(iofd->ssl && iofd->ssl_server_hs) {
+ callback_event.type = IOEVENT_SSLACCEPT;
+ callback_event.iofd = iofd->data;
+ callback_event.data.accept_iofd = iofd;
+ iofd->data = NULL;
+ }
+ else
+ callback_event.type = IOEVENT_CONNECTED;
+ iofd->state = IO_CONNECTED;
+ engine->update(iofd);
+ }
+ break;
+ case IO_CONNECTED:
+ if(readable) {
+ if(iofd->read_lines) {
+ int bytes;
+
+ if(iofd->ssl_active)
+ bytes = iohandler_ssl_read(iofd, iofd->readbuf.buffer + iofd->readbuf.bufpos, iofd->readbuf.buflen - iofd->readbuf.bufpos);
+ else {
+ if(iofd->type == IOTYPE_STDIN)
+ #ifdef WIN32
+ bytes = readable;
+ #else
+ bytes = read(iofd->fd, iofd->readbuf.buffer + iofd->readbuf.bufpos, iofd->readbuf.buflen - iofd->readbuf.bufpos);
+ #endif
+ else
+ bytes = recv(iofd->fd, iofd->readbuf.buffer + iofd->readbuf.bufpos, iofd->readbuf.buflen - iofd->readbuf.bufpos, 0);
+ }
+ if(bytes <= 0) {
+ if (errno != EAGAIN || errno != EWOULDBLOCK) {
+ iofd->state = IO_CLOSED;
+ engine->update(iofd);
+ callback_event.type = IOEVENT_CLOSED;
+ callback_event.data.errid = errno;
+ }
+ } else {
+ int i, used_bytes = 0;
+ iohandler_log(IOLOG_DEBUG, "received %d bytes (fd: %d). readbuf position: %d", bytes, iofd->fd, iofd->readbuf.bufpos);
+ iofd->readbuf.bufpos += bytes;
+ callback_event.type = IOEVENT_RECV;
+ for(i = 0; i < iofd->readbuf.bufpos; i++) {
+ if(iofd->readbuf.buffer[i] == '\r' && iofd->readbuf.buffer[i+1] == '\n')
+ iofd->readbuf.buffer[i] = 0;
+ else if(iofd->readbuf.buffer[i] == '\n' || iofd->readbuf.buffer[i] == '\r') {
+ iofd->readbuf.buffer[i] = 0;
+ callback_event.data.recv_str = iofd->readbuf.buffer + used_bytes;
+ iohandler_log(IOLOG_DEBUG, "parsed line (%d bytes): %s", i - used_bytes, iofd->readbuf.buffer + used_bytes);
+ used_bytes = i+1;
+ iohandler_trigger_event(&callback_event);
+ } else if(i + 1 - used_bytes >= IO_LINE_LEN) { //512 max
+ iofd->readbuf.buffer[i] = 0;
+ callback_event.data.recv_str = iofd->readbuf.buffer + used_bytes;
+ iohandler_log(IOLOG_DEBUG, "parsed and stripped line (%d bytes): %s", i - used_bytes, iofd->readbuf.buffer + used_bytes);
+ for(; i < iofd->readbuf.bufpos; i++) { //skip the rest of the line
+ if(iofd->readbuf.buffer[i] == '\n' || (iofd->readbuf.buffer[i] == '\r' && iofd->readbuf.buffer[i+1] != '\n')) {
+ break;
+ }
+ }
+ used_bytes = i+1;
+ iohandler_trigger_event(&callback_event);
+ }
+ }
+ if(used_bytes) {
+ if(used_bytes == iofd->readbuf.bufpos) {
+ iofd->readbuf.bufpos = 0;
+ iohandler_log(IOLOG_DEBUG, "readbuf fully processed (set buffer position to 0)");
+ } else {
+ iohandler_log(IOLOG_DEBUG, "readbuf rest: %d bytes (used %d bytes)", iofd->readbuf.bufpos - used_bytes, used_bytes);
+ memmove(iofd->readbuf.buffer, iofd->readbuf.buffer + used_bytes, iofd->readbuf.bufpos - used_bytes);
+ iofd->readbuf.bufpos -= used_bytes;
+ }
+ }
+ callback_event.type = IOEVENT_IGNORE;
+ }
+ } else
+ callback_event.type = IOEVENT_READABLE;
+ }
+ if(writeable) {
+ int bytes;
+ bytes = iohandler_try_write(iofd);
+ if(bytes < 0) {
+ iofd->state = IO_CLOSED;
+ engine->update(iofd);
+ callback_event.type = IOEVENT_CLOSED;
+ callback_event.data.errid = errno;
+ }
+ }
+ break;
+ }
+ if(callback_event.type == IOEVENT_IGNORE && !readable && !writeable)
+ callback_event.type = IOEVENT_TIMEOUT;
+ if(callback_event.type != IOEVENT_IGNORE)
+ iohandler_trigger_event(&callback_event);
+}
+
+void iohandler_poll() {
+ struct timeval timeout;
+ timeout.tv_sec = IO_MAX_TIMEOUT;
+ timeout.tv_usec = 0;
+ iohandler_poll_timeout(timeout);
+}
+
+void iohandler_poll_timeout(struct timeval timeout) {
+ if(engine) {
+ IOSYNCHRONIZE(io_poll_sync); //quite senceless multithread support... better support will follow
+ engine->loop(&timeout);
+ IODESYNCHRONIZE(io_poll_sync);
+ }
+}
+
+//debugging functions
+char *iohandler_iotype_name(enum IOType type) {
+ switch(type) {
+ case IOTYPE_UNKNOWN:
+ return "IOTYPE_UNKNOWN";
+ case IOTYPE_SERVER:
+ return "IOTYPE_SERVER";
+ case IOTYPE_CLIENT:
+ return "IOTYPE_CLIENT";
+ case IOTYPE_STDIN:
+ return "IOTYPE_STDIN";
+ case IOTYPE_TIMER:
+ return "IOTYPE_TIMER";
+ default:
+ return "(UNDEFINED)";
+ }
+}
+
+char *iohandler_iostatus_name(enum IOStatus status) {
+ switch(status) {
+ case IO_CLOSED:
+ return "IO_CLOSED";
+ case IO_LISTENING:
+ return "IO_LISTENING";
+ case IO_CONNECTING:
+ return "IO_CONNECTING";
+ case IO_CONNECTED:
+ return "IO_CONNECTED";
+ case IO_SSLWAIT:
+ return "IO_SSLWAIT";
+ default:
+ return "(UNDEFINED)";
+ }
+}
+
+char *iohandler_ioeventtype_name(enum IOEventType type) {
+ switch(type) {
+ case IOEVENT_IGNORE:
+ return "IOEVENT_IGNORE";
+ case IOEVENT_READABLE:
+ return "IOEVENT_READABLE";
+ case IOEVENT_RECV:
+ return "IOEVENT_RECV";
+ case IOEVENT_CONNECTED:
+ return "IOEVENT_CONNECTED";
+ case IOEVENT_NOTCONNECTED:
+ return "IOEVENT_NOTCONNECTED";
+ case IOEVENT_CLOSED:
+ return "IOEVENT_CLOSED";
+ case IOEVENT_ACCEPT:
+ return "IOEVENT_ACCEPT";
+ case IOEVENT_SSLACCEPT:
+ return "IOEVENT_SSLACCEPT";
+ case IOEVENT_TIMEOUT:
+ return "IOEVENT_TIMEOUT";
+ default:
+ return "(UNDEFINED)";
+ }
+}
--- /dev/null
+/* IOHandler.h - IOMultiplexer
+ * Copyright (C) 2012 Philipp Kreil (pk910)
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+#ifndef _IOHandler_h
+#define _IOHandler_h
+#include <stddef.h>
+#include <sys/time.h> /* struct timeval */
+
+#define IO_READ_BUFLEN 1024
+#define IO_MAX_TIMEOUT 10
+#define IO_LINE_LEN 1024
+
+struct timeval;
+struct IODescriptor;
+struct IOEvent;
+struct IOSSLNode;
+
+enum IOLogType {
+ IOLOG_DEBUG,
+ IOLOG_WARNING,
+ IOLOG_ERROR,
+ IOLOG_FATAL
+};
+
+#define IOHANDLER_CALLBACK(NAME) void NAME(struct IOEvent *event)
+typedef IOHANDLER_CALLBACK(iohandler_callback);
+
+#define IOHANDLER_LOG_BACKEND(NAME) void NAME(enum IOLogType type, const char *line)
+typedef IOHANDLER_LOG_BACKEND(iohandler_log_callback);
+
+extern iohandler_log_callback *iolog_backend;
+
+enum IOType {
+ IOTYPE_UNKNOWN, /* ignore descriptor (uninitialized) */
+ IOTYPE_SERVER, /* server socket */
+ IOTYPE_CLIENT, /* client socket */
+ IOTYPE_STDIN, /* stdin */
+ IOTYPE_TIMER /* timer */
+};
+
+enum IOStatus {
+ IO_CLOSED, /* descriptor is dead (socket waiting for removal or timer) */
+ IO_LISTENING, /* descriptor is waiting for connections (server socket) */
+ IO_CONNECTING, /* descriptor is waiting for connection approval (connecting client socket) */
+ IO_CONNECTED, /* descriptor is connected (connected client socket) */
+ IO_SSLWAIT /* waiting for SSL backend (e.g. handshake) */
+};
+
+enum IOEventType {
+ IOEVENT_IGNORE,
+ IOEVENT_READABLE, /* socket is readable - not read anything yet, could also be disconnect notification */
+ IOEVENT_RECV, /* client socket received something (recv_str valid) */
+ IOEVENT_CONNECTED, /* client socket connected successful */
+ IOEVENT_NOTCONNECTED, /* client socket could not connect (errid valid) */
+ IOEVENT_CLOSED, /* client socket lost connection (errid valid) */
+ IOEVENT_ACCEPT, /* server socket accepted new connection (accept_fd valid) */
+ IOEVENT_SSLACCEPT, /* SSL server socket accepted new connection (accept_iofd valid) */
+ IOEVENT_TIMEOUT, /* timer timed out */
+ IOEVENT_SSLFAILED /* failed to initialize SSL session */
+};
+
+struct IOBuffer {
+ char *buffer;
+ size_t bufpos, buflen;
+};
+
+struct IODescriptor {
+ int fd;
+ enum IOType type;
+ enum IOStatus state;
+ struct timeval timeout;
+ int constant_timeout;
+ iohandler_callback *callback;
+ struct IOBuffer readbuf;
+ struct IOBuffer writebuf;
+ void *data;
+ int read_lines : 1;
+ int ssl : 1;
+ int ssl_server_hs : 1;
+ int ssl_active : 1;
+ int ssl_hs_read : 1;
+ int ssl_hs_write : 1;
+ struct IOSSLNode *sslnode;
+
+ struct IODescriptor *next, *prev;
+};
+
+struct IOEvent {
+ enum IOEventType type;
+ struct IODescriptor *iofd;
+ union {
+ char *recv_str;
+ int accept_fd;
+ int errid;
+ struct IODescriptor *accept_iofd;
+ } data;
+};
+
+#define IOHANDLER_LISTEN_IPV4 0x01
+#define IOHANDLER_LISTEN_IPV6 0x02 /* overrides IOHANDLER_LISTEN_IPV4 */
+
+#define IOHANDLER_CONNECT_IPV4 0x01
+#define IOHANDLER_CONNECT_IPV6 0x02 /* overrides IOHANDLER_CONNECT_IPV4 */
+
+#define IOHANDLER_SETTING_HIGH_PRECISION_TIMER 0x01
+
+void iohandler_set(int setting, int value);
+
+struct IODescriptor *iohandler_add(int sockfd, enum IOType type, struct timeval *timeout, iohandler_callback *callback);
+struct IODescriptor *iohandler_timer(struct timeval timeout, iohandler_callback *callback);
+struct IODescriptor *iohandler_constant_timer(int msec, iohandler_callback *callback);
+struct IODescriptor *iohandler_connect(const char *hostname, unsigned int port, int ssl, const char *bind, iohandler_callback *callback);
+struct IODescriptor *iohandler_connect_flags(const char *hostname, unsigned int port, int ssl, const char *bindhost, iohandler_callback *callback, int flags);
+struct IODescriptor *iohandler_listen(const char *hostname, unsigned int port, iohandler_callback *callback);
+struct IODescriptor *iohandler_listen_flags(const char *hostname, unsigned int port, iohandler_callback *callback, int flags);
+struct IODescriptor *iohandler_listen_ssl(const char *hostname, unsigned int port, const char *certfile, const char *keyfile, iohandler_callback *callback);
+struct IODescriptor *iohandler_listen_ssl_flags(const char *hostname, unsigned int port, const char *certfile, const char *keyfile, iohandler_callback *callback, int flags);
+void iohandler_write(struct IODescriptor *iofd, const char *line);
+void iohandler_send(struct IODescriptor *iofd, const char *data, size_t datalen);
+void iohandler_printf(struct IODescriptor *iofd, const char *text, ...);
+void iohandler_close(struct IODescriptor *iofd);
+void iohandler_update(struct IODescriptor *iofd);
+void iohandler_set_timeout(struct IODescriptor *iofd, struct timeval *timeout);
+
+void iohandler_poll();
+void iohandler_poll_timeout(struct timeval timeout);
+
+#endif
--- /dev/null
+/* IOHandler_SSL.c - IOMultiplexer
+ * Copyright (C) 2012 Philipp Kreil (pk910)
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+#include "IOEngine.h"
+#include "IOHandler_SSL.h"
+#ifdef HAVE_SSL
+
+void iohandler_ssl_init() {
+ SSL_library_init();
+ OpenSSL_add_all_algorithms(); /* load & register all cryptos, etc. */
+ SSL_load_error_strings();
+}
+
+static void iohandler_ssl_error() {
+ unsigned long e;
+ while((e = ERR_get_error())) {
+ iohandler_log(IOLOG_ERROR, "SSLv23 ERROR %lu: %s", e, ERR_error_string(e, NULL));
+ }
+}
+
+void iohandler_ssl_connect(struct IODescriptor *iofd) {
+ iofd->state = IO_SSLWAIT;
+ iofd->ssl_server_hs = 0;
+ struct IOSSLNode *sslnode = malloc(sizeof(*sslnode));
+ sslnode->sslContext = SSL_CTX_new(SSLv23_client_method());
+ if(!sslnode->sslContext) {
+ iohandler_ssl_error();
+ iohandler_log(IOLOG_ERROR, "SSL: could not create client SSL CTX");
+ goto ssl_connect_err;
+ }
+ sslnode->sslHandle = SSL_new(sslnode->sslContext);
+ if(!sslnode->sslHandle) {
+ iohandler_ssl_error();
+ iohandler_log(IOLOG_ERROR, "SSL: could not create client SSL Handle");
+ goto ssl_connect_err;
+ }
+ if(!SSL_set_fd(sslnode->sslHandle, iofd->fd)) {
+ iohandler_ssl_error();
+ iohandler_log(IOLOG_ERROR, "SSL: could not set client fd in SSL Handle");
+ goto ssl_connect_err;
+ }
+ SSL_set_connect_state(sslnode->sslHandle);
+ iofd->sslnode = sslnode;
+ iohandler_ssl_client_handshake(iofd);
+ return;
+ssl_connect_err:
+ free(sslnode);
+ iohandler_events(iofd, 0, 0);
+}
+
+void iohandler_ssl_listen(struct IODescriptor *iofd, const char *certfile, const char *keyfile) {
+ struct IOSSLNode *sslnode = malloc(sizeof(*sslnode));
+ sslnode->sslContext = SSL_CTX_new(SSLv23_server_method());
+ if(!sslnode->sslContext) {
+ iohandler_ssl_error();
+ iohandler_log(IOLOG_ERROR, "SSL: could not create server SSL CTX");
+ goto ssl_listen_err;
+ }
+ /* load certificate */
+ if(SSL_CTX_use_certificate_file(sslnode->sslContext, certfile, SSL_FILETYPE_PEM) <= 0) {
+ iohandler_ssl_error();
+ iohandler_log(IOLOG_ERROR, "SSL: could not load server certificate (%s)", certfile);
+ goto ssl_listen_err;
+ }
+ /* load keyfile */
+ if(SSL_CTX_use_PrivateKey_file(sslnode->sslContext, keyfile, SSL_FILETYPE_PEM) <= 0) {
+ iohandler_ssl_error();
+ iohandler_log(IOLOG_ERROR, "SSL: could not load server keyfile (%s)", keyfile);
+ goto ssl_listen_err;
+ }
+ /* check certificate and keyfile */
+ if(!SSL_CTX_check_private_key(sslnode->sslContext)) {
+ iohandler_ssl_error();
+ iohandler_log(IOLOG_ERROR, "SSL: server certificate (%s) and keyfile (%s) doesn't match!", certfile, keyfile);
+ goto ssl_listen_err;
+ }
+ iofd->sslnode = sslnode;
+ return;
+ssl_listen_err:
+ free(sslnode);
+ iofd->sslnode = NULL;
+ iohandler_events(iofd, 0, 0);
+}
+
+void iohandler_ssl_client_handshake(struct IODescriptor *iofd) {
+ // Perform an SSL handshake.
+ int ret = SSL_do_handshake(iofd->sslnode->sslHandle);
+ iofd->ssl_hs_read = 0;
+ iofd->ssl_hs_write = 0;
+ switch(SSL_get_error(iofd->sslnode->sslHandle, ret)) {
+ case SSL_ERROR_NONE:
+ iofd->state = IO_CONNECTING;
+ iofd->ssl_active = 1;
+ iohandler_log(IOLOG_DEBUG, "SSL handshake for %s (fd: %d) successful", iohandler_iotype_name(iofd->type), iofd->fd);
+ iohandler_events(iofd, 0, 1); //perform IOEVENT_CONNECTED event
+ break;
+ case SSL_ERROR_WANT_READ:
+ iofd->ssl_hs_read = 1;
+ iohandler_log(IOLOG_DEBUG, "SSL_do_handshake for %s (fd: %d) returned SSL_ERROR_WANT_READ", iohandler_iotype_name(iofd->type), iofd->fd);
+ break;
+ case SSL_ERROR_WANT_WRITE:
+ iofd->ssl_hs_write = 1;
+ iohandler_log(IOLOG_DEBUG, "SSL_do_handshake for %s (fd: %d) returned SSL_ERROR_WANT_WRITE", iohandler_iotype_name(iofd->type), iofd->fd);
+ break;
+ default:
+ iohandler_log(IOLOG_ERROR, "SSL_do_handshake for %s (fd: %d) failed with ", iohandler_iotype_name(iofd->type), iofd->fd);
+ iohandler_events(iofd, 0, 0);
+ break;
+ }
+}
+
+void iohandler_ssl_client_accepted(struct IODescriptor *iofd, struct IODescriptor *client_iofd) {
+ struct IOSSLNode *sslnode = malloc(sizeof(*sslnode));
+ sslnode->sslHandle = SSL_new(sslnode->sslContext);
+ if(!sslnode->sslHandle) {
+ iohandler_ssl_error();
+ iohandler_log(IOLOG_ERROR, "SSL: could not create client SSL Handle");
+ goto ssl_accept_err;
+ }
+ if(!SSL_set_fd(sslnode->sslHandle, client_iofd->fd)) {
+ iohandler_ssl_error();
+ iohandler_log(IOLOG_ERROR, "SSL: could not set client fd in SSL Handle");
+ goto ssl_accept_err;
+ }
+ client_iofd->state = IO_SSLWAIT;
+ client_iofd->ssl_server_hs = 1;
+ client_iofd->ssl = 1;
+ client_iofd->sslnode = sslnode;
+ client_iofd->callback = iofd->callback;
+ client_iofd->data = iofd;
+ return;
+ssl_accept_err:
+ iohandler_close(client_iofd);
+ free(sslnode);
+}
+
+void iohandler_ssl_server_handshake(struct IODescriptor *iofd) {
+ // Perform an SSL handshake.
+ int ret = SSL_accept(iofd->sslnode->sslHandle);
+ iofd->ssl_hs_read = 0;
+ iofd->ssl_hs_write = 0;
+ switch(SSL_get_error(iofd->sslnode->sslHandle, ret)) {
+ case SSL_ERROR_NONE:
+ iofd->state = IO_CONNECTING;
+ iofd->ssl_active = 1;
+ iohandler_log(IOLOG_DEBUG, "SSL handshake for %s (fd: %d) successful", iohandler_iotype_name(iofd->type), iofd->fd);
+ iohandler_events(iofd, 0, 1); //perform IOEVENT_CONNECTED event
+ break;
+ case SSL_ERROR_WANT_READ:
+ iofd->ssl_hs_read = 1;
+ iohandler_log(IOLOG_DEBUG, "SSL_do_handshake for %s (fd: %d) returned SSL_ERROR_WANT_READ", iohandler_iotype_name(iofd->type), iofd->fd);
+ break;
+ case SSL_ERROR_WANT_WRITE:
+ iofd->ssl_hs_write = 1;
+ iohandler_log(IOLOG_DEBUG, "SSL_do_handshake for %s (fd: %d) returned SSL_ERROR_WANT_WRITE", iohandler_iotype_name(iofd->type), iofd->fd);
+ break;
+ default:
+ iohandler_log(IOLOG_ERROR, "SSL_do_handshake for %s (fd: %d) failed with ", iohandler_iotype_name(iofd->type), iofd->fd);
+ iohandler_events(iofd, 0, 0);
+ break;
+ }
+}
+
+void iohandler_ssl_disconnect(struct IODescriptor *iofd) {
+ if(!iofd->sslnode) return;
+ SSL_shutdown(iofd->sslnode->sslHandle);
+ SSL_free(iofd->sslnode->sslHandle);
+ SSL_CTX_free(iofd->sslnode->sslContext);
+ free(iofd->sslnode);
+ iofd->sslnode = NULL;
+ iofd->ssl_active = 0;
+}
+
+int iohandler_ssl_read(struct IODescriptor *iofd, char *buffer, int len) {
+ if(!iofd->sslnode) return 0;
+ int ret = SSL_read(iofd->sslnode->sslHandle, buffer, len);
+ int update = (iofd->ssl_hs_read || iofd->ssl_hs_write);
+ iofd->ssl_hs_read = 0;
+ iofd->ssl_hs_write = 0;
+ switch(SSL_get_error(iofd->sslnode->sslHandle, ret)) {
+ case SSL_ERROR_NONE:
+ case SSL_ERROR_ZERO_RETURN:
+ if(update)
+ iohandler_update(iofd);
+ return ret;
+ break;
+ case SSL_ERROR_WANT_READ:
+ iofd->ssl_hs_read = 1;
+ iohandler_update(iofd);
+ iohandler_log(IOLOG_DEBUG, "SSL_read for %s (fd: %d) returned SSL_ERROR_WANT_READ", iohandler_iotype_name(iofd->type), iofd->fd);
+ errno = EAGAIN;
+ return -1;
+ break;
+ case SSL_ERROR_WANT_WRITE:
+ iofd->ssl_hs_write = 1;
+ iohandler_update(iofd);
+ iohandler_log(IOLOG_DEBUG, "SSL_read for %s (fd: %d) returned SSL_ERROR_WANT_WRITE", iohandler_iotype_name(iofd->type), iofd->fd);
+ errno = EAGAIN;
+ return -1;
+ break;
+ default:
+ iohandler_log(IOLOG_ERROR, "SSL_read for %s (fd: %d) failed with ", iohandler_iotype_name(iofd->type), iofd->fd);
+ return -1;
+ break;
+ }
+}
+
+int iohandler_ssl_write(struct IODescriptor *iofd, char *buffer, int len) {
+ if(!iofd->sslnode) return 0;
+ int ret = SSL_write(iofd->sslnode->sslHandle, buffer, len);
+ int update = (iofd->ssl_hs_read || iofd->ssl_hs_write);
+ iofd->ssl_hs_read = 0;
+ iofd->ssl_hs_write = 0;
+ switch(SSL_get_error(iofd->sslnode->sslHandle, ret)) {
+ case SSL_ERROR_NONE:
+ case SSL_ERROR_ZERO_RETURN:
+ if(update)
+ iohandler_update(iofd);
+ return ret;
+ break;
+ case SSL_ERROR_WANT_READ:
+ iofd->ssl_hs_read = 1;
+ iohandler_update(iofd);
+ iohandler_log(IOLOG_DEBUG, "SSL_write for %s (fd: %d) returned SSL_ERROR_WANT_READ", iohandler_iotype_name(iofd->type), iofd->fd);
+ errno = EAGAIN;
+ return -1;
+ break;
+ case SSL_ERROR_WANT_WRITE:
+ iofd->ssl_hs_write = 1;
+ iohandler_update(iofd);
+ iohandler_log(IOLOG_DEBUG, "SSL_write for %s (fd: %d) returned SSL_ERROR_WANT_WRITE", iohandler_iotype_name(iofd->type), iofd->fd);
+ errno = EAGAIN;
+ return -1;
+ break;
+ default:
+ iohandler_log(IOLOG_ERROR, "SSL_write for %s (fd: %d) failed with ", iohandler_iotype_name(iofd->type), iofd->fd);
+ return -1;
+ break;
+ }
+}
+
+#else
+// NULL-backend
+
+void iohandler_ssl_init() {};
+void iohandler_ssl_connect(struct IODescriptor *iofd) {};
+void iohandler_ssl_listen(struct IODescriptor *iofd, const char *certfile, const char *keyfile) {};
+void iohandler_ssl_client_handshake(struct IODescriptor *iofd) {};
+void iohandler_ssl_client_accepted(struct IODescriptor *iofd, struct IODescriptor *client_iofd) {};
+void iohandler_ssl_server_handshake(struct IODescriptor *iofd) {};
+void iohandler_ssl_disconnect(struct IODescriptor *iofd) {};
+int iohandler_ssl_read(struct IODescriptor *iofd, char *buffer, int len) { return 0; };
+int iohandler_ssl_write(struct IODescriptor *iofd, char *buffer, int len) { return 0; };
+#endif
--- /dev/null
+/* IOHandler_SSL.h - IOMultiplexer
+ * Copyright (C) 2012 Philipp Kreil (pk910)
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+#ifndef _IOHandler_SSL_h
+#define _IOHandler_SSL_h
+
+struct IODescriptor;
+
+#ifdef HAVE_SSL
+#include <openssl/rand.h>
+#include <openssl/ssl.h>
+#include <openssl/err.h>
+
+struct IOSSLNode {
+ SSL *sslHandle;
+ SSL_CTX *sslContext;
+};
+#else
+struct IOSSLNode {
+ //just unused
+};
+#endif
+
+void iohandler_ssl_init();
+void iohandler_ssl_connect(struct IODescriptor *iofd);
+void iohandler_ssl_listen(struct IODescriptor *iofd, const char *certfile, const char *keyfile);
+void iohandler_ssl_client_handshake(struct IODescriptor *iofd);
+void iohandler_ssl_client_accepted(struct IODescriptor *iofd, struct IODescriptor *client_iofd);
+void iohandler_ssl_server_handshake(struct IODescriptor *iofd);
+void iohandler_ssl_disconnect(struct IODescriptor *iofd);
+int iohandler_ssl_read(struct IODescriptor *iofd, char *buffer, int len);
+int iohandler_ssl_write(struct IODescriptor *iofd, char *buffer, int len);
+
+#endif
--- /dev/null
+
+CC = gcc
+CFLAGS = -g -O0 -Wall -Wshadow -Werror -DHAVE_PTHREAD_H
+LDFLAGS = -lws2_32 -lpthread
+
+OBJ = ../../IOEngine_epoll.o ../../IOEngine_kevent.o ../../IOEngine_select.o ../../IOEngine_win32.o ../../IOHandler.o ../../IOHandler_SSL.o iotest.o
+
+all: $(OBJ)
+ $(CC) $(CFLAGS) -oiotest $(OBJ) $(LDFLAGS)
+
+%.o: %.c
+ $(CC) $(CFLAGS) -o$@ -c $<
--- /dev/null
+/* main.c - IOMultiplexer
+ * Copyright (C) 2012 Philipp Kreil (pk910)
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <stdio.h>
+#include "../IOHandler.h"
+
+static IOHANDLER_CALLBACK(io_callback);
+static IOHANDLER_LOG_BACKEND(io_log);
+
+static struct IODescriptor *irc_iofd = NULL;
+
+int main(int argc, char *argv[]) {
+ iolog_backend = io_log;
+
+ irc_iofd = iohandler_connect("pk910.de", 6667, 0, NULL, io_callback);
+
+ struct IODescriptor *iofd;
+ iofd = iohandler_add(0, IOTYPE_STDIN, NULL, io_callback);
+ iofd->read_lines = 1;
+
+ while(1) {
+ iohandler_poll();
+ }
+}
+
+static IOHANDLER_CALLBACK(io_callback) {
+ switch(event->type) {
+ case IOEVENT_CONNECTED:
+ printf("[connect]\n");
+ break;
+ case IOEVENT_CLOSED:
+ printf("[disconnect]\n");
+ break;
+ case IOEVENT_RECV:
+ if(event->iofd->type == IOTYPE_STDIN) {
+ iohandler_printf(irc_iofd, "%s\n", event->data.recv_str);
+ printf("[out] %s\n", event->data.recv_str);
+ } else
+ printf("[in] %s\n", event->data.recv_str);
+ break;
+
+ default:
+ break;
+ }
+}
+
+static IOHANDLER_LOG_BACKEND(io_log) {
+ //printf("%s", line);
+}
--- /dev/null
+
+CC = gcc
+CFLAGS = -g -O0 -Wall -Wshadow -Werror -DHAVE_PTHREAD_H
+LDFLAGS = -lws2_32 -lpthread
+
+OBJ = ../../IOEngine_epoll.o ../../IOEngine_kevent.o ../../IOEngine_select.o ../../IOEngine_win32.o ../../IOHandler.o ../../IOHandler_SSL.o iotest.o
+
+all: $(OBJ)
+ $(CC) $(CFLAGS) -oiotest $(OBJ) $(LDFLAGS)
+
+%.o: %.c
+ $(CC) $(CFLAGS) -o$@ -c $<
--- /dev/null
+/* main.c - IOMultiplexer
+ * Copyright (C) 2012 Philipp Kreil (pk910)
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <stdio.h>
+#include "../../IOHandler.h"
+
+#define TEST_DURATION 100
+
+static IOHANDLER_CALLBACK(io_callback);
+static IOHANDLER_LOG_BACKEND(io_log);
+
+static struct timeval test_clock1, test_clock2;
+static int timercount;
+
+void add_timer(int ms) {
+ struct timeval timeout;
+ gettimeofday(&timeout, NULL);
+ timeout.tv_usec += (ms % 1000) * 1000;
+ timeout.tv_sec += (ms / 1000);
+ if(timeout.tv_usec > 1000000) {
+ timeout.tv_usec -= 1000000;
+ timeout.tv_sec++;
+ }
+ iohandler_timer(timeout, io_callback);
+}
+
+int main(int argc, char *argv[]) {
+ iolog_backend = io_log;
+
+ iohandler_set(IOHANDLER_SETTING_HIGH_PRECISION_TIMER, 1);
+
+ gettimeofday(&test_clock1, NULL);
+ gettimeofday(&test_clock2, NULL);
+ //add_timer(TEST_DURATION);
+ iohandler_constant_timer(TEST_DURATION, io_callback);
+ timercount = 0;
+
+ printf("[timer 0] %ld.%ld\n", test_clock1.tv_sec, test_clock1.tv_usec);
+
+ while(1) {
+ iohandler_poll();
+ }
+}
+
+static IOHANDLER_CALLBACK(io_callback) {
+ struct timeval curr_time;
+ int diff1;
+ double diff2;
+ switch(event->type) {
+ case IOEVENT_TIMEOUT:
+ //add_timer(TEST_DURATION);
+ timercount++;
+ gettimeofday(&curr_time, NULL);
+ diff1 = (curr_time.tv_sec - test_clock1.tv_sec) * 1000 + ((curr_time.tv_usec - test_clock1.tv_usec) / 1000);
+ diff2 = (curr_time.tv_sec - test_clock2.tv_sec) * 1000 + ((curr_time.tv_usec - test_clock2.tv_usec) / 1000.0);
+ diff2 -= (timercount * TEST_DURATION);
+ gettimeofday(&test_clock1, NULL);
+ printf("[timer %03d] %ld.%06ld [%d ms] accuracy: %f ms\n", timercount, curr_time.tv_sec, curr_time.tv_usec, diff1, diff2);
+ break;
+ default:
+ break;
+ }
+}
+
+static IOHANDLER_LOG_BACKEND(io_log) {
+ //printf("%s", line);
+}
--- /dev/null
+/* IOEngine.h - IOMultiplexer
+ * Copyright (C) 2012 Philipp Kreil (pk910)
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+#ifndef _IOEngine_h
+#define _IOEngine_h
+#include "IOHandler.h"
+
+#ifdef HAVE_PTHREAD_H
+#include <pthread.h>
+#ifdef PTHREAD_MUTEX_RECURSIVE_NP
+#define PTHREAD_MUTEX_RECURSIVE_VAL PTHREAD_MUTEX_RECURSIVE_NP
+#else
+#define PTHREAD_MUTEX_RECURSIVE_VAL PTHREAD_MUTEX_RECURSIVE
+#endif
+#define IOTHREAD_MUTEX_INIT(var) { \
+ pthread_mutexattr_t mutex_attr; \
+ pthread_mutexattr_init(&mutex_attr);\
+ pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_RECURSIVE_VAL);\
+ pthread_mutex_init(&var, &mutex_attr); \
+}
+#define IOSYNCHRONIZE(var) pthread_mutex_lock(&var)
+#define IODESYNCHRONIZE(var) pthread_mutex_unlock(&var)
+#else
+#define IOTHREAD_MUTEX_INIT(var)
+#define IOSYNCHRONIZE(var)
+#define IODESYNCHRONIZE(var)
+#endif
+
+struct IODescriptor;
+enum IOType;
+enum IOStatus;
+enum IOEventType;
+
+#define timeval_is_bigger(x,y) ((x->tv_sec > y->tv_sec) || (x->tv_sec == y->tv_sec && x->tv_usec > y->tv_usec))
+#define timeval_is_smaler(x,y) ((x->tv_sec < y->tv_sec) || (x->tv_sec == y->tv_sec && x->tv_usec < y->tv_usec))
+
+extern struct IODescriptor *first_descriptor;
+extern struct IODescriptor *timer_priority;
+
+struct IOEngine {
+ const char *name;
+ int (*init)(void);
+ void (*add)(struct IODescriptor *iofd);
+ void (*remove)(struct IODescriptor *iofd);
+ void (*update)(struct IODescriptor *iofd);
+ void (*loop)(struct timeval *timeout);
+ void (*cleanup)(void);
+};
+
+#define iohandler_wants_writes(IOFD) ((IOFD->writebuf.bufpos && !IOFD->ssl_hs_read) || IOFD->state == IO_CONNECTING || IOFD->ssl_hs_write)
+
+void iohandler_log(enum IOLogType type, char *text, ...);
+void iohandler_events(struct IODescriptor *iofd, int readable, int writeable);
+char *iohandler_iotype_name(enum IOType type);
+char *iohandler_iostatus_name(enum IOStatus status);
+char *iohandler_ioeventtype_name(enum IOEventType type);
+
+#endif
--- /dev/null
+/* IOEngine_epoll.c - IOMultiplexer
+ * Copyright (C) 2012 Philipp Kreil (pk910)
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+#include "IOEngine.h"
+
+#ifdef HAVE_SYS_EPOLL_H
+#include <sys/epoll.h>
+#include <errno.h>
+#include <string.h>
+#include <unistd.h>
+
+#define MAX_EVENTS 32
+
+static int epoll_fd;
+
+static int engine_epoll_init() {
+ epoll_fd = epoll_create(1024);
+ if (epoll_fd < 0)
+ return 0;
+ return 1;
+}
+
+static void engine_epoll_add(struct IODescriptor *iofd) {
+ if(iofd->type == IOTYPE_TIMER) return;
+ //add descriptor to the epoll queue
+ struct epoll_event evt;
+ int res;
+
+ evt.events = EPOLLHUP | EPOLLIN | (iohandler_wants_writes(iofd) ? EPOLLOUT : 0);
+ evt.data.ptr = iofd;
+ res = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, iofd->fd, &evt);
+ if(res < 0) {
+ iohandler_log(IOLOG_ERROR, "could not add IODescriptor %d to epoll queue. (returned: %d)", iofd->fd, res);
+ }
+}
+
+static void engine_epoll_remove(struct IODescriptor *iofd) {
+ if(iofd->type == IOTYPE_TIMER) return;
+ struct epoll_event evt;
+ epoll_ctl(epoll_fd, EPOLL_CTL_DEL, iofd->fd, &evt);
+}
+
+static void engine_epoll_update(struct IODescriptor *iofd) {
+ if(iofd->type == IOTYPE_TIMER) return;
+ if(iofd->state == IO_CLOSED) {
+ engine_epoll_remove(iofd);
+ return;
+ }
+ struct epoll_event evt;
+ int res;
+
+ evt.events = EPOLLHUP | EPOLLIN | (iohandler_wants_writes(iofd) ? EPOLLOUT : 0);
+ evt.data.ptr = iofd;
+ res = epoll_ctl(epoll_fd, EPOLL_CTL_MOD, iofd->fd, &evt);
+ if(res < 0) {
+ iohandler_log(IOLOG_ERROR, "could not update IODescriptor %d in epoll queue. (returned: %d)", iofd->fd, res);
+ }
+}
+
+static void engine_epoll_loop(struct timeval *timeout) {
+ struct epoll_event evts[MAX_EVENTS];
+ struct timeval now, tdiff;
+ int msec;
+ int events;
+ int epoll_result;
+
+ gettimeofday(&now, NULL);
+
+ while(timer_priority) {
+ tdiff.tv_sec = timer_priority->timeout.tv_sec - now.tv_sec;
+ tdiff.tv_usec = timer_priority->timeout.tv_usec - now.tv_usec;
+ if(tdiff.tv_sec < 0 || (tdiff.tv_sec == 0 && tdiff.tv_usec <= 0)) {
+ if(timer_priority->constant_timeout) {
+ tdiff.tv_sec = 0;
+ iohandler_set_timeout(timer_priority, &tdiff);
+ iohandler_events(timer_priority, 0, 0);
+ } else {
+ iohandler_events(timer_priority, 0, 0);
+ iohandler_close(timer_priority); //also sets timer_priority to the next timed element
+ }
+ continue;
+ } else if(tdiff.tv_usec < 0) {
+ tdiff.tv_sec--;
+ tdiff.tv_usec += 1000000; //1 sec
+ }
+ if(timeval_is_smaler((&tdiff), timeout)) {
+ timeout->tv_sec = tdiff.tv_sec;
+ timeout->tv_usec = tdiff.tv_usec;
+ }
+ break;
+ }
+
+ msec = timeout ? ((timeout->tv_sec * 1000 + timeout->tv_usec / 1000) + (timeout->tv_usec % 1000 != 0 ? 1 : 0)) : -1;
+
+ //select system call
+ epoll_result = epoll_wait(epoll_fd, evts, MAX_EVENTS, msec);
+
+ if (epoll_result < 0) {
+ if (errno != EINTR) {
+ iohandler_log(IOLOG_FATAL, "epoll_wait() failed with errno %d: %s", errno, strerror(errno));
+ return;
+ }
+ } else {
+ int i;
+ for(i = 0; i < epoll_result; i++) {
+ events = evts[i].events;
+ iohandler_events(evts[i].data.ptr, (events & (EPOLLIN | EPOLLHUP)), (events & EPOLLOUT));
+ }
+ }
+
+ //check timers
+ while(timer_priority) {
+ tdiff.tv_sec = timer_priority->timeout.tv_sec - now.tv_sec;
+ tdiff.tv_usec = timer_priority->timeout.tv_usec - now.tv_usec;
+ if(tdiff.tv_sec < 0 || (tdiff.tv_sec == 0 && tdiff.tv_usec <= 0)) {
+ if(timer_priority->constant_timeout) {
+ tdiff.tv_sec = 0;
+ iohandler_set_timeout(timer_priority, &tdiff);
+ iohandler_events(timer_priority, 0, 0);
+ } else {
+ iohandler_events(timer_priority, 0, 0);
+ iohandler_close(timer_priority); //also sets timer_priority to the next timed element
+ }
+ continue;
+ }
+ break;
+ }
+
+}
+
+static void engine_epoll_cleanup() {
+ close(epoll_fd);
+}
+
+struct IOEngine engine_epoll = {
+ .name = "epoll",
+ .init = engine_epoll_init,
+ .add = engine_epoll_add,
+ .remove = engine_epoll_remove,
+ .update = engine_epoll_update,
+ .loop = engine_epoll_loop,
+ .cleanup = engine_epoll_cleanup,
+};
+
+#else
+
+struct IOEngine engine_epoll = {
+ .name = "epoll",
+ .init = NULL,
+ .add = NULL,
+ .remove = NULL,
+ .update = NULL,
+ .loop = NULL,
+ .cleanup = NULL,
+};
+
+#endif
--- /dev/null
+/* IOengine_kevent.c - IOMultiplexer
+ * Copyright (C) 2012 Philipp Kreil (pk910)
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+#include "IOEngine.h"
+
+#ifdef HAVE_SYS_EVENT_H
+#include <sys/event.h>
+#include <errno.h>
+
+#define MAX_EVENTS 32
+
+static int kevent_fd;
+
+static int engine_kevent_init() {
+ kevent_fd = kqueue();
+ if (kevent_fd < 0)
+ return 0;
+ return 1;
+}
+
+static void engine_kevent_add(struct IODescriptor *iofd) {
+ if(iofd->type == IOTYPE_TIMER) return;
+ //add descriptor to the kevent queue
+ struct kevent changes[2];
+ int nchanges = 0;
+ int res;
+
+ EV_SET(&changes[nchanges++], iofd->fd, EVFILT_READ, EV_ADD, 0, 0, iofd);
+ if (iohandler_wants_writes(iofd))
+ EV_SET(&changes[nchanges++], iofd->fd, EVFILT_WRITE, EV_ADD, 0, 0, iofd);
+
+ res = kevent(kevent_fd, changes, nchanges, NULL, 0, NULL);
+ if(res < 0)
+ iohandler_log(IOLOG_ERROR, "could not add IODescriptor %d to kevent queue. (returned: %d)", res);
+}
+
+static void engine_kevent_remove(struct IODescriptor *iofd) {
+ if(iofd->type == IOTYPE_TIMER) return;
+ struct kevent changes[2];
+ int nchanges = 0;
+
+ EV_SET(&changes[nchanges++], iofd->fd, EVFILT_READ, EV_DELETE, 0, 0, iofd);
+ EV_SET(&changes[nchanges++], iofd->fd, EVFILT_WRITE, EV_DELETE, 0, 0, iofd);
+ kevent(kevent_fd, changes, nchanges, NULL, 0, NULL);
+}
+
+static void engine_kevent_update(struct IODescriptor *iofd) {
+ if(iofd->type == IOTYPE_TIMER) return;
+ if(iofd->state == IO_CLOSED) {
+ engine_kevent_remove(iofd);
+ return;
+ }
+ struct kevent changes[2];
+ int nchanges = 0;
+ int res;
+
+ EV_SET(&changes[nchanges++], iofd->fd, EVFILT_READ, EV_ADD, 0, 0, iofd);
+ EV_SET(&changes[nchanges++], iofd->fd, EVFILT_WRITE, iohandler_wants_writes(iofd) ? EV_ADD : EV_DELETE, 0, 0, iofd);
+
+ res = kevent(kevent_fd, changes, nchanges, NULL, 0, NULL);
+ if(res < 0) {
+ iohandler_log(IOLOG_ERROR, "could not update IODescriptor %d in kevent queue. (returned: %d)", res);
+ }
+}
+
+static void engine_kevent_loop(struct timeval *timeout) {
+ struct kevent events[MAX_EVENTS];
+ struct timeval now, tdiff;
+ struct timespec ts, *pts;
+ int msec;
+ int kevent_result;
+
+ gettimeofday(&now, NULL);
+
+ while(timer_priority) {
+ tdiff.tv_sec = timer_priority->timeout.tv_sec - now.tv_sec;
+ tdiff.tv_usec = timer_priority->timeout.tv_usec - now.tv_usec;
+ if(tdiff.tv_sec < 0 || (tdiff.tv_sec == 0 && tdiff.tv_usec <= 0)) {
+ if(timer_priority->constant_timeout) {
+ tdiff.tv_sec = 0;
+ iohandler_set_timeout(timer_priority, &tdiff);
+ iohandler_events(timer_priority, 0, 0);
+ } else {
+ iohandler_events(timer_priority, 0, 0);
+ iohandler_close(timer_priority); //also sets timer_priority to the next timed element
+ }
+ continue;
+ } else if(tdiff.tv_usec < 0) {
+ tdiff.tv_sec--;
+ tdiff.tv_usec += 1000000; //1 sec
+ }
+ if(timeval_is_smaler((&tdiff), timeout)) {
+ timeout->tv_sec = tdiff.tv_sec;
+ timeout->tv_usec = tdiff.tv_usec;
+ }
+ break;
+ }
+
+ if (timeout) {
+ ts.tv_sec = timeout->tv_sec;
+ ts.tv_nsec = timeout->tv_usec * 1000;
+ pts = &ts;
+ } else {
+ pts = NULL;
+ }
+
+ //select system call
+ kevent_result = kevent(kevent_fd, NULL, 0, events, MAX_EVENTS, pts);
+
+ if (kevent_result < 0) {
+ if (errno != EINTR) {
+ iohandler_log(IOLOG_FATAL, "kevent() failed with errno %d: %s", errno, strerror(errno));
+ return;
+ }
+ } else {
+ int i;
+ for(i = 0; i < kevent_result; i++)
+ iohandler_events(events[i].udata, (events[i].filter == EVFILT_READ), (events[i].filter == EVFILT_WRITE));
+ }
+
+ //check timers
+ while(timer_priority) {
+ tdiff.tv_sec = timer_priority->timeout.tv_sec - now.tv_sec;
+ tdiff.tv_usec = timer_priority->timeout.tv_usec - now.tv_usec;
+ if(tdiff.tv_sec < 0 || (tdiff.tv_sec == 0 && tdiff.tv_usec <= 0)) {
+ if(timer_priority->constant_timeout) {
+ tdiff.tv_sec = 0;
+ iohandler_set_timeout(timer_priority, &tdiff);
+ iohandler_events(timer_priority, 0, 0);
+ } else {
+ iohandler_events(timer_priority, 0, 0);
+ iohandler_close(timer_priority); //also sets timer_priority to the next timed element
+ }
+ continue;
+ }
+ break;
+ }
+
+}
+
+static void engine_kevent_cleanup() {
+ close(kevent_fd);
+}
+
+struct IOEngine engine_kevent = {
+ .name = "kevent",
+ .init = engine_kevent_init,
+ .add = engine_kevent_add,
+ .remove = engine_kevent_remove,
+ .update = engine_kevent_update,
+ .loop = engine_kevent_loop,
+ .cleanup = engine_kevent_cleanup,
+};
+
+#else
+
+struct IOEngine engine_kevent = {
+ .name = "kevent",
+ .init = NULL,
+ .add = NULL,
+ .remove = NULL,
+ .update = NULL,
+ .loop = NULL,
+ .cleanup = NULL,
+};
+
+#endif
--- /dev/null
+/* IOEngine_select.c - IOMultiplexer
+ * Copyright (C) 2012 Philipp Kreil (pk910)
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+#include "IOEngine.h"
+#include <errno.h>
+#include <time.h>
+#ifdef WIN32
+#define _WIN32_WINNT 0x501
+#include <windows.h>
+#include <winsock2.h>
+#else
+#include <string.h>
+#include <stdio.h>
+#endif
+
+static int engine_select_timer_delay_fix;
+
+static int engine_select_init() {
+ engine_select_timer_delay_fix = 0;
+ return 1;
+}
+
+static void engine_select_add(struct IODescriptor *iofd) {
+ #ifdef WIN32
+ if(iofd->type == IOTYPE_STDIN)
+ SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE),ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT);
+ #endif
+ /* empty */
+}
+
+static void engine_select_remove(struct IODescriptor *iofd) {
+ /* empty */
+}
+
+static void engine_select_update(struct IODescriptor *iofd) {
+ /* empty */
+}
+
+static void engine_select_loop(struct timeval *timeout) {
+ fd_set read_fds;
+ fd_set write_fds;
+ unsigned int fds_size = 0;
+ struct IODescriptor *iofd, *tmp_iofd;
+ struct timeval now, tdiff;
+ int select_result;
+ int timer_fix;
+
+ gettimeofday(&now, NULL);
+
+ //clear fds
+ FD_ZERO(&read_fds);
+ FD_ZERO(&write_fds);
+
+ select_result = 0;
+ for(iofd = first_descriptor; iofd; iofd = tmp_iofd) {
+ tmp_iofd = iofd->next;
+ if(iofd->type == IOTYPE_STDIN) {
+ #ifdef WIN32
+ //WIN32 doesn't support stdin within select
+ //just try to read the single events from the console
+ DWORD dwRead;
+ INPUT_RECORD inRecords[128];
+ unsigned int i;
+ int read_bytes = 0;
+ GetNumberOfConsoleInputEvents(GetStdHandle(STD_INPUT_HANDLE), &dwRead);
+ if(dwRead)
+ ReadConsoleInput(GetStdHandle(STD_INPUT_HANDLE), &inRecords[0], 128, &dwRead);
+ for (i = 0; i < dwRead; ++i) {
+ if (inRecords[i].EventType == KEY_EVENT) {
+ const char c = inRecords[i].Event.KeyEvent.uChar.AsciiChar;
+ if (inRecords[i].Event.KeyEvent.bKeyDown && c != 0) {
+ iofd->readbuf.buffer[iofd->readbuf.bufpos + read_bytes] = c;
+ read_bytes++;
+ }
+ }
+ }
+ if(read_bytes)
+ iohandler_events(iofd, read_bytes, 0);
+ if(read_bytes >= 128) {
+ timeout->tv_sec = 0;
+ timeout->tv_usec = 1;
+ //minimal timeout
+ } else {
+ timeout->tv_sec = 0;
+ timeout->tv_usec = 100000;
+ }
+ #else
+ if(iofd->fd > fds_size)
+ fds_size = iofd->fd;
+ FD_SET(iofd->fd, &read_fds);
+ select_result++;
+ #endif
+ }
+ else if(iofd->type == IOTYPE_SERVER || iofd->type == IOTYPE_CLIENT) {
+ if(iofd->state == IO_CLOSED)
+ continue;
+ if(iofd->fd > fds_size)
+ fds_size = iofd->fd;
+ FD_SET(iofd->fd, &read_fds);
+ select_result++;
+ if(iohandler_wants_writes(iofd))
+ FD_SET(iofd->fd, &write_fds);
+ }
+ }
+
+ while(timer_priority) {
+ tdiff.tv_sec = timer_priority->timeout.tv_sec - now.tv_sec;
+ tdiff.tv_usec = timer_priority->timeout.tv_usec - now.tv_usec;
+ if(tdiff.tv_sec < 0 || (tdiff.tv_sec == 0 && tdiff.tv_usec <= 0)) {
+ if(timer_priority->constant_timeout) {
+ tdiff.tv_sec = 0;
+ iohandler_set_timeout(timer_priority, &tdiff);
+ iohandler_events(timer_priority, 0, 0);
+ } else {
+ iohandler_events(timer_priority, 0, 0);
+ iohandler_close(timer_priority); //also sets timer_priority to the next timed element
+ }
+ continue;
+ } else if(tdiff.tv_usec < 0) {
+ tdiff.tv_sec--;
+ tdiff.tv_usec += 1000000; //1 sec
+ }
+ if(timeval_is_smaler((&tdiff), timeout)) {
+ timeout->tv_sec = tdiff.tv_sec;
+ timeout->tv_usec = tdiff.tv_usec + engine_select_timer_delay_fix;
+ if(timeout->tv_usec < 0) {
+ timeout->tv_sec--;
+ timeout->tv_usec += 1000000;
+ }
+ }
+ break;
+ }
+
+ if(select_result) {
+ //select system call
+ select_result = select(fds_size + 1, &read_fds, &write_fds, NULL, timeout);
+ } else {
+ #ifdef WIN32
+ Sleep((timeout->tv_sec * 1000) + (timeout->tv_usec / 1000) + 1);
+ #else
+ struct timespec usleep_time;
+ usleep_time.tv_sec = timeout->tv_sec;
+ usleep_time.tv_nsec = timeout->tv_usec * 1000;
+ nanosleep(&usleep_time, NULL);
+ #endif
+ }
+
+ if (select_result < 0) {
+ if (errno != EINTR) {
+ iohandler_log(IOLOG_FATAL, "select() failed with errno %d %d: %s", select_result, errno, strerror(errno));
+ return;
+ }
+ }
+
+ gettimeofday(&now, NULL);
+
+ //check all descriptors
+ for(iofd = first_descriptor; iofd; iofd = tmp_iofd) {
+ tmp_iofd = iofd->next;
+ if(iofd->type == IOTYPE_SERVER || iofd->type == IOTYPE_CLIENT || iofd->type == IOTYPE_STDIN) {
+ if(FD_ISSET(iofd->fd, &read_fds) || FD_ISSET(iofd->fd, &write_fds)) {
+ iohandler_events(iofd, FD_ISSET(iofd->fd, &read_fds), FD_ISSET(iofd->fd, &write_fds));
+ continue;
+ }
+ }
+ }
+
+ //check timers
+ while(timer_priority) {
+ tdiff.tv_sec = timer_priority->timeout.tv_sec - now.tv_sec;
+ tdiff.tv_usec = timer_priority->timeout.tv_usec - now.tv_usec;
+ timer_fix = (tdiff.tv_sec * 1000000) + tdiff.tv_usec;
+ if(timer_fix <= 100) {
+ if(timer_fix + 100 < engine_select_timer_delay_fix || timer_fix - 100 > engine_select_timer_delay_fix) {
+ engine_select_timer_delay_fix = ((engine_select_timer_delay_fix * 19) + timer_fix) / 20;
+ iohandler_log(IOLOG_DEBUG, "timer delay fix set to: %d us", engine_select_timer_delay_fix);
+ }
+ if(timer_priority->constant_timeout) {
+ tdiff.tv_sec = 0;
+ iohandler_set_timeout(timer_priority, &tdiff);
+ iohandler_events(timer_priority, 0, 0);
+ } else {
+ iohandler_events(timer_priority, 0, 0);
+ iohandler_close(timer_priority); //also sets timer_priority to the next timed element
+ }
+ continue;
+ }
+ break;
+ }
+
+}
+
+static void engine_select_cleanup() {
+ /* empty */
+}
+
+struct IOEngine engine_select = {
+ .name = "select",
+ .init = engine_select_init,
+ .add = engine_select_add,
+ .remove = engine_select_remove,
+ .update = engine_select_update,
+ .loop = engine_select_loop,
+ .cleanup = engine_select_cleanup,
+};
--- /dev/null
+/* IOEngine_win32.c - IOMultiplexer
+ * Copyright (C) 2012 Philipp Kreil (pk910)
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+#include "IOEngine.h"
+
+#ifdef WIN32
+
+#define _WIN32_WINNT 0x501
+#include <windows.h>
+#include <winsock2.h>
+
+/* This is massively kludgy. Unfortunately, the only performant I/O
+ * multiplexer with halfway decent semantics under Windows is
+ * WSAAsyncSelect() -- which requires a window that can receive
+ * messages.
+ *
+ * So ioset_win32_init() creates a hidden window and sets it up for
+ * asynchronous socket notifications.
+ */
+
+#define IDT_TIMER1 1000
+#define IDT_TIMER2 1001
+#define IDT_SOCKET 1002
+
+static HWND ioset_window;
+
+static struct IODescriptor *engine_win32_get_iofd(int fd) {
+ struct IODescriptor *iofd;
+ for(iofd = first_descriptor; iofd; iofd = iofd->next) {
+ if(iofd->fd == fd)
+ return iofd;
+ }
+ return NULL;
+}
+
+static LRESULT CALLBACK engine_win32_wndproc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
+ struct IODescriptor *iofd;
+ int events;
+ struct timeval now, tdiff;
+
+ gettimeofday(&now, NULL);
+
+ if (hWnd == ioset_window) switch (uMsg)
+ {
+ case IDT_TIMER1:
+ return 0;
+ case IDT_TIMER2:
+ //User Timer
+ while(timer_priority) {
+ tdiff.tv_sec = timer_priority->timeout.tv_sec - now.tv_sec;
+ tdiff.tv_usec = timer_priority->timeout.tv_usec - now.tv_usec;
+ if(tdiff.tv_sec < 0 || (tdiff.tv_sec == 0 && tdiff.tv_usec <= 0)) {
+ if(timer_priority->constant_timeout) {
+ tdiff.tv_sec = 0;
+ iohandler_set_timeout(timer_priority, &tdiff);
+ iohandler_events(timer_priority, 0, 0);
+ } else {
+ iohandler_events(timer_priority, 0, 0);
+ iohandler_close(timer_priority); //also sets timer_priority to the next timed element
+ }
+ continue;
+ }
+ break;
+ }
+ return 0;
+ case IDT_SOCKET:
+ iofd = engine_win32_get_iofd(wParam);
+ events = WSAGETSELECTEVENT(lParam);
+
+ iohandler_events(iofd, (events & (FD_READ | FD_ACCEPT | FD_CLOSE)) != 0, (events & (FD_WRITE | FD_CONNECT)) != 0);
+ return 0;
+ case WM_QUIT:
+ return 0;
+ }
+ return DefWindowProc(hWnd, uMsg, wParam, lParam);
+}
+
+static int engine_win32_init() {
+ WNDCLASSEX wcx;
+ HINSTANCE hinst;
+ WSADATA wsadata;
+
+ // Start Windows Sockets.
+ if (WSAStartup(MAKEWORD(2, 0), &wsadata)) {
+ iohandler_log(IOLOG_FATAL, "Unable to start Windows Sockets");
+ return 0;
+ }
+
+ // Get Windows HINSTANCE.
+ hinst = GetModuleHandle(NULL);
+
+ // Describe and register a window class.
+ memset(&wcx, 0, sizeof(wcx));
+ wcx.cbSize = sizeof(wcx);
+ wcx.lpfnWndProc = engine_win32_wndproc;
+ wcx.hInstance = hinst;
+ wcx.lpszClassName = "IOMultiplexerMainWindow";
+ if (!RegisterClassEx(&wcx))
+ return 0;
+
+ ioset_window = CreateWindow("IOMultiplexerMainWindow", "IOMultiplexer", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hinst, NULL);
+ if (!ioset_window)
+ return 0;
+ return 1;
+}
+
+static long engine_win32_events(struct IODescriptor *iofd) {
+ switch (iofd->state) {
+ case IO_CLOSED:
+ return 0;
+ case IO_LISTENING:
+ return FD_ACCEPT;
+ case IO_CONNECTING:
+ return FD_CONNECT;
+ case IO_CONNECTED:
+ case IO_SSLWAIT:
+ return FD_READ | FD_CLOSE | (iohandler_wants_writes(iofd) ? FD_WRITE : 0);
+ }
+ return 0;
+}
+
+static void engine_win32_update(struct IODescriptor *iofd) {
+ long events;
+
+ if(iofd->type == IOTYPE_STDIN)
+ return;
+
+ events = engine_win32_events(iofd);
+ WSAAsyncSelect(iofd->fd, ioset_window, IDT_SOCKET, events);
+}
+
+static void engine_win32_add(struct IODescriptor *iofd) {
+ if(iofd->type == IOTYPE_STDIN)
+ return;
+
+ engine_win32_update(iofd);
+}
+
+static void engine_win32_remove(struct IODescriptor *iofd) {
+ unsigned long ulong;
+
+ if(iofd->type == IOTYPE_STDIN)
+ return;
+
+ WSAAsyncSelect(iofd->fd, ioset_window, IDT_SOCKET, 0);
+
+ ulong = 0;
+ ioctlsocket(iofd->fd, FIONBIO, &ulong);
+}
+
+static void engine_win32_loop(struct timeval *timeout) {
+ MSG msg;
+ BOOL not_really_bool;
+ int msec, cmsec, sett2;
+ struct timeval now, tdiff;
+ struct IODescriptor *iofd, *tmp_iofd;
+
+ gettimeofday(&now, NULL);
+
+ for(iofd = first_descriptor; iofd; iofd = tmp_iofd) {
+ tmp_iofd = iofd->next;
+ if(iofd->type == IOTYPE_STDIN) {
+ #ifdef WIN32
+ //WIN32 doesn't support stdin within select
+ //just try to read the single events from the console
+ DWORD dwRead;
+ INPUT_RECORD inRecords[128];
+ unsigned int i;
+ int read_bytes = 0;
+ GetNumberOfConsoleInputEvents(GetStdHandle(STD_INPUT_HANDLE), &dwRead);
+ if(dwRead)
+ ReadConsoleInput(GetStdHandle(STD_INPUT_HANDLE), &inRecords[0], 128, &dwRead);
+ for (i = 0; i < dwRead; ++i) {
+ if (inRecords[i].EventType == KEY_EVENT) {
+ const char c = inRecords[i].Event.KeyEvent.uChar.AsciiChar;
+ if (inRecords[i].Event.KeyEvent.bKeyDown && c != 0) {
+ iofd->readbuf.buffer[iofd->readbuf.bufpos + read_bytes] = c;
+ read_bytes++;
+ }
+ }
+ }
+ if(read_bytes)
+ iohandler_events(iofd, read_bytes, 0);
+ if(read_bytes >= 128) {
+ timeout->tv_sec = 0;
+ timeout->tv_usec = 1;
+ //minimal timeout
+ } else {
+ timeout->tv_sec = 0;
+ timeout->tv_usec = 100000;
+ }
+ #else
+ if(iofd->fd > fds_size)
+ fds_size = iofd->fd;
+ FD_SET(iofd->fd, &read_fds);
+ #endif
+ }
+ }
+
+ // Make sure we are woken up after the appropriate time.
+ msec = (timeout->tv_sec * 1000) + (timeout->tv_usec / 1000);
+ SetTimer(ioset_window, IDT_TIMER1, msec, NULL);
+
+ //set additional User Timer (if ther's one)
+ sett2 = 0;
+ while(timer_priority) {
+ tdiff.tv_sec = timer_priority->timeout.tv_sec - now.tv_sec;
+ tdiff.tv_usec = timer_priority->timeout.tv_usec - now.tv_usec;
+ if(tdiff.tv_sec < 0 || (tdiff.tv_sec == 0 && tdiff.tv_usec < 100)) {
+ if(timer_priority->constant_timeout) {
+ tdiff.tv_sec = 0;
+ iohandler_set_timeout(timer_priority, &tdiff);
+ iohandler_events(timer_priority, 0, 0);
+ } else {
+ iohandler_events(timer_priority, 0, 0);
+ iohandler_close(timer_priority); //also sets timer_priority to the next timed element
+ }
+ continue;
+ } else if(tdiff.tv_usec < 0) {
+ tdiff.tv_sec--;
+ tdiff.tv_usec += 1000000; //1 sec
+ }
+ cmsec = (tdiff.tv_sec * 1000) + (tdiff.tv_usec / 1000);
+ if(cmsec < msec) {
+ sett2 = 1;
+ msec = cmsec;
+ }
+ break;
+ }
+ if(sett2)
+ SetTimer(ioset_window, IDT_TIMER2, msec, NULL);
+
+ // Do a blocking read of the message queue.
+ not_really_bool = GetMessage(&msg, NULL, 0, 0);
+ KillTimer(ioset_window, IDT_TIMER1);
+ if(sett2)
+ KillTimer(ioset_window, IDT_TIMER2);
+ if (not_really_bool <=0)
+ return;
+ else {
+ TranslateMessage(&msg);
+ DispatchMessage(&msg);
+ }
+}
+
+static void engine_win32_cleanup() {
+ DestroyWindow(ioset_window);
+ ioset_window = NULL;
+ WSACleanup();
+}
+
+struct IOEngine engine_win32 = {
+ .name = "win32",
+ .init = engine_win32_init,
+ .add = engine_win32_add,
+ .remove = engine_win32_remove,
+ .update = engine_win32_update,
+ .loop = engine_win32_loop,
+ .cleanup = engine_win32_cleanup,
+};
+
+#else
+
+struct IOEngine engine_win32 = {
+ .name = "win32",
+ .init = NULL,
+ .add = NULL,
+ .remove = NULL,
+ .update = NULL,
+ .loop = NULL,
+ .cleanup = NULL,
+};
+
+#endif
--- /dev/null
+/* IOHandler.c - IOMultiplexer
+ * Copyright (C) 2012 Philipp Kreil (pk910)
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+#include "IOHandler.h"
+#include "IOEngine.h"
+#include "IOHandler_SSL.h"
+#include <errno.h>
+#include <stdio.h>
+#include <unistd.h>
+#ifdef WIN32
+#define _WIN32_WINNT 0x501
+#include <windows.h>
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#else
+#include <signal.h>
+#include <stdarg.h>
+#include <stdlib.h>
+#include <string.h>
+#include <netdb.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <netinet/tcp.h>
+#include <fcntl.h>
+#endif
+
+#ifndef EWOULDBLOCK
+#define EWOULDBLOCK EAGAIN
+#endif
+
+#define MAXLOG 1024
+iohandler_log_callback *iolog_backend = NULL;
+
+struct IODescriptor *first_descriptor = NULL;
+struct IODescriptor *timer_priority = NULL;
+
+#ifdef HAVE_PTHREAD_H
+static pthread_mutex_t io_thread_sync;
+static pthread_mutex_t io_poll_sync;
+#endif
+
+void iohandler_log(enum IOLogType type, char *text, ...) {
+ va_list arg_list;
+ char logBuf[MAXLOG+1];
+ int pos;
+ logBuf[0] = '\0';
+ va_start(arg_list, text);
+ pos = vsnprintf(logBuf, MAXLOG - 1, text, arg_list);
+ va_end(arg_list);
+ if (pos < 0 || pos > (MAXLOG - 1)) pos = MAXLOG - 1;
+ logBuf[pos] = '\n';
+ logBuf[pos+1] = '\0';
+
+ if(iolog_backend)
+ iolog_backend(type, logBuf);
+}
+
+/* IO Engines */
+extern struct IOEngine engine_select; /* select system call (should always be useable) */
+extern struct IOEngine engine_kevent;
+extern struct IOEngine engine_epoll;
+extern struct IOEngine engine_win32;
+
+int iohandler_settings = 0;
+struct IOEngine *engine = NULL;
+
+void iohandler_set(int setting, int value) {
+ if(value)
+ iohandler_settings |= setting;
+ else
+ iohandler_settings &= ~setting;
+}
+
+static void iohandler_init_engine() {
+ if(engine) return;
+ IOTHREAD_MUTEX_INIT(io_thread_sync);
+ IOTHREAD_MUTEX_INIT(io_poll_sync);
+
+ //try other engines
+ if(!(iohandler_settings & IOHANDLER_SETTING_HIGH_PRECISION_TIMER)) {
+ if(!engine && engine_kevent.init && engine_kevent.init())
+ engine = &engine_kevent;
+ if(!engine && engine_epoll.init && engine_epoll.init())
+ engine = &engine_epoll;
+ if(!engine && engine_win32.init && engine_win32.init())
+ engine = &engine_win32;
+ }
+
+ if (!engine) {
+ if(engine_select.init())
+ engine = &engine_select;
+ else {
+ iohandler_log(IOLOG_FATAL, "found no useable IO engine");
+ return;
+ }
+ }
+ iohandler_log(IOLOG_DEBUG, "using %s IO engine", engine->name);
+ iohandler_ssl_init();
+}
+
+static void iohandler_append(struct IODescriptor *descriptor) {
+ IOSYNCHRONIZE(io_thread_sync);
+ struct timeval *timeout = ((descriptor->timeout.tv_sec || descriptor->timeout.tv_usec) ? &descriptor->timeout : NULL);
+ if(timeout) {
+ struct IODescriptor *iofd;
+ int set_priority = 1;
+ descriptor->timeout = *timeout;
+ if(timer_priority)
+ iofd = timer_priority;
+ else
+ iofd = first_descriptor;
+ if(iofd) {
+ for(;;iofd = iofd->next) {
+ if(timeval_is_smaler(timeout, (&iofd->timeout))) {
+ descriptor->prev = iofd->prev;
+ descriptor->next = iofd;
+ if(iofd->prev)
+ iofd->prev->next = descriptor;
+ iofd->prev = descriptor;
+ if(set_priority)
+ timer_priority = descriptor;
+ break;
+ }
+ if(iofd == timer_priority)
+ set_priority = 0;
+ if(iofd->next == NULL) {
+ descriptor->next = NULL;
+ descriptor->prev = iofd;
+ iofd->next = descriptor;
+ if(set_priority)
+ timer_priority = descriptor;
+ break;
+ }
+ }
+ } else {
+ descriptor->prev = NULL;
+ descriptor->next = NULL;
+ first_descriptor = descriptor;
+ timer_priority = descriptor;
+ }
+
+ } else {
+ descriptor->prev = NULL;
+ descriptor->next = first_descriptor;
+ if(first_descriptor)
+ first_descriptor->prev = descriptor;
+ first_descriptor = descriptor;
+ }
+ IODESYNCHRONIZE(io_thread_sync);
+}
+
+static void iohandler_remove(struct IODescriptor *descriptor, int engine_remove) {
+ //remove IODescriptor from the list
+ IOSYNCHRONIZE(io_thread_sync);
+ if(descriptor->prev)
+ descriptor->prev->next = descriptor->next;
+ else
+ first_descriptor = descriptor->next;
+ if(descriptor->next)
+ descriptor->next->prev = descriptor->prev;
+ if(descriptor == timer_priority)
+ timer_priority = descriptor->next;
+
+ if(engine_remove)
+ engine->remove(descriptor);
+ if(descriptor->readbuf.buffer)
+ free(descriptor->readbuf.buffer);
+ if(descriptor->writebuf.buffer)
+ free(descriptor->writebuf.buffer);
+ iohandler_log(IOLOG_DEBUG, "removed IODescriptor (%d) of type `%s`", descriptor->fd, iohandler_iotype_name(descriptor->type));
+ free(descriptor);
+ IODESYNCHRONIZE(io_thread_sync);
+}
+
+struct IODescriptor *iohandler_add(int sockfd, enum IOType type, struct timeval *timeout, iohandler_callback *callback) {
+ //just add a new IODescriptor
+ struct IODescriptor *descriptor = calloc(1, sizeof(*descriptor));
+ if(!descriptor) {
+ iohandler_log(IOLOG_ERROR, "could not allocate memory for IODescriptor in %s:%d", __FILE__, __LINE__);
+ return NULL;
+ }
+ descriptor->fd = (type == IOTYPE_STDIN ? fileno(stdin) : sockfd);
+ descriptor->type = type;
+ descriptor->state = (type == IOTYPE_STDIN ? IO_CONNECTED : IO_CLOSED);
+ descriptor->callback = callback;
+ if(timeout) {
+ descriptor->timeout = *timeout;
+ if(descriptor->timeout.tv_usec > 1000000) {
+ descriptor->timeout.tv_usec -= 1000000;
+ descriptor->timeout.tv_sec++;
+ }
+ }
+ if(type != IOTYPE_TIMER) {
+ descriptor->readbuf.buffer = malloc(IO_READ_BUFLEN + 2);
+ descriptor->readbuf.bufpos = 0;
+ descriptor->readbuf.buflen = IO_READ_BUFLEN;
+ descriptor->writebuf.buffer = malloc(IO_READ_BUFLEN + 2);
+ descriptor->writebuf.bufpos = 0;
+ descriptor->writebuf.buflen = IO_READ_BUFLEN;
+ }
+
+ if(!engine) {
+ iohandler_init_engine();
+ if(!engine) {
+ return NULL;
+ }
+ }
+ engine->add(descriptor);
+
+ //add IODescriptor to the list
+ iohandler_append(descriptor);
+
+ iohandler_log(IOLOG_DEBUG, "added custom socket descriptor (%d) as type `%s`", sockfd, iohandler_iotype_name(type));
+ return descriptor;
+}
+
+void iohandler_set_timeout(struct IODescriptor *descriptor, struct timeval *timeout) {
+ if(descriptor->prev)
+ descriptor->prev->next = descriptor->next;
+ else
+ first_descriptor = descriptor->next;
+ if(descriptor->next)
+ descriptor->next->prev = descriptor->prev;
+ if(descriptor == timer_priority)
+ timer_priority = descriptor->next;
+ if(timeout && timeout->tv_sec == 0 && descriptor->constant_timeout) {
+ descriptor->timeout.tv_usec += (descriptor->constant_timeout % 1000) * 1000;
+ descriptor->timeout.tv_sec += (descriptor->constant_timeout / 1000);
+ if(descriptor->timeout.tv_usec > 1000000) {
+ descriptor->timeout.tv_sec += (descriptor->timeout.tv_usec / 1000000);
+ descriptor->timeout.tv_usec %= 1000000;
+ }
+ } else if(timeout) {
+ descriptor->timeout = *timeout;
+ if(descriptor->timeout.tv_usec > 1000000) {
+ descriptor->timeout.tv_usec -= 1000000;
+ descriptor->timeout.tv_sec++;
+ }
+ } else {
+ descriptor->timeout.tv_sec = 0;
+ descriptor->timeout.tv_usec = 0;
+ }
+ iohandler_append(descriptor);
+}
+
+static void iohandler_increase_iobuf(struct IOBuffer *iobuf, size_t required) {
+ if(iobuf->buflen >= required) return;
+ char *new_buf = realloc(iobuf->buffer, required + 2);
+ if(new_buf) {
+ iobuf->buffer = new_buf;
+ iobuf->buflen = required;
+ }
+}
+
+struct IODescriptor *iohandler_timer(struct timeval timeout, iohandler_callback *callback) {
+ struct IODescriptor *descriptor;
+ descriptor = iohandler_add(-1, IOTYPE_TIMER, &timeout, callback);
+ if(!descriptor) {
+ iohandler_log(IOLOG_ERROR, "could not allocate memory for IODescriptor in %s:%d", __FILE__, __LINE__);
+ return NULL;
+ }
+ iohandler_log(IOLOG_DEBUG, "added timer descriptor (sec: %d; usec: %d)", timeout.tv_sec, timeout.tv_usec);
+ return descriptor;
+}
+
+struct IODescriptor *iohandler_constant_timer(int msec, iohandler_callback *callback) {
+ struct IODescriptor *descriptor;
+ struct timeval timeout;
+ gettimeofday(&timeout, NULL);
+ timeout.tv_usec += (msec % 1000) * 1000;
+ timeout.tv_sec += (msec / 1000);
+ if(timeout.tv_usec > 1000000) {
+ timeout.tv_sec += (timeout.tv_usec / 1000000);
+ timeout.tv_usec %= 1000000;
+ }
+ descriptor = iohandler_add(-1, IOTYPE_TIMER, &timeout, callback);
+ if(!descriptor) {
+ iohandler_log(IOLOG_ERROR, "could not allocate memory for IODescriptor in %s:%d", __FILE__, __LINE__);
+ return NULL;
+ }
+ descriptor->constant_timeout = msec;
+ iohandler_log(IOLOG_DEBUG, "added timer descriptor (sec: %d; usec: %d)", timeout.tv_sec, timeout.tv_usec);
+ return descriptor;
+}
+
+struct IODescriptor *iohandler_connect(const char *hostname, unsigned int port, int ssl, const char *bindhost, iohandler_callback *callback) {
+ return iohandler_connect_flags(hostname, port, ssl, bindhost, callback, IOHANDLER_CONNECT_IPV4 | IOHANDLER_CONNECT_IPV6);
+}
+
+struct IODescriptor *iohandler_connect_flags(const char *hostname, unsigned int port, int ssl, const char *bindhost, iohandler_callback *callback, int flags) {
+ //non-blocking connect
+ int sockfd, result;
+ struct addrinfo hints, *res;
+ struct sockaddr_in *ip4 = NULL;
+ struct sockaddr_in6 *ip6 = NULL;
+ size_t dstaddrlen;
+ struct sockaddr *dstaddr = NULL;
+ struct IODescriptor *descriptor;
+
+ if(!engine) {
+ iohandler_init_engine();
+ if(!engine) return NULL;
+ }
+ memset (&hints, 0, sizeof (hints));
+ hints.ai_family = PF_UNSPEC;
+ hints.ai_socktype = SOCK_STREAM;
+ hints.ai_flags |= AI_CANONNAME;
+ if ((result = getaddrinfo (hostname, NULL, &hints, &res))) {
+ iohandler_log(IOLOG_ERROR, "could not resolve %s to an IP address (%d)", hostname, result);
+ return NULL;
+ }
+ while (res) {
+ switch (res->ai_family) {
+ case AF_INET:
+ ip4 = (struct sockaddr_in *) res->ai_addr;
+ break;
+ case AF_INET6:
+ ip6 = (struct sockaddr_in6 *) res->ai_addr;
+ break;
+ }
+ res = res->ai_next;
+ freeaddrinfo(res);
+ }
+
+ if(ip6 && (flags & IOHANDLER_CONNECT_IPV6)) {
+ sockfd = socket(AF_INET6, SOCK_STREAM, 0);
+ if(sockfd == -1) {
+ iohandler_log(IOLOG_ERROR, "could not create socket in %s:%d", __FILE__, __LINE__);
+ return NULL;
+ }
+
+ ip6->sin6_family = AF_INET6;
+ ip6->sin6_port = htons(port);
+
+ struct sockaddr_in6 *ip6vhost = NULL;
+ if (bindhost && !getaddrinfo(bindhost, NULL, &hints, &res)) {
+ while (res) {
+ switch (res->ai_family) {
+ case AF_INET6:
+ ip6vhost = (struct sockaddr_in6 *) res->ai_addr;
+ break;
+ }
+ res = res->ai_next;
+ freeaddrinfo(res);
+ }
+ }
+ if(ip6vhost) {
+ ip6vhost->sin6_family = AF_INET6;
+ ip6vhost->sin6_port = htons(0);
+ bind(sockfd, (struct sockaddr*)ip6vhost, sizeof(*ip6vhost));
+ }
+ dstaddr = (struct sockaddr*)ip6;
+ dstaddrlen = sizeof(*ip6);
+ } else if(ip4 && (flags & IOHANDLER_CONNECT_IPV4)) {
+ sockfd = socket(AF_INET, SOCK_STREAM, 0);
+ if(sockfd == -1) {
+ iohandler_log(IOLOG_ERROR, "could not create socket in %s:%d", __FILE__, __LINE__);
+ return NULL;
+ }
+
+ ip4->sin_family = AF_INET;
+ ip4->sin_port = htons(port);
+
+ struct sockaddr_in *ip4vhost = NULL;
+ if (bindhost && !getaddrinfo(bindhost, NULL, &hints, &res)) {
+ while (res) {
+ switch (res->ai_family) {
+ case AF_INET:
+ ip4vhost = (struct sockaddr_in *) res->ai_addr;
+ break;
+ }
+ res = res->ai_next;
+ freeaddrinfo(res);
+ }
+ }
+ if(ip4vhost) {
+ ip4vhost->sin_family = AF_INET;
+ ip4vhost->sin_port = htons(0);
+ bind(sockfd, (struct sockaddr*)ip4vhost, sizeof(*ip4vhost));
+ }
+ dstaddr = (struct sockaddr*)ip4;
+ dstaddrlen = sizeof(*ip4);
+ } else
+ return NULL;
+ //prevent SIGPIPE
+ #ifndef WIN32
+ #if defined(SO_NOSIGPIPE)
+ {
+ int set = 1;
+ setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&set, sizeof(int));
+ }
+ #else
+ signal(SIGPIPE, SIG_IGN);
+ #endif
+ #endif
+ //make sockfd unblocking
+ #if defined(F_GETFL)
+ {
+ int fcntl_flags;
+ fcntl_flags = fcntl(sockfd, F_GETFL);
+ fcntl(sockfd, F_SETFL, fcntl_flags|O_NONBLOCK);
+ fcntl_flags = fcntl(sockfd, F_GETFD);
+ fcntl(sockfd, F_SETFD, fcntl_flags|FD_CLOEXEC);
+ }
+ #else
+ /* I hope you're using the Win32 backend or something else that
+ * automatically marks the file descriptor non-blocking...
+ */
+ #endif
+ descriptor = iohandler_add(sockfd, IOTYPE_CLIENT, NULL, callback);
+ if(!descriptor) {
+ close(sockfd);
+ return NULL;
+ }
+ connect(sockfd, dstaddr, dstaddrlen); //returns EINPROGRESS here (nonblocking)
+ descriptor->state = IO_CONNECTING;
+ descriptor->ssl = (ssl ? 1 : 0);
+ descriptor->read_lines = 1;
+ engine->update(descriptor);
+ iohandler_log(IOLOG_DEBUG, "added client socket (%d) connecting to %s:%d", sockfd, hostname, port);
+ return descriptor;
+}
+
+struct IODescriptor *iohandler_listen(const char *hostname, unsigned int port, iohandler_callback *callback) {
+ return iohandler_listen_flags(hostname, port, callback, IOHANDLER_LISTEN_IPV4 | IOHANDLER_LISTEN_IPV6);
+}
+
+struct IODescriptor *iohandler_listen_flags(const char *hostname, unsigned int port, iohandler_callback *callback, int flags) {
+ int sockfd;
+ struct addrinfo hints, *res;
+ struct sockaddr_in *ip4 = NULL;
+ struct sockaddr_in6 *ip6 = NULL;
+ struct IODescriptor *descriptor;
+ unsigned int opt;
+
+ if(!engine) {
+ iohandler_init_engine();
+ if(!engine) return NULL;
+ }
+ memset (&hints, 0, sizeof (hints));
+ hints.ai_family = PF_UNSPEC;
+ hints.ai_socktype = SOCK_STREAM;
+ hints.ai_flags |= AI_CANONNAME;
+ if (getaddrinfo (hostname, NULL, &hints, &res)) {
+ return NULL;
+ }
+ while (res) {
+ switch (res->ai_family) {
+ case AF_INET:
+ ip4 = (struct sockaddr_in *) res->ai_addr;
+ break;
+ case AF_INET6:
+ ip6 = (struct sockaddr_in6 *) res->ai_addr;
+ break;
+ }
+ res = res->ai_next;
+ freeaddrinfo(res);
+ }
+
+ if(ip6 && (flags & IOHANDLER_LISTEN_IPV6)) {
+ sockfd = socket(AF_INET6, SOCK_STREAM, 0);
+ if(sockfd == -1) return NULL;
+
+ opt = 1;
+ setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt));
+
+ ip6->sin6_family = AF_INET6;
+ ip6->sin6_port = htons(port);
+
+ bind(sockfd, (struct sockaddr*)ip6, sizeof(*ip6));
+ } else if(ip4 && (flags & IOHANDLER_LISTEN_IPV4)) {
+ sockfd = socket(AF_INET, SOCK_STREAM, 0);
+ if(sockfd == -1) return NULL;
+
+ opt = 1;
+ setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt));
+
+ ip4->sin_family = AF_INET;
+ ip4->sin_port = htons(port);
+
+ bind(sockfd, (struct sockaddr*)ip4, sizeof(*ip4));
+ } else
+ return NULL;
+ //prevent SIGPIPE
+ #ifndef WIN32
+ #if defined(SO_NOSIGPIPE)
+ {
+ int set = 1;
+ setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&set, sizeof(int));
+ }
+ #else
+ signal(SIGPIPE, SIG_IGN);
+ #endif
+ #endif
+ //make sockfd unblocking
+ #if defined(F_GETFL)
+ {
+ int flag;
+ flag = fcntl(sockfd, F_GETFL);
+ fcntl(sockfd, F_SETFL, flag|O_NONBLOCK);
+ flag = fcntl(sockfd, F_GETFD);
+ fcntl(sockfd, F_SETFD, flag|FD_CLOEXEC);
+ }
+ #else
+ /* I hope you're using the Win32 backend or something else that
+ * automatically marks the file descriptor non-blocking...
+ */
+ #endif
+ descriptor = iohandler_add(sockfd, IOTYPE_SERVER, NULL, callback);
+ if(!descriptor) {
+ close(sockfd);
+ return NULL;
+ }
+ listen(sockfd, 1);
+ descriptor->state = IO_LISTENING;
+ engine->update(descriptor);
+ iohandler_log(IOLOG_DEBUG, "added server socket (%d) listening on %s:%d", sockfd, hostname, port);
+ return descriptor;
+}
+
+struct IODescriptor *iohandler_listen_ssl(const char *hostname, unsigned int port, const char *certfile, const char *keyfile, iohandler_callback *callback) {
+ return iohandler_listen_ssl_flags(hostname, port, certfile, keyfile, callback, IOHANDLER_LISTEN_IPV4 | IOHANDLER_LISTEN_IPV6);
+}
+
+struct IODescriptor *iohandler_listen_ssl_flags(const char *hostname, unsigned int port, const char *certfile, const char *keyfile, iohandler_callback *callback, int flags) {
+ struct IODescriptor *descriptor = iohandler_listen_flags(hostname, port, callback, flags);
+ if(!descriptor)
+ return NULL;
+ //SSL Server Socket
+ iohandler_ssl_listen(descriptor, certfile, keyfile);
+ if(descriptor->sslnode)
+ descriptor->ssl = 1;
+ return descriptor;
+}
+
+void iohandler_write(struct IODescriptor *iofd, const char *line) {
+ size_t linelen = strlen(line);
+ iohandler_send(iofd, line, linelen);
+}
+
+void iohandler_send(struct IODescriptor *iofd, const char *data, size_t datalen) {
+ if(iofd->type == IOTYPE_TIMER || iofd->state == IO_CLOSED) {
+ iohandler_log(IOLOG_ERROR, "could not write to socket (%s)", (iofd->type == IOTYPE_TIMER ? "IOTYPE_TIMER" : "IO_CLOSED"));
+ return;
+ }
+ iohandler_log(IOLOG_DEBUG, "add %d to writebuf (fd: %d): %s", datalen, iofd->fd, data);
+ if(iofd->writebuf.buflen < iofd->writebuf.bufpos + datalen) {
+ iohandler_log(IOLOG_DEBUG, "increase writebuf (curr: %d) to %d (+%d bytes)", iofd->writebuf.buflen, iofd->writebuf.bufpos + datalen, (iofd->writebuf.bufpos + datalen - iofd->writebuf.buflen));
+ iohandler_increase_iobuf(&iofd->writebuf, iofd->writebuf.bufpos + datalen);
+ if(iofd->writebuf.buflen < iofd->writebuf.bufpos + datalen) {
+ iohandler_log(IOLOG_ERROR, "increase writebuf (curr: %d) to %d (+%d bytes) FAILED", iofd->writebuf.buflen, iofd->writebuf.bufpos + datalen, (iofd->writebuf.bufpos + datalen - iofd->writebuf.buflen));
+ return;
+ }
+ }
+ memcpy(iofd->writebuf.buffer + iofd->writebuf.bufpos, data, datalen);
+ iofd->writebuf.bufpos += datalen;
+ engine->update(iofd);
+}
+
+void iohandler_printf(struct IODescriptor *iofd, const char *text, ...) {
+ va_list arg_list;
+ char sendBuf[IO_LINE_LEN];
+ int pos;
+ sendBuf[0] = '\0';
+ va_start(arg_list, text);
+ pos = vsnprintf(sendBuf, IO_LINE_LEN - 2, text, arg_list);
+ va_end(arg_list);
+ if (pos < 0 || pos > (IO_LINE_LEN - 2)) pos = IO_LINE_LEN - 2;
+ sendBuf[pos] = '\n';
+ sendBuf[pos+1] = '\0';
+ iohandler_send(iofd, sendBuf, pos+1);
+}
+
+static int iohandler_try_write(struct IODescriptor *iofd) {
+ if(!iofd->writebuf.bufpos) return 0;
+ iohandler_log(IOLOG_DEBUG, "write writebuf (%d bytes) to socket (fd: %d)", iofd->writebuf.bufpos, iofd->fd);
+ int res;
+ if(iofd->ssl_active)
+ res = iohandler_ssl_write(iofd, iofd->writebuf.buffer, iofd->writebuf.bufpos);
+ else
+ res = send(iofd->fd, iofd->writebuf.buffer, iofd->writebuf.bufpos, 0);
+ if(res < 0) {
+ if (errno != EAGAIN && errno != EWOULDBLOCK)
+ iohandler_log(IOLOG_ERROR, "could not write to socket (fd: %d): %d - %s", iofd->fd, errno, strerror(errno));
+ else
+ res = 0;
+ } else {
+ iofd->writebuf.bufpos -= res;
+ if(iofd->state != IO_CLOSED)
+ engine->update(iofd);
+ }
+ return res;
+}
+
+void iohandler_close(struct IODescriptor *iofd) {
+ int engine_remove = 1;
+ iofd->state = IO_CLOSED;
+ if(iofd->writebuf.bufpos) {
+ //try to send everything before closing
+#if defined(F_GETFL)
+ {
+ int flags;
+ flags = fcntl(iofd->fd, F_GETFL);
+ fcntl(iofd->fd, F_SETFL, flags & ~O_NONBLOCK);
+ flags = fcntl(iofd->fd, F_GETFD);
+ fcntl(iofd->fd, F_SETFD, flags|FD_CLOEXEC);
+ }
+#else
+ engine_remove = 0;
+ engine->remove(iofd);
+#endif
+ iohandler_try_write(iofd);
+ }
+ //close IODescriptor
+ if(iofd->ssl)
+ iohandler_ssl_disconnect(iofd);
+ if(iofd->type == IOTYPE_SERVER || iofd->type == IOTYPE_CLIENT || iofd->type == IOTYPE_STDIN)
+ close(iofd->fd);
+ iohandler_remove(iofd, engine_remove);
+}
+
+void iohandler_update(struct IODescriptor *iofd) {
+ iohandler_log(IOLOG_DEBUG, "external call to iohandler_update (fd: %d)", iofd->fd);
+ engine->update(iofd);
+}
+
+static void iohandler_trigger_event(struct IOEvent *event) {
+ if(!event->iofd->callback) return;
+ iohandler_log(IOLOG_DEBUG, "triggering event (%s) for %s (fd: %d)", iohandler_ioeventtype_name(event->type), iohandler_iotype_name(event->iofd->type), event->iofd->fd);
+ event->iofd->callback(event);
+}
+
+void iohandler_events(struct IODescriptor *iofd, int readable, int writeable) {
+ struct IOEvent callback_event;
+ callback_event.type = IOEVENT_IGNORE;
+ callback_event.iofd = iofd;
+ switch(iofd->state) {
+ case IO_SSLWAIT:
+ if(!readable && !writeable) {
+ if(!iofd->ssl_server_hs) {
+ callback_event.type = IOEVENT_SSLFAILED;
+ iofd->state = IO_CLOSED;
+ engine->update(iofd);
+ } else
+ iohandler_close(iofd);
+ } else if(iofd->ssl_server_hs) {
+ iohandler_log(IOLOG_DEBUG, "triggering iohandler_ssl_server_handshake for %s (fd: %d)", iohandler_iotype_name(iofd->type), iofd->fd);
+ iohandler_ssl_server_handshake(iofd);
+ } else {
+ iohandler_log(IOLOG_DEBUG, "triggering iohandler_ssl_client_handshake for %s (fd: %d)", iohandler_iotype_name(iofd->type), iofd->fd);
+ iohandler_ssl_client_handshake(iofd);
+ }
+ break;
+ case IO_CLOSED:
+ if(iofd->type == IOTYPE_TIMER)
+ callback_event.type = IOEVENT_TIMEOUT;
+ break;
+ case IO_LISTENING:
+ if(readable) {
+ callback_event.data.accept_fd = accept(iofd->fd, NULL, 0);
+ if(callback_event.data.accept_fd < 0) {
+ iohandler_log(IOLOG_ERROR, "could not accept client (server fd: %d): %d - %s", iofd->fd, errno, strerror(errno));
+ } else if(iofd->ssl) {
+ struct IODescriptor *client_iofd = iohandler_add(callback_event.data.accept_fd, IOTYPE_CLIENT, NULL, NULL);
+ iohandler_ssl_client_accepted(iofd, client_iofd);
+ } else
+ callback_event.type = IOEVENT_ACCEPT;
+ }
+ break;
+ case IO_CONNECTING:
+ if(readable) { //could not connect
+ callback_event.type = IOEVENT_NOTCONNECTED;
+ //socklen_t arglen;
+ //arglen = sizeof(callback_event.data.errid);
+ //if (getsockopt(iofd->fd, SOL_SOCKET, SO_ERROR, &callback_event.data.errid, &arglen) < 0)
+ // callback_event.data.errid = errno;
+ iofd->state = IO_CLOSED;
+ engine->update(iofd);
+ } else if(writeable) {
+ if(iofd->ssl && !iofd->ssl_active) {
+ iohandler_log(IOLOG_DEBUG, "triggering iohandler_ssl_connect for %s (fd: %d)", iohandler_iotype_name(iofd->type), iofd->fd);
+ iohandler_ssl_connect(iofd);
+ return;
+ }
+ if(iofd->ssl && iofd->ssl_server_hs) {
+ callback_event.type = IOEVENT_SSLACCEPT;
+ callback_event.iofd = iofd->data;
+ callback_event.data.accept_iofd = iofd;
+ iofd->data = NULL;
+ }
+ else
+ callback_event.type = IOEVENT_CONNECTED;
+ iofd->state = IO_CONNECTED;
+ engine->update(iofd);
+ }
+ break;
+ case IO_CONNECTED:
+ if(readable) {
+ if(iofd->read_lines) {
+ int bytes;
+
+ if(iofd->ssl_active)
+ bytes = iohandler_ssl_read(iofd, iofd->readbuf.buffer + iofd->readbuf.bufpos, iofd->readbuf.buflen - iofd->readbuf.bufpos);
+ else {
+ if(iofd->type == IOTYPE_STDIN)
+ #ifdef WIN32
+ bytes = readable;
+ #else
+ bytes = read(iofd->fd, iofd->readbuf.buffer + iofd->readbuf.bufpos, iofd->readbuf.buflen - iofd->readbuf.bufpos);
+ #endif
+ else
+ bytes = recv(iofd->fd, iofd->readbuf.buffer + iofd->readbuf.bufpos, iofd->readbuf.buflen - iofd->readbuf.bufpos, 0);
+ }
+ if(bytes <= 0) {
+ if (errno != EAGAIN || errno != EWOULDBLOCK) {
+ iofd->state = IO_CLOSED;
+ engine->update(iofd);
+ callback_event.type = IOEVENT_CLOSED;
+ callback_event.data.errid = errno;
+ }
+ } else {
+ int i, used_bytes = 0;
+ iohandler_log(IOLOG_DEBUG, "received %d bytes (fd: %d). readbuf position: %d", bytes, iofd->fd, iofd->readbuf.bufpos);
+ iofd->readbuf.bufpos += bytes;
+ callback_event.type = IOEVENT_RECV;
+ for(i = 0; i < iofd->readbuf.bufpos; i++) {
+ if(iofd->readbuf.buffer[i] == '\r' && iofd->readbuf.buffer[i+1] == '\n')
+ iofd->readbuf.buffer[i] = 0;
+ else if(iofd->readbuf.buffer[i] == '\n' || iofd->readbuf.buffer[i] == '\r') {
+ iofd->readbuf.buffer[i] = 0;
+ callback_event.data.recv_str = iofd->readbuf.buffer + used_bytes;
+ iohandler_log(IOLOG_DEBUG, "parsed line (%d bytes): %s", i - used_bytes, iofd->readbuf.buffer + used_bytes);
+ used_bytes = i+1;
+ iohandler_trigger_event(&callback_event);
+ } else if(i + 1 - used_bytes >= IO_LINE_LEN) { //512 max
+ iofd->readbuf.buffer[i] = 0;
+ callback_event.data.recv_str = iofd->readbuf.buffer + used_bytes;
+ iohandler_log(IOLOG_DEBUG, "parsed and stripped line (%d bytes): %s", i - used_bytes, iofd->readbuf.buffer + used_bytes);
+ for(; i < iofd->readbuf.bufpos; i++) { //skip the rest of the line
+ if(iofd->readbuf.buffer[i] == '\n' || (iofd->readbuf.buffer[i] == '\r' && iofd->readbuf.buffer[i+1] != '\n')) {
+ break;
+ }
+ }
+ used_bytes = i+1;
+ iohandler_trigger_event(&callback_event);
+ }
+ }
+ if(used_bytes) {
+ if(used_bytes == iofd->readbuf.bufpos) {
+ iofd->readbuf.bufpos = 0;
+ iohandler_log(IOLOG_DEBUG, "readbuf fully processed (set buffer position to 0)");
+ } else {
+ iohandler_log(IOLOG_DEBUG, "readbuf rest: %d bytes (used %d bytes)", iofd->readbuf.bufpos - used_bytes, used_bytes);
+ memmove(iofd->readbuf.buffer, iofd->readbuf.buffer + used_bytes, iofd->readbuf.bufpos - used_bytes);
+ iofd->readbuf.bufpos -= used_bytes;
+ }
+ }
+ callback_event.type = IOEVENT_IGNORE;
+ }
+ } else
+ callback_event.type = IOEVENT_READABLE;
+ }
+ if(writeable) {
+ int bytes;
+ bytes = iohandler_try_write(iofd);
+ if(bytes < 0) {
+ iofd->state = IO_CLOSED;
+ engine->update(iofd);
+ callback_event.type = IOEVENT_CLOSED;
+ callback_event.data.errid = errno;
+ }
+ }
+ break;
+ }
+ if(callback_event.type == IOEVENT_IGNORE && !readable && !writeable)
+ callback_event.type = IOEVENT_TIMEOUT;
+ if(callback_event.type != IOEVENT_IGNORE)
+ iohandler_trigger_event(&callback_event);
+}
+
+void iohandler_poll() {
+ struct timeval timeout;
+ timeout.tv_sec = IO_MAX_TIMEOUT;
+ timeout.tv_usec = 0;
+ iohandler_poll_timeout(timeout);
+}
+
+void iohandler_poll_timeout(struct timeval timeout) {
+ if(engine) {
+ IOSYNCHRONIZE(io_poll_sync); //quite senceless multithread support... better support will follow
+ engine->loop(&timeout);
+ IODESYNCHRONIZE(io_poll_sync);
+ }
+}
+
+//debugging functions
+char *iohandler_iotype_name(enum IOType type) {
+ switch(type) {
+ case IOTYPE_UNKNOWN:
+ return "IOTYPE_UNKNOWN";
+ case IOTYPE_SERVER:
+ return "IOTYPE_SERVER";
+ case IOTYPE_CLIENT:
+ return "IOTYPE_CLIENT";
+ case IOTYPE_STDIN:
+ return "IOTYPE_STDIN";
+ case IOTYPE_TIMER:
+ return "IOTYPE_TIMER";
+ default:
+ return "(UNDEFINED)";
+ }
+}
+
+char *iohandler_iostatus_name(enum IOStatus status) {
+ switch(status) {
+ case IO_CLOSED:
+ return "IO_CLOSED";
+ case IO_LISTENING:
+ return "IO_LISTENING";
+ case IO_CONNECTING:
+ return "IO_CONNECTING";
+ case IO_CONNECTED:
+ return "IO_CONNECTED";
+ case IO_SSLWAIT:
+ return "IO_SSLWAIT";
+ default:
+ return "(UNDEFINED)";
+ }
+}
+
+char *iohandler_ioeventtype_name(enum IOEventType type) {
+ switch(type) {
+ case IOEVENT_IGNORE:
+ return "IOEVENT_IGNORE";
+ case IOEVENT_READABLE:
+ return "IOEVENT_READABLE";
+ case IOEVENT_RECV:
+ return "IOEVENT_RECV";
+ case IOEVENT_CONNECTED:
+ return "IOEVENT_CONNECTED";
+ case IOEVENT_NOTCONNECTED:
+ return "IOEVENT_NOTCONNECTED";
+ case IOEVENT_CLOSED:
+ return "IOEVENT_CLOSED";
+ case IOEVENT_ACCEPT:
+ return "IOEVENT_ACCEPT";
+ case IOEVENT_SSLACCEPT:
+ return "IOEVENT_SSLACCEPT";
+ case IOEVENT_TIMEOUT:
+ return "IOEVENT_TIMEOUT";
+ default:
+ return "(UNDEFINED)";
+ }
+}
--- /dev/null
+/* IOHandler.h - IOMultiplexer
+ * Copyright (C) 2012 Philipp Kreil (pk910)
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+#ifndef _IOHandler_h
+#define _IOHandler_h
+#include <stddef.h>
+#include <sys/time.h> /* struct timeval */
+
+#define IO_READ_BUFLEN 1024
+#define IO_MAX_TIMEOUT 10
+#define IO_LINE_LEN 1024
+
+struct timeval;
+struct IODescriptor;
+struct IOEvent;
+struct IOSSLNode;
+
+enum IOLogType {
+ IOLOG_DEBUG,
+ IOLOG_WARNING,
+ IOLOG_ERROR,
+ IOLOG_FATAL
+};
+
+#define IOHANDLER_CALLBACK(NAME) void NAME(struct IOEvent *event)
+typedef IOHANDLER_CALLBACK(iohandler_callback);
+
+#define IOHANDLER_LOG_BACKEND(NAME) void NAME(enum IOLogType type, const char *line)
+typedef IOHANDLER_LOG_BACKEND(iohandler_log_callback);
+
+extern iohandler_log_callback *iolog_backend;
+
+enum IOType {
+ IOTYPE_UNKNOWN, /* ignore descriptor (uninitialized) */
+ IOTYPE_SERVER, /* server socket */
+ IOTYPE_CLIENT, /* client socket */
+ IOTYPE_STDIN, /* stdin */
+ IOTYPE_TIMER /* timer */
+};
+
+enum IOStatus {
+ IO_CLOSED, /* descriptor is dead (socket waiting for removal or timer) */
+ IO_LISTENING, /* descriptor is waiting for connections (server socket) */
+ IO_CONNECTING, /* descriptor is waiting for connection approval (connecting client socket) */
+ IO_CONNECTED, /* descriptor is connected (connected client socket) */
+ IO_SSLWAIT /* waiting for SSL backend (e.g. handshake) */
+};
+
+enum IOEventType {
+ IOEVENT_IGNORE,
+ IOEVENT_READABLE, /* socket is readable - not read anything yet, could also be disconnect notification */
+ IOEVENT_RECV, /* client socket received something (recv_str valid) */
+ IOEVENT_CONNECTED, /* client socket connected successful */
+ IOEVENT_NOTCONNECTED, /* client socket could not connect (errid valid) */
+ IOEVENT_CLOSED, /* client socket lost connection (errid valid) */
+ IOEVENT_ACCEPT, /* server socket accepted new connection (accept_fd valid) */
+ IOEVENT_SSLACCEPT, /* SSL server socket accepted new connection (accept_iofd valid) */
+ IOEVENT_TIMEOUT, /* timer timed out */
+ IOEVENT_SSLFAILED /* failed to initialize SSL session */
+};
+
+struct IOBuffer {
+ char *buffer;
+ size_t bufpos, buflen;
+};
+
+struct IODescriptor {
+ int fd;
+ enum IOType type;
+ enum IOStatus state;
+ struct timeval timeout;
+ int constant_timeout;
+ iohandler_callback *callback;
+ struct IOBuffer readbuf;
+ struct IOBuffer writebuf;
+ void *data;
+ int read_lines : 1;
+ int ssl : 1;
+ int ssl_server_hs : 1;
+ int ssl_active : 1;
+ int ssl_hs_read : 1;
+ int ssl_hs_write : 1;
+ struct IOSSLNode *sslnode;
+
+ struct IODescriptor *next, *prev;
+};
+
+struct IOEvent {
+ enum IOEventType type;
+ struct IODescriptor *iofd;
+ union {
+ char *recv_str;
+ int accept_fd;
+ int errid;
+ struct IODescriptor *accept_iofd;
+ } data;
+};
+
+#define IOHANDLER_LISTEN_IPV4 0x01
+#define IOHANDLER_LISTEN_IPV6 0x02 /* overrides IOHANDLER_LISTEN_IPV4 */
+
+#define IOHANDLER_CONNECT_IPV4 0x01
+#define IOHANDLER_CONNECT_IPV6 0x02 /* overrides IOHANDLER_CONNECT_IPV4 */
+
+#define IOHANDLER_SETTING_HIGH_PRECISION_TIMER 0x01
+
+void iohandler_set(int setting, int value);
+
+struct IODescriptor *iohandler_add(int sockfd, enum IOType type, struct timeval *timeout, iohandler_callback *callback);
+struct IODescriptor *iohandler_timer(struct timeval timeout, iohandler_callback *callback);
+struct IODescriptor *iohandler_constant_timer(int msec, iohandler_callback *callback);
+struct IODescriptor *iohandler_connect(const char *hostname, unsigned int port, int ssl, const char *bind, iohandler_callback *callback);
+struct IODescriptor *iohandler_connect_flags(const char *hostname, unsigned int port, int ssl, const char *bindhost, iohandler_callback *callback, int flags);
+struct IODescriptor *iohandler_listen(const char *hostname, unsigned int port, iohandler_callback *callback);
+struct IODescriptor *iohandler_listen_flags(const char *hostname, unsigned int port, iohandler_callback *callback, int flags);
+struct IODescriptor *iohandler_listen_ssl(const char *hostname, unsigned int port, const char *certfile, const char *keyfile, iohandler_callback *callback);
+struct IODescriptor *iohandler_listen_ssl_flags(const char *hostname, unsigned int port, const char *certfile, const char *keyfile, iohandler_callback *callback, int flags);
+void iohandler_write(struct IODescriptor *iofd, const char *line);
+void iohandler_send(struct IODescriptor *iofd, const char *data, size_t datalen);
+void iohandler_printf(struct IODescriptor *iofd, const char *text, ...);
+void iohandler_close(struct IODescriptor *iofd);
+void iohandler_update(struct IODescriptor *iofd);
+void iohandler_set_timeout(struct IODescriptor *iofd, struct timeval *timeout);
+
+void iohandler_poll();
+void iohandler_poll_timeout(struct timeval timeout);
+
+#endif
--- /dev/null
+/* IOHandler_SSL.c - IOMultiplexer
+ * Copyright (C) 2012 Philipp Kreil (pk910)
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+#include "IOEngine.h"
+#include "IOHandler_SSL.h"
+#ifdef HAVE_SSL
+
+void iohandler_ssl_init() {
+ SSL_library_init();
+ OpenSSL_add_all_algorithms(); /* load & register all cryptos, etc. */
+ SSL_load_error_strings();
+}
+
+static void iohandler_ssl_error() {
+ unsigned long e;
+ while((e = ERR_get_error())) {
+ iohandler_log(IOLOG_ERROR, "SSLv23 ERROR %lu: %s", e, ERR_error_string(e, NULL));
+ }
+}
+
+void iohandler_ssl_connect(struct IODescriptor *iofd) {
+ iofd->state = IO_SSLWAIT;
+ iofd->ssl_server_hs = 0;
+ struct IOSSLNode *sslnode = malloc(sizeof(*sslnode));
+ sslnode->sslContext = SSL_CTX_new(SSLv23_client_method());
+ if(!sslnode->sslContext) {
+ iohandler_ssl_error();
+ iohandler_log(IOLOG_ERROR, "SSL: could not create client SSL CTX");
+ goto ssl_connect_err;
+ }
+ sslnode->sslHandle = SSL_new(sslnode->sslContext);
+ if(!sslnode->sslHandle) {
+ iohandler_ssl_error();
+ iohandler_log(IOLOG_ERROR, "SSL: could not create client SSL Handle");
+ goto ssl_connect_err;
+ }
+ if(!SSL_set_fd(sslnode->sslHandle, iofd->fd)) {
+ iohandler_ssl_error();
+ iohandler_log(IOLOG_ERROR, "SSL: could not set client fd in SSL Handle");
+ goto ssl_connect_err;
+ }
+ SSL_set_connect_state(sslnode->sslHandle);
+ iofd->sslnode = sslnode;
+ iohandler_ssl_client_handshake(iofd);
+ return;
+ssl_connect_err:
+ free(sslnode);
+ iohandler_events(iofd, 0, 0);
+}
+
+void iohandler_ssl_listen(struct IODescriptor *iofd, const char *certfile, const char *keyfile) {
+ struct IOSSLNode *sslnode = malloc(sizeof(*sslnode));
+ sslnode->sslContext = SSL_CTX_new(SSLv23_server_method());
+ if(!sslnode->sslContext) {
+ iohandler_ssl_error();
+ iohandler_log(IOLOG_ERROR, "SSL: could not create server SSL CTX");
+ goto ssl_listen_err;
+ }
+ /* load certificate */
+ if(SSL_CTX_use_certificate_file(sslnode->sslContext, certfile, SSL_FILETYPE_PEM) <= 0) {
+ iohandler_ssl_error();
+ iohandler_log(IOLOG_ERROR, "SSL: could not load server certificate (%s)", certfile);
+ goto ssl_listen_err;
+ }
+ /* load keyfile */
+ if(SSL_CTX_use_PrivateKey_file(sslnode->sslContext, keyfile, SSL_FILETYPE_PEM) <= 0) {
+ iohandler_ssl_error();
+ iohandler_log(IOLOG_ERROR, "SSL: could not load server keyfile (%s)", keyfile);
+ goto ssl_listen_err;
+ }
+ /* check certificate and keyfile */
+ if(!SSL_CTX_check_private_key(sslnode->sslContext)) {
+ iohandler_ssl_error();
+ iohandler_log(IOLOG_ERROR, "SSL: server certificate (%s) and keyfile (%s) doesn't match!", certfile, keyfile);
+ goto ssl_listen_err;
+ }
+ iofd->sslnode = sslnode;
+ return;
+ssl_listen_err:
+ free(sslnode);
+ iofd->sslnode = NULL;
+ iohandler_events(iofd, 0, 0);
+}
+
+void iohandler_ssl_client_handshake(struct IODescriptor *iofd) {
+ // Perform an SSL handshake.
+ int ret = SSL_do_handshake(iofd->sslnode->sslHandle);
+ iofd->ssl_hs_read = 0;
+ iofd->ssl_hs_write = 0;
+ switch(SSL_get_error(iofd->sslnode->sslHandle, ret)) {
+ case SSL_ERROR_NONE:
+ iofd->state = IO_CONNECTING;
+ iofd->ssl_active = 1;
+ iohandler_log(IOLOG_DEBUG, "SSL handshake for %s (fd: %d) successful", iohandler_iotype_name(iofd->type), iofd->fd);
+ iohandler_events(iofd, 0, 1); //perform IOEVENT_CONNECTED event
+ break;
+ case SSL_ERROR_WANT_READ:
+ iofd->ssl_hs_read = 1;
+ iohandler_log(IOLOG_DEBUG, "SSL_do_handshake for %s (fd: %d) returned SSL_ERROR_WANT_READ", iohandler_iotype_name(iofd->type), iofd->fd);
+ break;
+ case SSL_ERROR_WANT_WRITE:
+ iofd->ssl_hs_write = 1;
+ iohandler_log(IOLOG_DEBUG, "SSL_do_handshake for %s (fd: %d) returned SSL_ERROR_WANT_WRITE", iohandler_iotype_name(iofd->type), iofd->fd);
+ break;
+ default:
+ iohandler_log(IOLOG_ERROR, "SSL_do_handshake for %s (fd: %d) failed with ", iohandler_iotype_name(iofd->type), iofd->fd);
+ iohandler_events(iofd, 0, 0);
+ break;
+ }
+}
+
+void iohandler_ssl_client_accepted(struct IODescriptor *iofd, struct IODescriptor *client_iofd) {
+ struct IOSSLNode *sslnode = malloc(sizeof(*sslnode));
+ sslnode->sslHandle = SSL_new(sslnode->sslContext);
+ if(!sslnode->sslHandle) {
+ iohandler_ssl_error();
+ iohandler_log(IOLOG_ERROR, "SSL: could not create client SSL Handle");
+ goto ssl_accept_err;
+ }
+ if(!SSL_set_fd(sslnode->sslHandle, client_iofd->fd)) {
+ iohandler_ssl_error();
+ iohandler_log(IOLOG_ERROR, "SSL: could not set client fd in SSL Handle");
+ goto ssl_accept_err;
+ }
+ client_iofd->state = IO_SSLWAIT;
+ client_iofd->ssl_server_hs = 1;
+ client_iofd->ssl = 1;
+ client_iofd->sslnode = sslnode;
+ client_iofd->callback = iofd->callback;
+ client_iofd->data = iofd;
+ return;
+ssl_accept_err:
+ iohandler_close(client_iofd);
+ free(sslnode);
+}
+
+void iohandler_ssl_server_handshake(struct IODescriptor *iofd) {
+ // Perform an SSL handshake.
+ int ret = SSL_accept(iofd->sslnode->sslHandle);
+ iofd->ssl_hs_read = 0;
+ iofd->ssl_hs_write = 0;
+ switch(SSL_get_error(iofd->sslnode->sslHandle, ret)) {
+ case SSL_ERROR_NONE:
+ iofd->state = IO_CONNECTING;
+ iofd->ssl_active = 1;
+ iohandler_log(IOLOG_DEBUG, "SSL handshake for %s (fd: %d) successful", iohandler_iotype_name(iofd->type), iofd->fd);
+ iohandler_events(iofd, 0, 1); //perform IOEVENT_CONNECTED event
+ break;
+ case SSL_ERROR_WANT_READ:
+ iofd->ssl_hs_read = 1;
+ iohandler_log(IOLOG_DEBUG, "SSL_do_handshake for %s (fd: %d) returned SSL_ERROR_WANT_READ", iohandler_iotype_name(iofd->type), iofd->fd);
+ break;
+ case SSL_ERROR_WANT_WRITE:
+ iofd->ssl_hs_write = 1;
+ iohandler_log(IOLOG_DEBUG, "SSL_do_handshake for %s (fd: %d) returned SSL_ERROR_WANT_WRITE", iohandler_iotype_name(iofd->type), iofd->fd);
+ break;
+ default:
+ iohandler_log(IOLOG_ERROR, "SSL_do_handshake for %s (fd: %d) failed with ", iohandler_iotype_name(iofd->type), iofd->fd);
+ iohandler_events(iofd, 0, 0);
+ break;
+ }
+}
+
+void iohandler_ssl_disconnect(struct IODescriptor *iofd) {
+ if(!iofd->sslnode) return;
+ SSL_shutdown(iofd->sslnode->sslHandle);
+ SSL_free(iofd->sslnode->sslHandle);
+ SSL_CTX_free(iofd->sslnode->sslContext);
+ free(iofd->sslnode);
+ iofd->sslnode = NULL;
+ iofd->ssl_active = 0;
+}
+
+int iohandler_ssl_read(struct IODescriptor *iofd, char *buffer, int len) {
+ if(!iofd->sslnode) return 0;
+ int ret = SSL_read(iofd->sslnode->sslHandle, buffer, len);
+ int update = (iofd->ssl_hs_read || iofd->ssl_hs_write);
+ iofd->ssl_hs_read = 0;
+ iofd->ssl_hs_write = 0;
+ switch(SSL_get_error(iofd->sslnode->sslHandle, ret)) {
+ case SSL_ERROR_NONE:
+ case SSL_ERROR_ZERO_RETURN:
+ if(update)
+ iohandler_update(iofd);
+ return ret;
+ break;
+ case SSL_ERROR_WANT_READ:
+ iofd->ssl_hs_read = 1;
+ iohandler_update(iofd);
+ iohandler_log(IOLOG_DEBUG, "SSL_read for %s (fd: %d) returned SSL_ERROR_WANT_READ", iohandler_iotype_name(iofd->type), iofd->fd);
+ errno = EAGAIN;
+ return -1;
+ break;
+ case SSL_ERROR_WANT_WRITE:
+ iofd->ssl_hs_write = 1;
+ iohandler_update(iofd);
+ iohandler_log(IOLOG_DEBUG, "SSL_read for %s (fd: %d) returned SSL_ERROR_WANT_WRITE", iohandler_iotype_name(iofd->type), iofd->fd);
+ errno = EAGAIN;
+ return -1;
+ break;
+ default:
+ iohandler_log(IOLOG_ERROR, "SSL_read for %s (fd: %d) failed with ", iohandler_iotype_name(iofd->type), iofd->fd);
+ return -1;
+ break;
+ }
+}
+
+int iohandler_ssl_write(struct IODescriptor *iofd, char *buffer, int len) {
+ if(!iofd->sslnode) return 0;
+ int ret = SSL_write(iofd->sslnode->sslHandle, buffer, len);
+ int update = (iofd->ssl_hs_read || iofd->ssl_hs_write);
+ iofd->ssl_hs_read = 0;
+ iofd->ssl_hs_write = 0;
+ switch(SSL_get_error(iofd->sslnode->sslHandle, ret)) {
+ case SSL_ERROR_NONE:
+ case SSL_ERROR_ZERO_RETURN:
+ if(update)
+ iohandler_update(iofd);
+ return ret;
+ break;
+ case SSL_ERROR_WANT_READ:
+ iofd->ssl_hs_read = 1;
+ iohandler_update(iofd);
+ iohandler_log(IOLOG_DEBUG, "SSL_write for %s (fd: %d) returned SSL_ERROR_WANT_READ", iohandler_iotype_name(iofd->type), iofd->fd);
+ errno = EAGAIN;
+ return -1;
+ break;
+ case SSL_ERROR_WANT_WRITE:
+ iofd->ssl_hs_write = 1;
+ iohandler_update(iofd);
+ iohandler_log(IOLOG_DEBUG, "SSL_write for %s (fd: %d) returned SSL_ERROR_WANT_WRITE", iohandler_iotype_name(iofd->type), iofd->fd);
+ errno = EAGAIN;
+ return -1;
+ break;
+ default:
+ iohandler_log(IOLOG_ERROR, "SSL_write for %s (fd: %d) failed with ", iohandler_iotype_name(iofd->type), iofd->fd);
+ return -1;
+ break;
+ }
+}
+
+#else
+// NULL-backend
+
+void iohandler_ssl_init() {};
+void iohandler_ssl_connect(struct IODescriptor *iofd) {};
+void iohandler_ssl_listen(struct IODescriptor *iofd, const char *certfile, const char *keyfile) {};
+void iohandler_ssl_client_handshake(struct IODescriptor *iofd) {};
+void iohandler_ssl_client_accepted(struct IODescriptor *iofd, struct IODescriptor *client_iofd) {};
+void iohandler_ssl_server_handshake(struct IODescriptor *iofd) {};
+void iohandler_ssl_disconnect(struct IODescriptor *iofd) {};
+int iohandler_ssl_read(struct IODescriptor *iofd, char *buffer, int len) { return 0; };
+int iohandler_ssl_write(struct IODescriptor *iofd, char *buffer, int len) { return 0; };
+#endif
--- /dev/null
+/* IOHandler_SSL.h - IOMultiplexer
+ * Copyright (C) 2012 Philipp Kreil (pk910)
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+#ifndef _IOHandler_SSL_h
+#define _IOHandler_SSL_h
+
+struct IODescriptor;
+
+#ifdef HAVE_SSL
+#include <openssl/rand.h>
+#include <openssl/ssl.h>
+#include <openssl/err.h>
+
+struct IOSSLNode {
+ SSL *sslHandle;
+ SSL_CTX *sslContext;
+};
+#else
+struct IOSSLNode {
+ //just unused
+};
+#endif
+
+void iohandler_ssl_init();
+void iohandler_ssl_connect(struct IODescriptor *iofd);
+void iohandler_ssl_listen(struct IODescriptor *iofd, const char *certfile, const char *keyfile);
+void iohandler_ssl_client_handshake(struct IODescriptor *iofd);
+void iohandler_ssl_client_accepted(struct IODescriptor *iofd, struct IODescriptor *client_iofd);
+void iohandler_ssl_server_handshake(struct IODescriptor *iofd);
+void iohandler_ssl_disconnect(struct IODescriptor *iofd);
+int iohandler_ssl_read(struct IODescriptor *iofd, char *buffer, int len);
+int iohandler_ssl_write(struct IODescriptor *iofd, char *buffer, int len);
+
+#endif
--- /dev/null
+
+CC = gcc
+CFLAGS = -g -O0 -Wall -Wshadow -Werror -DHAVE_PTHREAD_H
+LDFLAGS = -lws2_32 -lpthread
+
+OBJ = ../../IOEngine_epoll.o ../../IOEngine_kevent.o ../../IOEngine_select.o ../../IOEngine_win32.o ../../IOHandler.o ../../IOHandler_SSL.o iotest.o
+
+all: $(OBJ)
+ $(CC) $(CFLAGS) -oiotest $(OBJ) $(LDFLAGS)
+
+%.o: %.c
+ $(CC) $(CFLAGS) -o$@ -c $<
--- /dev/null
+/* main.c - IOMultiplexer
+ * Copyright (C) 2012 Philipp Kreil (pk910)
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <stdio.h>
+#include "../IOHandler.h"
+
+static IOHANDLER_CALLBACK(io_callback);
+static IOHANDLER_LOG_BACKEND(io_log);
+
+static struct IODescriptor *irc_iofd = NULL;
+
+int main(int argc, char *argv[]) {
+ iolog_backend = io_log;
+
+ irc_iofd = iohandler_connect("pk910.de", 6667, 0, NULL, io_callback);
+
+ struct IODescriptor *iofd;
+ iofd = iohandler_add(0, IOTYPE_STDIN, NULL, io_callback);
+ iofd->read_lines = 1;
+
+ while(1) {
+ iohandler_poll();
+ }
+}
+
+static IOHANDLER_CALLBACK(io_callback) {
+ switch(event->type) {
+ case IOEVENT_CONNECTED:
+ printf("[connect]\n");
+ break;
+ case IOEVENT_CLOSED:
+ printf("[disconnect]\n");
+ break;
+ case IOEVENT_RECV:
+ if(event->iofd->type == IOTYPE_STDIN) {
+ iohandler_printf(irc_iofd, "%s\n", event->data.recv_str);
+ printf("[out] %s\n", event->data.recv_str);
+ } else
+ printf("[in] %s\n", event->data.recv_str);
+ break;
+
+ default:
+ break;
+ }
+}
+
+static IOHANDLER_LOG_BACKEND(io_log) {
+ //printf("%s", line);
+}
--- /dev/null
+
+CC = gcc
+CFLAGS = -g -O0 -Wall -Wshadow -Werror -DHAVE_PTHREAD_H
+LDFLAGS = -lws2_32 -lpthread
+
+OBJ = ../../IOEngine_epoll.o ../../IOEngine_kevent.o ../../IOEngine_select.o ../../IOEngine_win32.o ../../IOHandler.o ../../IOHandler_SSL.o iotest.o
+
+all: $(OBJ)
+ $(CC) $(CFLAGS) -oiotest $(OBJ) $(LDFLAGS)
+
+%.o: %.c
+ $(CC) $(CFLAGS) -o$@ -c $<
--- /dev/null
+/* main.c - IOMultiplexer
+ * Copyright (C) 2012 Philipp Kreil (pk910)
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <stdio.h>
+#include "../../IOHandler.h"
+
+#define TEST_DURATION 100
+
+static IOHANDLER_CALLBACK(io_callback);
+static IOHANDLER_LOG_BACKEND(io_log);
+
+static struct timeval test_clock1, test_clock2;
+static int timercount;
+
+void add_timer(int ms) {
+ struct timeval timeout;
+ gettimeofday(&timeout, NULL);
+ timeout.tv_usec += (ms % 1000) * 1000;
+ timeout.tv_sec += (ms / 1000);
+ if(timeout.tv_usec > 1000000) {
+ timeout.tv_usec -= 1000000;
+ timeout.tv_sec++;
+ }
+ iohandler_timer(timeout, io_callback);
+}
+
+int main(int argc, char *argv[]) {
+ iolog_backend = io_log;
+
+ iohandler_set(IOHANDLER_SETTING_HIGH_PRECISION_TIMER, 1);
+
+ gettimeofday(&test_clock1, NULL);
+ gettimeofday(&test_clock2, NULL);
+ //add_timer(TEST_DURATION);
+ iohandler_constant_timer(TEST_DURATION, io_callback);
+ timercount = 0;
+
+ printf("[timer 0] %ld.%ld\n", test_clock1.tv_sec, test_clock1.tv_usec);
+
+ while(1) {
+ iohandler_poll();
+ }
+}
+
+static IOHANDLER_CALLBACK(io_callback) {
+ struct timeval curr_time;
+ int diff1;
+ double diff2;
+ switch(event->type) {
+ case IOEVENT_TIMEOUT:
+ //add_timer(TEST_DURATION);
+ timercount++;
+ gettimeofday(&curr_time, NULL);
+ diff1 = (curr_time.tv_sec - test_clock1.tv_sec) * 1000 + ((curr_time.tv_usec - test_clock1.tv_usec) / 1000);
+ diff2 = (curr_time.tv_sec - test_clock2.tv_sec) * 1000 + ((curr_time.tv_usec - test_clock2.tv_usec) / 1000.0);
+ diff2 -= (timercount * TEST_DURATION);
+ gettimeofday(&test_clock1, NULL);
+ printf("[timer %03d] %ld.%06ld [%d ms] accuracy: %f ms\n", timercount, curr_time.tv_sec, curr_time.tv_usec, diff1, diff2);
+ break;
+ default:
+ break;
+ }
+}
+
+static IOHANDLER_LOG_BACKEND(io_log) {
+ //printf("%s", line);
+}
+++ /dev/null
-/* IOEngine.h - IOMultiplexer
- * Copyright (C) 2012 Philipp Kreil (pk910)
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-#ifndef _IOEngine_h
-#define _IOEngine_h
-#include "IOHandler.h"
-
-#ifdef HAVE_PTHREAD_H
-#include <pthread.h>
-#ifdef PTHREAD_MUTEX_RECURSIVE_NP
-#define PTHREAD_MUTEX_RECURSIVE_VAL PTHREAD_MUTEX_RECURSIVE_NP
-#else
-#define PTHREAD_MUTEX_RECURSIVE_VAL PTHREAD_MUTEX_RECURSIVE
-#endif
-#define IOTHREAD_MUTEX_INIT(var) { \
- pthread_mutexattr_t mutex_attr; \
- pthread_mutexattr_init(&mutex_attr);\
- pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_RECURSIVE_VAL);\
- pthread_mutex_init(&var, &mutex_attr); \
-}
-#define IOSYNCHRONIZE(var) pthread_mutex_lock(&var)
-#define IODESYNCHRONIZE(var) pthread_mutex_unlock(&var)
-#else
-#define IOTHREAD_MUTEX_INIT(var)
-#define IOSYNCHRONIZE(var)
-#define IODESYNCHRONIZE(var)
-#endif
-
-struct IODescriptor;
-enum IOType;
-enum IOStatus;
-enum IOEventType;
-
-#define timeval_is_bigger(x,y) ((x->tv_sec > y->tv_sec) || (x->tv_sec == y->tv_sec && x->tv_usec > y->tv_usec))
-#define timeval_is_smaler(x,y) ((x->tv_sec < y->tv_sec) || (x->tv_sec == y->tv_sec && x->tv_usec < y->tv_usec))
-
-extern struct IODescriptor *first_descriptor;
-extern struct IODescriptor *timer_priority;
-
-struct IOEngine {
- const char *name;
- int (*init)(void);
- void (*add)(struct IODescriptor *iofd);
- void (*remove)(struct IODescriptor *iofd);
- void (*update)(struct IODescriptor *iofd);
- void (*loop)(struct timeval *timeout);
- void (*cleanup)(void);
-};
-
-#define iohandler_wants_writes(IOFD) ((IOFD->writebuf.bufpos && !IOFD->ssl_hs_read) || IOFD->state == IO_CONNECTING || IOFD->ssl_hs_write)
-
-void iohandler_log(enum IOLogType type, char *text, ...);
-void iohandler_events(struct IODescriptor *iofd, int readable, int writeable);
-char *iohandler_iotype_name(enum IOType type);
-char *iohandler_iostatus_name(enum IOStatus status);
-char *iohandler_ioeventtype_name(enum IOEventType type);
-
-#endif
+++ /dev/null
-/* IOEngine_epoll.c - IOMultiplexer
- * Copyright (C) 2012 Philipp Kreil (pk910)
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-#include "IOEngine.h"
-
-#ifdef HAVE_SYS_EPOLL_H
-#include <sys/epoll.h>
-#include <errno.h>
-#include <string.h>
-#include <unistd.h>
-
-#define MAX_EVENTS 32
-
-static int epoll_fd;
-
-static int engine_epoll_init() {
- epoll_fd = epoll_create(1024);
- if (epoll_fd < 0)
- return 0;
- return 1;
-}
-
-static void engine_epoll_add(struct IODescriptor *iofd) {
- if(iofd->type == IOTYPE_TIMER) return;
- //add descriptor to the epoll queue
- struct epoll_event evt;
- int res;
-
- evt.events = EPOLLHUP | EPOLLIN | (iohandler_wants_writes(iofd) ? EPOLLOUT : 0);
- evt.data.ptr = iofd;
- res = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, iofd->fd, &evt);
- if(res < 0) {
- iohandler_log(IOLOG_ERROR, "could not add IODescriptor %d to epoll queue. (returned: %d)", iofd->fd, res);
- }
-}
-
-static void engine_epoll_remove(struct IODescriptor *iofd) {
- if(iofd->type == IOTYPE_TIMER) return;
- struct epoll_event evt;
- epoll_ctl(epoll_fd, EPOLL_CTL_DEL, iofd->fd, &evt);
-}
-
-static void engine_epoll_update(struct IODescriptor *iofd) {
- if(iofd->type == IOTYPE_TIMER) return;
- if(iofd->state == IO_CLOSED) {
- engine_epoll_remove(iofd);
- return;
- }
- struct epoll_event evt;
- int res;
-
- evt.events = EPOLLHUP | EPOLLIN | (iohandler_wants_writes(iofd) ? EPOLLOUT : 0);
- evt.data.ptr = iofd;
- res = epoll_ctl(epoll_fd, EPOLL_CTL_MOD, iofd->fd, &evt);
- if(res < 0) {
- iohandler_log(IOLOG_ERROR, "could not update IODescriptor %d in epoll queue. (returned: %d)", iofd->fd, res);
- }
-}
-
-static void engine_epoll_loop(struct timeval *timeout) {
- struct epoll_event evts[MAX_EVENTS];
- struct timeval now, tdiff;
- int msec;
- int events;
- int epoll_result;
-
- gettimeofday(&now, NULL);
-
- while(timer_priority) {
- tdiff.tv_sec = timer_priority->timeout.tv_sec - now.tv_sec;
- tdiff.tv_usec = timer_priority->timeout.tv_usec - now.tv_usec;
- if(tdiff.tv_sec < 0 || (tdiff.tv_sec == 0 && tdiff.tv_usec <= 0)) {
- if(timer_priority->constant_timeout) {
- tdiff.tv_sec = 0;
- iohandler_set_timeout(timer_priority, &tdiff);
- iohandler_events(timer_priority, 0, 0);
- } else {
- iohandler_events(timer_priority, 0, 0);
- iohandler_close(timer_priority); //also sets timer_priority to the next timed element
- }
- continue;
- } else if(tdiff.tv_usec < 0) {
- tdiff.tv_sec--;
- tdiff.tv_usec += 1000000; //1 sec
- }
- if(timeval_is_smaler((&tdiff), timeout)) {
- timeout->tv_sec = tdiff.tv_sec;
- timeout->tv_usec = tdiff.tv_usec;
- }
- break;
- }
-
- msec = timeout ? ((timeout->tv_sec * 1000 + timeout->tv_usec / 1000) + (timeout->tv_usec % 1000 != 0 ? 1 : 0)) : -1;
-
- //select system call
- epoll_result = epoll_wait(epoll_fd, evts, MAX_EVENTS, msec);
-
- if (epoll_result < 0) {
- if (errno != EINTR) {
- iohandler_log(IOLOG_FATAL, "epoll_wait() failed with errno %d: %s", errno, strerror(errno));
- return;
- }
- } else {
- int i;
- for(i = 0; i < epoll_result; i++) {
- events = evts[i].events;
- iohandler_events(evts[i].data.ptr, (events & (EPOLLIN | EPOLLHUP)), (events & EPOLLOUT));
- }
- }
-
- //check timers
- while(timer_priority) {
- tdiff.tv_sec = timer_priority->timeout.tv_sec - now.tv_sec;
- tdiff.tv_usec = timer_priority->timeout.tv_usec - now.tv_usec;
- if(tdiff.tv_sec < 0 || (tdiff.tv_sec == 0 && tdiff.tv_usec <= 0)) {
- if(timer_priority->constant_timeout) {
- tdiff.tv_sec = 0;
- iohandler_set_timeout(timer_priority, &tdiff);
- iohandler_events(timer_priority, 0, 0);
- } else {
- iohandler_events(timer_priority, 0, 0);
- iohandler_close(timer_priority); //also sets timer_priority to the next timed element
- }
- continue;
- }
- break;
- }
-
-}
-
-static void engine_epoll_cleanup() {
- close(epoll_fd);
-}
-
-struct IOEngine engine_epoll = {
- .name = "epoll",
- .init = engine_epoll_init,
- .add = engine_epoll_add,
- .remove = engine_epoll_remove,
- .update = engine_epoll_update,
- .loop = engine_epoll_loop,
- .cleanup = engine_epoll_cleanup,
-};
-
-#else
-
-struct IOEngine engine_epoll = {
- .name = "epoll",
- .init = NULL,
- .add = NULL,
- .remove = NULL,
- .update = NULL,
- .loop = NULL,
- .cleanup = NULL,
-};
-
-#endif
+++ /dev/null
-/* IOengine_kevent.c - IOMultiplexer
- * Copyright (C) 2012 Philipp Kreil (pk910)
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-#include "IOEngine.h"
-
-#ifdef HAVE_SYS_EVENT_H
-#include <sys/event.h>
-#include <errno.h>
-
-#define MAX_EVENTS 32
-
-static int kevent_fd;
-
-static int engine_kevent_init() {
- kevent_fd = kqueue();
- if (kevent_fd < 0)
- return 0;
- return 1;
-}
-
-static void engine_kevent_add(struct IODescriptor *iofd) {
- if(iofd->type == IOTYPE_TIMER) return;
- //add descriptor to the kevent queue
- struct kevent changes[2];
- int nchanges = 0;
- int res;
-
- EV_SET(&changes[nchanges++], iofd->fd, EVFILT_READ, EV_ADD, 0, 0, iofd);
- if (iohandler_wants_writes(iofd))
- EV_SET(&changes[nchanges++], iofd->fd, EVFILT_WRITE, EV_ADD, 0, 0, iofd);
-
- res = kevent(kevent_fd, changes, nchanges, NULL, 0, NULL);
- if(res < 0)
- iohandler_log(IOLOG_ERROR, "could not add IODescriptor %d to kevent queue. (returned: %d)", res);
-}
-
-static void engine_kevent_remove(struct IODescriptor *iofd) {
- if(iofd->type == IOTYPE_TIMER) return;
- struct kevent changes[2];
- int nchanges = 0;
-
- EV_SET(&changes[nchanges++], iofd->fd, EVFILT_READ, EV_DELETE, 0, 0, iofd);
- EV_SET(&changes[nchanges++], iofd->fd, EVFILT_WRITE, EV_DELETE, 0, 0, iofd);
- kevent(kevent_fd, changes, nchanges, NULL, 0, NULL);
-}
-
-static void engine_kevent_update(struct IODescriptor *iofd) {
- if(iofd->type == IOTYPE_TIMER) return;
- if(iofd->state == IO_CLOSED) {
- engine_kevent_remove(iofd);
- return;
- }
- struct kevent changes[2];
- int nchanges = 0;
- int res;
-
- EV_SET(&changes[nchanges++], iofd->fd, EVFILT_READ, EV_ADD, 0, 0, iofd);
- EV_SET(&changes[nchanges++], iofd->fd, EVFILT_WRITE, iohandler_wants_writes(iofd) ? EV_ADD : EV_DELETE, 0, 0, iofd);
-
- res = kevent(kevent_fd, changes, nchanges, NULL, 0, NULL);
- if(res < 0) {
- iohandler_log(IOLOG_ERROR, "could not update IODescriptor %d in kevent queue. (returned: %d)", res);
- }
-}
-
-static void engine_kevent_loop(struct timeval *timeout) {
- struct kevent events[MAX_EVENTS];
- struct timeval now, tdiff;
- struct timespec ts, *pts;
- int msec;
- int kevent_result;
-
- gettimeofday(&now, NULL);
-
- while(timer_priority) {
- tdiff.tv_sec = timer_priority->timeout.tv_sec - now.tv_sec;
- tdiff.tv_usec = timer_priority->timeout.tv_usec - now.tv_usec;
- if(tdiff.tv_sec < 0 || (tdiff.tv_sec == 0 && tdiff.tv_usec <= 0)) {
- if(timer_priority->constant_timeout) {
- tdiff.tv_sec = 0;
- iohandler_set_timeout(timer_priority, &tdiff);
- iohandler_events(timer_priority, 0, 0);
- } else {
- iohandler_events(timer_priority, 0, 0);
- iohandler_close(timer_priority); //also sets timer_priority to the next timed element
- }
- continue;
- } else if(tdiff.tv_usec < 0) {
- tdiff.tv_sec--;
- tdiff.tv_usec += 1000000; //1 sec
- }
- if(timeval_is_smaler((&tdiff), timeout)) {
- timeout->tv_sec = tdiff.tv_sec;
- timeout->tv_usec = tdiff.tv_usec;
- }
- break;
- }
-
- if (timeout) {
- ts.tv_sec = timeout->tv_sec;
- ts.tv_nsec = timeout->tv_usec * 1000;
- pts = &ts;
- } else {
- pts = NULL;
- }
-
- //select system call
- kevent_result = kevent(kevent_fd, NULL, 0, events, MAX_EVENTS, pts);
-
- if (kevent_result < 0) {
- if (errno != EINTR) {
- iohandler_log(IOLOG_FATAL, "kevent() failed with errno %d: %s", errno, strerror(errno));
- return;
- }
- } else {
- int i;
- for(i = 0; i < kevent_result; i++)
- iohandler_events(events[i].udata, (events[i].filter == EVFILT_READ), (events[i].filter == EVFILT_WRITE));
- }
-
- //check timers
- while(timer_priority) {
- tdiff.tv_sec = timer_priority->timeout.tv_sec - now.tv_sec;
- tdiff.tv_usec = timer_priority->timeout.tv_usec - now.tv_usec;
- if(tdiff.tv_sec < 0 || (tdiff.tv_sec == 0 && tdiff.tv_usec <= 0)) {
- if(timer_priority->constant_timeout) {
- tdiff.tv_sec = 0;
- iohandler_set_timeout(timer_priority, &tdiff);
- iohandler_events(timer_priority, 0, 0);
- } else {
- iohandler_events(timer_priority, 0, 0);
- iohandler_close(timer_priority); //also sets timer_priority to the next timed element
- }
- continue;
- }
- break;
- }
-
-}
-
-static void engine_kevent_cleanup() {
- close(kevent_fd);
-}
-
-struct IOEngine engine_kevent = {
- .name = "kevent",
- .init = engine_kevent_init,
- .add = engine_kevent_add,
- .remove = engine_kevent_remove,
- .update = engine_kevent_update,
- .loop = engine_kevent_loop,
- .cleanup = engine_kevent_cleanup,
-};
-
-#else
-
-struct IOEngine engine_kevent = {
- .name = "kevent",
- .init = NULL,
- .add = NULL,
- .remove = NULL,
- .update = NULL,
- .loop = NULL,
- .cleanup = NULL,
-};
-
-#endif
+++ /dev/null
-/* IOEngine_select.c - IOMultiplexer
- * Copyright (C) 2012 Philipp Kreil (pk910)
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-#include "IOEngine.h"
-#include <errno.h>
-#include <time.h>
-#ifdef WIN32
-#define _WIN32_WINNT 0x501
-#include <windows.h>
-#include <winsock2.h>
-#else
-#include <string.h>
-#include <stdio.h>
-#endif
-
-static int engine_select_timer_delay_fix;
-
-static int engine_select_init() {
- engine_select_timer_delay_fix = 0;
- return 1;
-}
-
-static void engine_select_add(struct IODescriptor *iofd) {
- #ifdef WIN32
- if(iofd->type == IOTYPE_STDIN)
- SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE),ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT);
- #endif
- /* empty */
-}
-
-static void engine_select_remove(struct IODescriptor *iofd) {
- /* empty */
-}
-
-static void engine_select_update(struct IODescriptor *iofd) {
- /* empty */
-}
-
-static void engine_select_loop(struct timeval *timeout) {
- fd_set read_fds;
- fd_set write_fds;
- unsigned int fds_size = 0;
- struct IODescriptor *iofd, *tmp_iofd;
- struct timeval now, tdiff;
- int select_result;
- int timer_fix;
-
- gettimeofday(&now, NULL);
-
- //clear fds
- FD_ZERO(&read_fds);
- FD_ZERO(&write_fds);
-
- select_result = 0;
- for(iofd = first_descriptor; iofd; iofd = tmp_iofd) {
- tmp_iofd = iofd->next;
- if(iofd->type == IOTYPE_STDIN) {
- #ifdef WIN32
- //WIN32 doesn't support stdin within select
- //just try to read the single events from the console
- DWORD dwRead;
- INPUT_RECORD inRecords[128];
- unsigned int i;
- int read_bytes = 0;
- GetNumberOfConsoleInputEvents(GetStdHandle(STD_INPUT_HANDLE), &dwRead);
- if(dwRead)
- ReadConsoleInput(GetStdHandle(STD_INPUT_HANDLE), &inRecords[0], 128, &dwRead);
- for (i = 0; i < dwRead; ++i) {
- if (inRecords[i].EventType == KEY_EVENT) {
- const char c = inRecords[i].Event.KeyEvent.uChar.AsciiChar;
- if (inRecords[i].Event.KeyEvent.bKeyDown && c != 0) {
- iofd->readbuf.buffer[iofd->readbuf.bufpos + read_bytes] = c;
- read_bytes++;
- }
- }
- }
- if(read_bytes)
- iohandler_events(iofd, read_bytes, 0);
- if(read_bytes >= 128) {
- timeout->tv_sec = 0;
- timeout->tv_usec = 1;
- //minimal timeout
- } else {
- timeout->tv_sec = 0;
- timeout->tv_usec = 100000;
- }
- #else
- if(iofd->fd > fds_size)
- fds_size = iofd->fd;
- FD_SET(iofd->fd, &read_fds);
- select_result++;
- #endif
- }
- else if(iofd->type == IOTYPE_SERVER || iofd->type == IOTYPE_CLIENT) {
- if(iofd->state == IO_CLOSED)
- continue;
- if(iofd->fd > fds_size)
- fds_size = iofd->fd;
- FD_SET(iofd->fd, &read_fds);
- select_result++;
- if(iohandler_wants_writes(iofd))
- FD_SET(iofd->fd, &write_fds);
- }
- }
-
- while(timer_priority) {
- tdiff.tv_sec = timer_priority->timeout.tv_sec - now.tv_sec;
- tdiff.tv_usec = timer_priority->timeout.tv_usec - now.tv_usec;
- if(tdiff.tv_sec < 0 || (tdiff.tv_sec == 0 && tdiff.tv_usec <= 0)) {
- if(timer_priority->constant_timeout) {
- tdiff.tv_sec = 0;
- iohandler_set_timeout(timer_priority, &tdiff);
- iohandler_events(timer_priority, 0, 0);
- } else {
- iohandler_events(timer_priority, 0, 0);
- iohandler_close(timer_priority); //also sets timer_priority to the next timed element
- }
- continue;
- } else if(tdiff.tv_usec < 0) {
- tdiff.tv_sec--;
- tdiff.tv_usec += 1000000; //1 sec
- }
- if(timeval_is_smaler((&tdiff), timeout)) {
- timeout->tv_sec = tdiff.tv_sec;
- timeout->tv_usec = tdiff.tv_usec + engine_select_timer_delay_fix;
- if(timeout->tv_usec < 0) {
- timeout->tv_sec--;
- timeout->tv_usec += 1000000;
- }
- }
- break;
- }
-
- if(select_result) {
- //select system call
- select_result = select(fds_size + 1, &read_fds, &write_fds, NULL, timeout);
- } else {
- #ifdef WIN32
- Sleep((timeout->tv_sec * 1000) + (timeout->tv_usec / 1000) + 1);
- #else
- struct timespec usleep_time;
- usleep_time.tv_sec = timeout->tv_sec;
- usleep_time.tv_nsec = timeout->tv_usec * 1000;
- nanosleep(&usleep_time, NULL);
- #endif
- }
-
- if (select_result < 0) {
- if (errno != EINTR) {
- iohandler_log(IOLOG_FATAL, "select() failed with errno %d %d: %s", select_result, errno, strerror(errno));
- return;
- }
- }
-
- gettimeofday(&now, NULL);
-
- //check all descriptors
- for(iofd = first_descriptor; iofd; iofd = tmp_iofd) {
- tmp_iofd = iofd->next;
- if(iofd->type == IOTYPE_SERVER || iofd->type == IOTYPE_CLIENT || iofd->type == IOTYPE_STDIN) {
- if(FD_ISSET(iofd->fd, &read_fds) || FD_ISSET(iofd->fd, &write_fds)) {
- iohandler_events(iofd, FD_ISSET(iofd->fd, &read_fds), FD_ISSET(iofd->fd, &write_fds));
- continue;
- }
- }
- }
-
- //check timers
- while(timer_priority) {
- tdiff.tv_sec = timer_priority->timeout.tv_sec - now.tv_sec;
- tdiff.tv_usec = timer_priority->timeout.tv_usec - now.tv_usec;
- timer_fix = (tdiff.tv_sec * 1000000) + tdiff.tv_usec;
- if(timer_fix <= 100) {
- if(timer_fix + 100 < engine_select_timer_delay_fix || timer_fix - 100 > engine_select_timer_delay_fix) {
- engine_select_timer_delay_fix = ((engine_select_timer_delay_fix * 19) + timer_fix) / 20;
- iohandler_log(IOLOG_DEBUG, "timer delay fix set to: %d us", engine_select_timer_delay_fix);
- }
- if(timer_priority->constant_timeout) {
- tdiff.tv_sec = 0;
- iohandler_set_timeout(timer_priority, &tdiff);
- iohandler_events(timer_priority, 0, 0);
- } else {
- iohandler_events(timer_priority, 0, 0);
- iohandler_close(timer_priority); //also sets timer_priority to the next timed element
- }
- continue;
- }
- break;
- }
-
-}
-
-static void engine_select_cleanup() {
- /* empty */
-}
-
-struct IOEngine engine_select = {
- .name = "select",
- .init = engine_select_init,
- .add = engine_select_add,
- .remove = engine_select_remove,
- .update = engine_select_update,
- .loop = engine_select_loop,
- .cleanup = engine_select_cleanup,
-};
+++ /dev/null
-/* IOEngine_win32.c - IOMultiplexer
- * Copyright (C) 2012 Philipp Kreil (pk910)
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-#include "IOEngine.h"
-
-#ifdef WIN32
-
-#define _WIN32_WINNT 0x501
-#include <windows.h>
-#include <winsock2.h>
-
-/* This is massively kludgy. Unfortunately, the only performant I/O
- * multiplexer with halfway decent semantics under Windows is
- * WSAAsyncSelect() -- which requires a window that can receive
- * messages.
- *
- * So ioset_win32_init() creates a hidden window and sets it up for
- * asynchronous socket notifications.
- */
-
-#define IDT_TIMER1 1000
-#define IDT_TIMER2 1001
-#define IDT_SOCKET 1002
-
-static HWND ioset_window;
-
-static struct IODescriptor *engine_win32_get_iofd(int fd) {
- struct IODescriptor *iofd;
- for(iofd = first_descriptor; iofd; iofd = iofd->next) {
- if(iofd->fd == fd)
- return iofd;
- }
- return NULL;
-}
-
-static LRESULT CALLBACK engine_win32_wndproc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
- struct IODescriptor *iofd;
- int events;
- struct timeval now, tdiff;
-
- gettimeofday(&now, NULL);
-
- if (hWnd == ioset_window) switch (uMsg)
- {
- case IDT_TIMER1:
- return 0;
- case IDT_TIMER2:
- //User Timer
- while(timer_priority) {
- tdiff.tv_sec = timer_priority->timeout.tv_sec - now.tv_sec;
- tdiff.tv_usec = timer_priority->timeout.tv_usec - now.tv_usec;
- if(tdiff.tv_sec < 0 || (tdiff.tv_sec == 0 && tdiff.tv_usec <= 0)) {
- if(timer_priority->constant_timeout) {
- tdiff.tv_sec = 0;
- iohandler_set_timeout(timer_priority, &tdiff);
- iohandler_events(timer_priority, 0, 0);
- } else {
- iohandler_events(timer_priority, 0, 0);
- iohandler_close(timer_priority); //also sets timer_priority to the next timed element
- }
- continue;
- }
- break;
- }
- return 0;
- case IDT_SOCKET:
- iofd = engine_win32_get_iofd(wParam);
- events = WSAGETSELECTEVENT(lParam);
-
- iohandler_events(iofd, (events & (FD_READ | FD_ACCEPT | FD_CLOSE)) != 0, (events & (FD_WRITE | FD_CONNECT)) != 0);
- return 0;
- case WM_QUIT:
- return 0;
- }
- return DefWindowProc(hWnd, uMsg, wParam, lParam);
-}
-
-static int engine_win32_init() {
- WNDCLASSEX wcx;
- HINSTANCE hinst;
- WSADATA wsadata;
-
- // Start Windows Sockets.
- if (WSAStartup(MAKEWORD(2, 0), &wsadata)) {
- iohandler_log(IOLOG_FATAL, "Unable to start Windows Sockets");
- return 0;
- }
-
- // Get Windows HINSTANCE.
- hinst = GetModuleHandle(NULL);
-
- // Describe and register a window class.
- memset(&wcx, 0, sizeof(wcx));
- wcx.cbSize = sizeof(wcx);
- wcx.lpfnWndProc = engine_win32_wndproc;
- wcx.hInstance = hinst;
- wcx.lpszClassName = "IOMultiplexerMainWindow";
- if (!RegisterClassEx(&wcx))
- return 0;
-
- ioset_window = CreateWindow("IOMultiplexerMainWindow", "IOMultiplexer", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hinst, NULL);
- if (!ioset_window)
- return 0;
- return 1;
-}
-
-static long engine_win32_events(struct IODescriptor *iofd) {
- switch (iofd->state) {
- case IO_CLOSED:
- return 0;
- case IO_LISTENING:
- return FD_ACCEPT;
- case IO_CONNECTING:
- return FD_CONNECT;
- case IO_CONNECTED:
- case IO_SSLWAIT:
- return FD_READ | FD_CLOSE | (iohandler_wants_writes(iofd) ? FD_WRITE : 0);
- }
- return 0;
-}
-
-static void engine_win32_update(struct IODescriptor *iofd) {
- long events;
-
- if(iofd->type == IOTYPE_STDIN)
- return;
-
- events = engine_win32_events(iofd);
- WSAAsyncSelect(iofd->fd, ioset_window, IDT_SOCKET, events);
-}
-
-static void engine_win32_add(struct IODescriptor *iofd) {
- if(iofd->type == IOTYPE_STDIN)
- return;
-
- engine_win32_update(iofd);
-}
-
-static void engine_win32_remove(struct IODescriptor *iofd) {
- unsigned long ulong;
-
- if(iofd->type == IOTYPE_STDIN)
- return;
-
- WSAAsyncSelect(iofd->fd, ioset_window, IDT_SOCKET, 0);
-
- ulong = 0;
- ioctlsocket(iofd->fd, FIONBIO, &ulong);
-}
-
-static void engine_win32_loop(struct timeval *timeout) {
- MSG msg;
- BOOL not_really_bool;
- int msec, cmsec, sett2;
- struct timeval now, tdiff;
- struct IODescriptor *iofd, *tmp_iofd;
-
- gettimeofday(&now, NULL);
-
- for(iofd = first_descriptor; iofd; iofd = tmp_iofd) {
- tmp_iofd = iofd->next;
- if(iofd->type == IOTYPE_STDIN) {
- #ifdef WIN32
- //WIN32 doesn't support stdin within select
- //just try to read the single events from the console
- DWORD dwRead;
- INPUT_RECORD inRecords[128];
- unsigned int i;
- int read_bytes = 0;
- GetNumberOfConsoleInputEvents(GetStdHandle(STD_INPUT_HANDLE), &dwRead);
- if(dwRead)
- ReadConsoleInput(GetStdHandle(STD_INPUT_HANDLE), &inRecords[0], 128, &dwRead);
- for (i = 0; i < dwRead; ++i) {
- if (inRecords[i].EventType == KEY_EVENT) {
- const char c = inRecords[i].Event.KeyEvent.uChar.AsciiChar;
- if (inRecords[i].Event.KeyEvent.bKeyDown && c != 0) {
- iofd->readbuf.buffer[iofd->readbuf.bufpos + read_bytes] = c;
- read_bytes++;
- }
- }
- }
- if(read_bytes)
- iohandler_events(iofd, read_bytes, 0);
- if(read_bytes >= 128) {
- timeout->tv_sec = 0;
- timeout->tv_usec = 1;
- //minimal timeout
- } else {
- timeout->tv_sec = 0;
- timeout->tv_usec = 100000;
- }
- #else
- if(iofd->fd > fds_size)
- fds_size = iofd->fd;
- FD_SET(iofd->fd, &read_fds);
- #endif
- }
- }
-
- // Make sure we are woken up after the appropriate time.
- msec = (timeout->tv_sec * 1000) + (timeout->tv_usec / 1000);
- SetTimer(ioset_window, IDT_TIMER1, msec, NULL);
-
- //set additional User Timer (if ther's one)
- sett2 = 0;
- while(timer_priority) {
- tdiff.tv_sec = timer_priority->timeout.tv_sec - now.tv_sec;
- tdiff.tv_usec = timer_priority->timeout.tv_usec - now.tv_usec;
- if(tdiff.tv_sec < 0 || (tdiff.tv_sec == 0 && tdiff.tv_usec < 100)) {
- if(timer_priority->constant_timeout) {
- tdiff.tv_sec = 0;
- iohandler_set_timeout(timer_priority, &tdiff);
- iohandler_events(timer_priority, 0, 0);
- } else {
- iohandler_events(timer_priority, 0, 0);
- iohandler_close(timer_priority); //also sets timer_priority to the next timed element
- }
- continue;
- } else if(tdiff.tv_usec < 0) {
- tdiff.tv_sec--;
- tdiff.tv_usec += 1000000; //1 sec
- }
- cmsec = (tdiff.tv_sec * 1000) + (tdiff.tv_usec / 1000);
- if(cmsec < msec) {
- sett2 = 1;
- msec = cmsec;
- }
- break;
- }
- if(sett2)
- SetTimer(ioset_window, IDT_TIMER2, msec, NULL);
-
- // Do a blocking read of the message queue.
- not_really_bool = GetMessage(&msg, NULL, 0, 0);
- KillTimer(ioset_window, IDT_TIMER1);
- if(sett2)
- KillTimer(ioset_window, IDT_TIMER2);
- if (not_really_bool <=0)
- return;
- else {
- TranslateMessage(&msg);
- DispatchMessage(&msg);
- }
-}
-
-static void engine_win32_cleanup() {
- DestroyWindow(ioset_window);
- ioset_window = NULL;
- WSACleanup();
-}
-
-struct IOEngine engine_win32 = {
- .name = "win32",
- .init = engine_win32_init,
- .add = engine_win32_add,
- .remove = engine_win32_remove,
- .update = engine_win32_update,
- .loop = engine_win32_loop,
- .cleanup = engine_win32_cleanup,
-};
-
-#else
-
-struct IOEngine engine_win32 = {
- .name = "win32",
- .init = NULL,
- .add = NULL,
- .remove = NULL,
- .update = NULL,
- .loop = NULL,
- .cleanup = NULL,
-};
-
-#endif
+++ /dev/null
-/* IOHandler.c - IOMultiplexer
- * Copyright (C) 2012 Philipp Kreil (pk910)
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-#include "IOHandler.h"
-#include "IOEngine.h"
-#include "IOHandler_SSL.h"
-#include <errno.h>
-#include <stdio.h>
-#include <unistd.h>
-#ifdef WIN32
-#define _WIN32_WINNT 0x501
-#include <windows.h>
-#include <winsock2.h>
-#include <ws2tcpip.h>
-#else
-#include <signal.h>
-#include <stdarg.h>
-#include <stdlib.h>
-#include <string.h>
-#include <netdb.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <netinet/tcp.h>
-#include <fcntl.h>
-#endif
-
-#ifndef EWOULDBLOCK
-#define EWOULDBLOCK EAGAIN
-#endif
-
-#define MAXLOG 1024
-iohandler_log_callback *iolog_backend = NULL;
-
-struct IODescriptor *first_descriptor = NULL;
-struct IODescriptor *timer_priority = NULL;
-
-#ifdef HAVE_PTHREAD_H
-static pthread_mutex_t io_thread_sync;
-static pthread_mutex_t io_poll_sync;
-#endif
-
-void iohandler_log(enum IOLogType type, char *text, ...) {
- va_list arg_list;
- char logBuf[MAXLOG+1];
- int pos;
- logBuf[0] = '\0';
- va_start(arg_list, text);
- pos = vsnprintf(logBuf, MAXLOG - 1, text, arg_list);
- va_end(arg_list);
- if (pos < 0 || pos > (MAXLOG - 1)) pos = MAXLOG - 1;
- logBuf[pos] = '\n';
- logBuf[pos+1] = '\0';
-
- if(iolog_backend)
- iolog_backend(type, logBuf);
-}
-
-/* IO Engines */
-extern struct IOEngine engine_select; /* select system call (should always be useable) */
-extern struct IOEngine engine_kevent;
-extern struct IOEngine engine_epoll;
-extern struct IOEngine engine_win32;
-
-int iohandler_settings = 0;
-struct IOEngine *engine = NULL;
-
-void iohandler_set(int setting, int value) {
- if(value)
- iohandler_settings |= setting;
- else
- iohandler_settings &= ~setting;
-}
-
-static void iohandler_init_engine() {
- if(engine) return;
- IOTHREAD_MUTEX_INIT(io_thread_sync);
- IOTHREAD_MUTEX_INIT(io_poll_sync);
-
- //try other engines
- if(!(iohandler_settings & IOHANDLER_SETTING_HIGH_PRECISION_TIMER)) {
- if(!engine && engine_kevent.init && engine_kevent.init())
- engine = &engine_kevent;
- if(!engine && engine_epoll.init && engine_epoll.init())
- engine = &engine_epoll;
- if(!engine && engine_win32.init && engine_win32.init())
- engine = &engine_win32;
- }
-
- if (!engine) {
- if(engine_select.init())
- engine = &engine_select;
- else {
- iohandler_log(IOLOG_FATAL, "found no useable IO engine");
- return;
- }
- }
- iohandler_log(IOLOG_DEBUG, "using %s IO engine", engine->name);
- iohandler_ssl_init();
-}
-
-static void iohandler_append(struct IODescriptor *descriptor) {
- IOSYNCHRONIZE(io_thread_sync);
- struct timeval *timeout = ((descriptor->timeout.tv_sec || descriptor->timeout.tv_usec) ? &descriptor->timeout : NULL);
- if(timeout) {
- struct IODescriptor *iofd;
- int set_priority = 1;
- descriptor->timeout = *timeout;
- if(timer_priority)
- iofd = timer_priority;
- else
- iofd = first_descriptor;
- if(iofd) {
- for(;;iofd = iofd->next) {
- if(timeval_is_smaler(timeout, (&iofd->timeout))) {
- descriptor->prev = iofd->prev;
- descriptor->next = iofd;
- if(iofd->prev)
- iofd->prev->next = descriptor;
- iofd->prev = descriptor;
- if(set_priority)
- timer_priority = descriptor;
- break;
- }
- if(iofd == timer_priority)
- set_priority = 0;
- if(iofd->next == NULL) {
- descriptor->next = NULL;
- descriptor->prev = iofd;
- iofd->next = descriptor;
- if(set_priority)
- timer_priority = descriptor;
- break;
- }
- }
- } else {
- descriptor->prev = NULL;
- descriptor->next = NULL;
- first_descriptor = descriptor;
- timer_priority = descriptor;
- }
-
- } else {
- descriptor->prev = NULL;
- descriptor->next = first_descriptor;
- if(first_descriptor)
- first_descriptor->prev = descriptor;
- first_descriptor = descriptor;
- }
- IODESYNCHRONIZE(io_thread_sync);
-}
-
-static void iohandler_remove(struct IODescriptor *descriptor, int engine_remove) {
- //remove IODescriptor from the list
- IOSYNCHRONIZE(io_thread_sync);
- if(descriptor->prev)
- descriptor->prev->next = descriptor->next;
- else
- first_descriptor = descriptor->next;
- if(descriptor->next)
- descriptor->next->prev = descriptor->prev;
- if(descriptor == timer_priority)
- timer_priority = descriptor->next;
-
- if(engine_remove)
- engine->remove(descriptor);
- if(descriptor->readbuf.buffer)
- free(descriptor->readbuf.buffer);
- if(descriptor->writebuf.buffer)
- free(descriptor->writebuf.buffer);
- iohandler_log(IOLOG_DEBUG, "removed IODescriptor (%d) of type `%s`", descriptor->fd, iohandler_iotype_name(descriptor->type));
- free(descriptor);
- IODESYNCHRONIZE(io_thread_sync);
-}
-
-struct IODescriptor *iohandler_add(int sockfd, enum IOType type, struct timeval *timeout, iohandler_callback *callback) {
- //just add a new IODescriptor
- struct IODescriptor *descriptor = calloc(1, sizeof(*descriptor));
- if(!descriptor) {
- iohandler_log(IOLOG_ERROR, "could not allocate memory for IODescriptor in %s:%d", __FILE__, __LINE__);
- return NULL;
- }
- descriptor->fd = (type == IOTYPE_STDIN ? fileno(stdin) : sockfd);
- descriptor->type = type;
- descriptor->state = (type == IOTYPE_STDIN ? IO_CONNECTED : IO_CLOSED);
- descriptor->callback = callback;
- if(timeout) {
- descriptor->timeout = *timeout;
- if(descriptor->timeout.tv_usec > 1000000) {
- descriptor->timeout.tv_usec -= 1000000;
- descriptor->timeout.tv_sec++;
- }
- }
- if(type != IOTYPE_TIMER) {
- descriptor->readbuf.buffer = malloc(IO_READ_BUFLEN + 2);
- descriptor->readbuf.bufpos = 0;
- descriptor->readbuf.buflen = IO_READ_BUFLEN;
- descriptor->writebuf.buffer = malloc(IO_READ_BUFLEN + 2);
- descriptor->writebuf.bufpos = 0;
- descriptor->writebuf.buflen = IO_READ_BUFLEN;
- }
-
- if(!engine) {
- iohandler_init_engine();
- if(!engine) {
- return NULL;
- }
- }
- engine->add(descriptor);
-
- //add IODescriptor to the list
- iohandler_append(descriptor);
-
- iohandler_log(IOLOG_DEBUG, "added custom socket descriptor (%d) as type `%s`", sockfd, iohandler_iotype_name(type));
- return descriptor;
-}
-
-void iohandler_set_timeout(struct IODescriptor *descriptor, struct timeval *timeout) {
- if(descriptor->prev)
- descriptor->prev->next = descriptor->next;
- else
- first_descriptor = descriptor->next;
- if(descriptor->next)
- descriptor->next->prev = descriptor->prev;
- if(descriptor == timer_priority)
- timer_priority = descriptor->next;
- if(timeout && timeout->tv_sec == 0 && descriptor->constant_timeout) {
- descriptor->timeout.tv_usec += (descriptor->constant_timeout % 1000) * 1000;
- descriptor->timeout.tv_sec += (descriptor->constant_timeout / 1000);
- if(descriptor->timeout.tv_usec > 1000000) {
- descriptor->timeout.tv_sec += (descriptor->timeout.tv_usec / 1000000);
- descriptor->timeout.tv_usec %= 1000000;
- }
- } else if(timeout) {
- descriptor->timeout = *timeout;
- if(descriptor->timeout.tv_usec > 1000000) {
- descriptor->timeout.tv_usec -= 1000000;
- descriptor->timeout.tv_sec++;
- }
- } else {
- descriptor->timeout.tv_sec = 0;
- descriptor->timeout.tv_usec = 0;
- }
- iohandler_append(descriptor);
-}
-
-static void iohandler_increase_iobuf(struct IOBuffer *iobuf, size_t required) {
- if(iobuf->buflen >= required) return;
- char *new_buf = realloc(iobuf->buffer, required + 2);
- if(new_buf) {
- iobuf->buffer = new_buf;
- iobuf->buflen = required;
- }
-}
-
-struct IODescriptor *iohandler_timer(struct timeval timeout, iohandler_callback *callback) {
- struct IODescriptor *descriptor;
- descriptor = iohandler_add(-1, IOTYPE_TIMER, &timeout, callback);
- if(!descriptor) {
- iohandler_log(IOLOG_ERROR, "could not allocate memory for IODescriptor in %s:%d", __FILE__, __LINE__);
- return NULL;
- }
- iohandler_log(IOLOG_DEBUG, "added timer descriptor (sec: %d; usec: %d)", timeout.tv_sec, timeout.tv_usec);
- return descriptor;
-}
-
-struct IODescriptor *iohandler_constant_timer(int msec, iohandler_callback *callback) {
- struct IODescriptor *descriptor;
- struct timeval timeout;
- gettimeofday(&timeout, NULL);
- timeout.tv_usec += (msec % 1000) * 1000;
- timeout.tv_sec += (msec / 1000);
- if(timeout.tv_usec > 1000000) {
- timeout.tv_sec += (timeout.tv_usec / 1000000);
- timeout.tv_usec %= 1000000;
- }
- descriptor = iohandler_add(-1, IOTYPE_TIMER, &timeout, callback);
- if(!descriptor) {
- iohandler_log(IOLOG_ERROR, "could not allocate memory for IODescriptor in %s:%d", __FILE__, __LINE__);
- return NULL;
- }
- descriptor->constant_timeout = msec;
- iohandler_log(IOLOG_DEBUG, "added timer descriptor (sec: %d; usec: %d)", timeout.tv_sec, timeout.tv_usec);
- return descriptor;
-}
-
-struct IODescriptor *iohandler_connect(const char *hostname, unsigned int port, int ssl, const char *bindhost, iohandler_callback *callback) {
- return iohandler_connect_flags(hostname, port, ssl, bindhost, callback, IOHANDLER_CONNECT_IPV4 | IOHANDLER_CONNECT_IPV6);
-}
-
-struct IODescriptor *iohandler_connect_flags(const char *hostname, unsigned int port, int ssl, const char *bindhost, iohandler_callback *callback, int flags) {
- //non-blocking connect
- int sockfd, result;
- struct addrinfo hints, *res;
- struct sockaddr_in *ip4 = NULL;
- struct sockaddr_in6 *ip6 = NULL;
- size_t dstaddrlen;
- struct sockaddr *dstaddr = NULL;
- struct IODescriptor *descriptor;
-
- if(!engine) {
- iohandler_init_engine();
- if(!engine) return NULL;
- }
- memset (&hints, 0, sizeof (hints));
- hints.ai_family = PF_UNSPEC;
- hints.ai_socktype = SOCK_STREAM;
- hints.ai_flags |= AI_CANONNAME;
- if ((result = getaddrinfo (hostname, NULL, &hints, &res))) {
- iohandler_log(IOLOG_ERROR, "could not resolve %s to an IP address (%d)", hostname, result);
- return NULL;
- }
- while (res) {
- switch (res->ai_family) {
- case AF_INET:
- ip4 = (struct sockaddr_in *) res->ai_addr;
- break;
- case AF_INET6:
- ip6 = (struct sockaddr_in6 *) res->ai_addr;
- break;
- }
- res = res->ai_next;
- freeaddrinfo(res);
- }
-
- if(ip6 && (flags & IOHANDLER_CONNECT_IPV6)) {
- sockfd = socket(AF_INET6, SOCK_STREAM, 0);
- if(sockfd == -1) {
- iohandler_log(IOLOG_ERROR, "could not create socket in %s:%d", __FILE__, __LINE__);
- return NULL;
- }
-
- ip6->sin6_family = AF_INET6;
- ip6->sin6_port = htons(port);
-
- struct sockaddr_in6 *ip6vhost = NULL;
- if (bindhost && !getaddrinfo(bindhost, NULL, &hints, &res)) {
- while (res) {
- switch (res->ai_family) {
- case AF_INET6:
- ip6vhost = (struct sockaddr_in6 *) res->ai_addr;
- break;
- }
- res = res->ai_next;
- freeaddrinfo(res);
- }
- }
- if(ip6vhost) {
- ip6vhost->sin6_family = AF_INET6;
- ip6vhost->sin6_port = htons(0);
- bind(sockfd, (struct sockaddr*)ip6vhost, sizeof(*ip6vhost));
- }
- dstaddr = (struct sockaddr*)ip6;
- dstaddrlen = sizeof(*ip6);
- } else if(ip4 && (flags & IOHANDLER_CONNECT_IPV4)) {
- sockfd = socket(AF_INET, SOCK_STREAM, 0);
- if(sockfd == -1) {
- iohandler_log(IOLOG_ERROR, "could not create socket in %s:%d", __FILE__, __LINE__);
- return NULL;
- }
-
- ip4->sin_family = AF_INET;
- ip4->sin_port = htons(port);
-
- struct sockaddr_in *ip4vhost = NULL;
- if (bindhost && !getaddrinfo(bindhost, NULL, &hints, &res)) {
- while (res) {
- switch (res->ai_family) {
- case AF_INET:
- ip4vhost = (struct sockaddr_in *) res->ai_addr;
- break;
- }
- res = res->ai_next;
- freeaddrinfo(res);
- }
- }
- if(ip4vhost) {
- ip4vhost->sin_family = AF_INET;
- ip4vhost->sin_port = htons(0);
- bind(sockfd, (struct sockaddr*)ip4vhost, sizeof(*ip4vhost));
- }
- dstaddr = (struct sockaddr*)ip4;
- dstaddrlen = sizeof(*ip4);
- } else
- return NULL;
- //prevent SIGPIPE
- #ifndef WIN32
- #if defined(SO_NOSIGPIPE)
- {
- int set = 1;
- setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&set, sizeof(int));
- }
- #else
- signal(SIGPIPE, SIG_IGN);
- #endif
- #endif
- //make sockfd unblocking
- #if defined(F_GETFL)
- {
- int fcntl_flags;
- fcntl_flags = fcntl(sockfd, F_GETFL);
- fcntl(sockfd, F_SETFL, fcntl_flags|O_NONBLOCK);
- fcntl_flags = fcntl(sockfd, F_GETFD);
- fcntl(sockfd, F_SETFD, fcntl_flags|FD_CLOEXEC);
- }
- #else
- /* I hope you're using the Win32 backend or something else that
- * automatically marks the file descriptor non-blocking...
- */
- #endif
- descriptor = iohandler_add(sockfd, IOTYPE_CLIENT, NULL, callback);
- if(!descriptor) {
- close(sockfd);
- return NULL;
- }
- connect(sockfd, dstaddr, dstaddrlen); //returns EINPROGRESS here (nonblocking)
- descriptor->state = IO_CONNECTING;
- descriptor->ssl = (ssl ? 1 : 0);
- descriptor->read_lines = 1;
- engine->update(descriptor);
- iohandler_log(IOLOG_DEBUG, "added client socket (%d) connecting to %s:%d", sockfd, hostname, port);
- return descriptor;
-}
-
-struct IODescriptor *iohandler_listen(const char *hostname, unsigned int port, iohandler_callback *callback) {
- return iohandler_listen_flags(hostname, port, callback, IOHANDLER_LISTEN_IPV4 | IOHANDLER_LISTEN_IPV6);
-}
-
-struct IODescriptor *iohandler_listen_flags(const char *hostname, unsigned int port, iohandler_callback *callback, int flags) {
- int sockfd;
- struct addrinfo hints, *res;
- struct sockaddr_in *ip4 = NULL;
- struct sockaddr_in6 *ip6 = NULL;
- struct IODescriptor *descriptor;
- unsigned int opt;
-
- if(!engine) {
- iohandler_init_engine();
- if(!engine) return NULL;
- }
- memset (&hints, 0, sizeof (hints));
- hints.ai_family = PF_UNSPEC;
- hints.ai_socktype = SOCK_STREAM;
- hints.ai_flags |= AI_CANONNAME;
- if (getaddrinfo (hostname, NULL, &hints, &res)) {
- return NULL;
- }
- while (res) {
- switch (res->ai_family) {
- case AF_INET:
- ip4 = (struct sockaddr_in *) res->ai_addr;
- break;
- case AF_INET6:
- ip6 = (struct sockaddr_in6 *) res->ai_addr;
- break;
- }
- res = res->ai_next;
- freeaddrinfo(res);
- }
-
- if(ip6 && (flags & IOHANDLER_LISTEN_IPV6)) {
- sockfd = socket(AF_INET6, SOCK_STREAM, 0);
- if(sockfd == -1) return NULL;
-
- opt = 1;
- setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt));
-
- ip6->sin6_family = AF_INET6;
- ip6->sin6_port = htons(port);
-
- bind(sockfd, (struct sockaddr*)ip6, sizeof(*ip6));
- } else if(ip4 && (flags & IOHANDLER_LISTEN_IPV4)) {
- sockfd = socket(AF_INET, SOCK_STREAM, 0);
- if(sockfd == -1) return NULL;
-
- opt = 1;
- setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt));
-
- ip4->sin_family = AF_INET;
- ip4->sin_port = htons(port);
-
- bind(sockfd, (struct sockaddr*)ip4, sizeof(*ip4));
- } else
- return NULL;
- //prevent SIGPIPE
- #ifndef WIN32
- #if defined(SO_NOSIGPIPE)
- {
- int set = 1;
- setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&set, sizeof(int));
- }
- #else
- signal(SIGPIPE, SIG_IGN);
- #endif
- #endif
- //make sockfd unblocking
- #if defined(F_GETFL)
- {
- int flag;
- flag = fcntl(sockfd, F_GETFL);
- fcntl(sockfd, F_SETFL, flag|O_NONBLOCK);
- flag = fcntl(sockfd, F_GETFD);
- fcntl(sockfd, F_SETFD, flag|FD_CLOEXEC);
- }
- #else
- /* I hope you're using the Win32 backend or something else that
- * automatically marks the file descriptor non-blocking...
- */
- #endif
- descriptor = iohandler_add(sockfd, IOTYPE_SERVER, NULL, callback);
- if(!descriptor) {
- close(sockfd);
- return NULL;
- }
- listen(sockfd, 1);
- descriptor->state = IO_LISTENING;
- engine->update(descriptor);
- iohandler_log(IOLOG_DEBUG, "added server socket (%d) listening on %s:%d", sockfd, hostname, port);
- return descriptor;
-}
-
-struct IODescriptor *iohandler_listen_ssl(const char *hostname, unsigned int port, const char *certfile, const char *keyfile, iohandler_callback *callback) {
- return iohandler_listen_ssl_flags(hostname, port, certfile, keyfile, callback, IOHANDLER_LISTEN_IPV4 | IOHANDLER_LISTEN_IPV6);
-}
-
-struct IODescriptor *iohandler_listen_ssl_flags(const char *hostname, unsigned int port, const char *certfile, const char *keyfile, iohandler_callback *callback, int flags) {
- struct IODescriptor *descriptor = iohandler_listen_flags(hostname, port, callback, flags);
- if(!descriptor)
- return NULL;
- //SSL Server Socket
- iohandler_ssl_listen(descriptor, certfile, keyfile);
- if(descriptor->sslnode)
- descriptor->ssl = 1;
- return descriptor;
-}
-
-void iohandler_write(struct IODescriptor *iofd, const char *line) {
- size_t linelen = strlen(line);
- iohandler_send(iofd, line, linelen);
-}
-
-void iohandler_send(struct IODescriptor *iofd, const char *data, size_t datalen) {
- if(iofd->type == IOTYPE_TIMER || iofd->state == IO_CLOSED) {
- iohandler_log(IOLOG_ERROR, "could not write to socket (%s)", (iofd->type == IOTYPE_TIMER ? "IOTYPE_TIMER" : "IO_CLOSED"));
- return;
- }
- iohandler_log(IOLOG_DEBUG, "add %d to writebuf (fd: %d): %s", datalen, iofd->fd, data);
- if(iofd->writebuf.buflen < iofd->writebuf.bufpos + datalen) {
- iohandler_log(IOLOG_DEBUG, "increase writebuf (curr: %d) to %d (+%d bytes)", iofd->writebuf.buflen, iofd->writebuf.bufpos + datalen, (iofd->writebuf.bufpos + datalen - iofd->writebuf.buflen));
- iohandler_increase_iobuf(&iofd->writebuf, iofd->writebuf.bufpos + datalen);
- if(iofd->writebuf.buflen < iofd->writebuf.bufpos + datalen) {
- iohandler_log(IOLOG_ERROR, "increase writebuf (curr: %d) to %d (+%d bytes) FAILED", iofd->writebuf.buflen, iofd->writebuf.bufpos + datalen, (iofd->writebuf.bufpos + datalen - iofd->writebuf.buflen));
- return;
- }
- }
- memcpy(iofd->writebuf.buffer + iofd->writebuf.bufpos, data, datalen);
- iofd->writebuf.bufpos += datalen;
- engine->update(iofd);
-}
-
-void iohandler_printf(struct IODescriptor *iofd, const char *text, ...) {
- va_list arg_list;
- char sendBuf[IO_LINE_LEN];
- int pos;
- sendBuf[0] = '\0';
- va_start(arg_list, text);
- pos = vsnprintf(sendBuf, IO_LINE_LEN - 2, text, arg_list);
- va_end(arg_list);
- if (pos < 0 || pos > (IO_LINE_LEN - 2)) pos = IO_LINE_LEN - 2;
- sendBuf[pos] = '\n';
- sendBuf[pos+1] = '\0';
- iohandler_send(iofd, sendBuf, pos+1);
-}
-
-static int iohandler_try_write(struct IODescriptor *iofd) {
- if(!iofd->writebuf.bufpos) return 0;
- iohandler_log(IOLOG_DEBUG, "write writebuf (%d bytes) to socket (fd: %d)", iofd->writebuf.bufpos, iofd->fd);
- int res;
- if(iofd->ssl_active)
- res = iohandler_ssl_write(iofd, iofd->writebuf.buffer, iofd->writebuf.bufpos);
- else
- res = send(iofd->fd, iofd->writebuf.buffer, iofd->writebuf.bufpos, 0);
- if(res < 0) {
- if (errno != EAGAIN && errno != EWOULDBLOCK)
- iohandler_log(IOLOG_ERROR, "could not write to socket (fd: %d): %d - %s", iofd->fd, errno, strerror(errno));
- else
- res = 0;
- } else {
- iofd->writebuf.bufpos -= res;
- if(iofd->state != IO_CLOSED)
- engine->update(iofd);
- }
- return res;
-}
-
-void iohandler_close(struct IODescriptor *iofd) {
- int engine_remove = 1;
- iofd->state = IO_CLOSED;
- if(iofd->writebuf.bufpos) {
- //try to send everything before closing
-#if defined(F_GETFL)
- {
- int flags;
- flags = fcntl(iofd->fd, F_GETFL);
- fcntl(iofd->fd, F_SETFL, flags & ~O_NONBLOCK);
- flags = fcntl(iofd->fd, F_GETFD);
- fcntl(iofd->fd, F_SETFD, flags|FD_CLOEXEC);
- }
-#else
- engine_remove = 0;
- engine->remove(iofd);
-#endif
- iohandler_try_write(iofd);
- }
- //close IODescriptor
- if(iofd->ssl)
- iohandler_ssl_disconnect(iofd);
- if(iofd->type == IOTYPE_SERVER || iofd->type == IOTYPE_CLIENT || iofd->type == IOTYPE_STDIN)
- close(iofd->fd);
- iohandler_remove(iofd, engine_remove);
-}
-
-void iohandler_update(struct IODescriptor *iofd) {
- iohandler_log(IOLOG_DEBUG, "external call to iohandler_update (fd: %d)", iofd->fd);
- engine->update(iofd);
-}
-
-static void iohandler_trigger_event(struct IOEvent *event) {
- if(!event->iofd->callback) return;
- iohandler_log(IOLOG_DEBUG, "triggering event (%s) for %s (fd: %d)", iohandler_ioeventtype_name(event->type), iohandler_iotype_name(event->iofd->type), event->iofd->fd);
- event->iofd->callback(event);
-}
-
-void iohandler_events(struct IODescriptor *iofd, int readable, int writeable) {
- struct IOEvent callback_event;
- callback_event.type = IOEVENT_IGNORE;
- callback_event.iofd = iofd;
- switch(iofd->state) {
- case IO_SSLWAIT:
- if(!readable && !writeable) {
- if(!iofd->ssl_server_hs) {
- callback_event.type = IOEVENT_SSLFAILED;
- iofd->state = IO_CLOSED;
- engine->update(iofd);
- } else
- iohandler_close(iofd);
- } else if(iofd->ssl_server_hs) {
- iohandler_log(IOLOG_DEBUG, "triggering iohandler_ssl_server_handshake for %s (fd: %d)", iohandler_iotype_name(iofd->type), iofd->fd);
- iohandler_ssl_server_handshake(iofd);
- } else {
- iohandler_log(IOLOG_DEBUG, "triggering iohandler_ssl_client_handshake for %s (fd: %d)", iohandler_iotype_name(iofd->type), iofd->fd);
- iohandler_ssl_client_handshake(iofd);
- }
- break;
- case IO_CLOSED:
- if(iofd->type == IOTYPE_TIMER)
- callback_event.type = IOEVENT_TIMEOUT;
- break;
- case IO_LISTENING:
- if(readable) {
- callback_event.data.accept_fd = accept(iofd->fd, NULL, 0);
- if(callback_event.data.accept_fd < 0) {
- iohandler_log(IOLOG_ERROR, "could not accept client (server fd: %d): %d - %s", iofd->fd, errno, strerror(errno));
- } else if(iofd->ssl) {
- struct IODescriptor *client_iofd = iohandler_add(callback_event.data.accept_fd, IOTYPE_CLIENT, NULL, NULL);
- iohandler_ssl_client_accepted(iofd, client_iofd);
- } else
- callback_event.type = IOEVENT_ACCEPT;
- }
- break;
- case IO_CONNECTING:
- if(readable) { //could not connect
- callback_event.type = IOEVENT_NOTCONNECTED;
- //socklen_t arglen;
- //arglen = sizeof(callback_event.data.errid);
- //if (getsockopt(iofd->fd, SOL_SOCKET, SO_ERROR, &callback_event.data.errid, &arglen) < 0)
- // callback_event.data.errid = errno;
- iofd->state = IO_CLOSED;
- engine->update(iofd);
- } else if(writeable) {
- if(iofd->ssl && !iofd->ssl_active) {
- iohandler_log(IOLOG_DEBUG, "triggering iohandler_ssl_connect for %s (fd: %d)", iohandler_iotype_name(iofd->type), iofd->fd);
- iohandler_ssl_connect(iofd);
- return;
- }
- if(iofd->ssl && iofd->ssl_server_hs) {
- callback_event.type = IOEVENT_SSLACCEPT;
- callback_event.iofd = iofd->data;
- callback_event.data.accept_iofd = iofd;
- iofd->data = NULL;
- }
- else
- callback_event.type = IOEVENT_CONNECTED;
- iofd->state = IO_CONNECTED;
- engine->update(iofd);
- }
- break;
- case IO_CONNECTED:
- if(readable) {
- if(iofd->read_lines) {
- int bytes;
-
- if(iofd->ssl_active)
- bytes = iohandler_ssl_read(iofd, iofd->readbuf.buffer + iofd->readbuf.bufpos, iofd->readbuf.buflen - iofd->readbuf.bufpos);
- else {
- if(iofd->type == IOTYPE_STDIN)
- #ifdef WIN32
- bytes = readable;
- #else
- bytes = read(iofd->fd, iofd->readbuf.buffer + iofd->readbuf.bufpos, iofd->readbuf.buflen - iofd->readbuf.bufpos);
- #endif
- else
- bytes = recv(iofd->fd, iofd->readbuf.buffer + iofd->readbuf.bufpos, iofd->readbuf.buflen - iofd->readbuf.bufpos, 0);
- }
- if(bytes <= 0) {
- if (errno != EAGAIN || errno != EWOULDBLOCK) {
- iofd->state = IO_CLOSED;
- engine->update(iofd);
- callback_event.type = IOEVENT_CLOSED;
- callback_event.data.errid = errno;
- }
- } else {
- int i, used_bytes = 0;
- iohandler_log(IOLOG_DEBUG, "received %d bytes (fd: %d). readbuf position: %d", bytes, iofd->fd, iofd->readbuf.bufpos);
- iofd->readbuf.bufpos += bytes;
- callback_event.type = IOEVENT_RECV;
- for(i = 0; i < iofd->readbuf.bufpos; i++) {
- if(iofd->readbuf.buffer[i] == '\r' && iofd->readbuf.buffer[i+1] == '\n')
- iofd->readbuf.buffer[i] = 0;
- else if(iofd->readbuf.buffer[i] == '\n' || iofd->readbuf.buffer[i] == '\r') {
- iofd->readbuf.buffer[i] = 0;
- callback_event.data.recv_str = iofd->readbuf.buffer + used_bytes;
- iohandler_log(IOLOG_DEBUG, "parsed line (%d bytes): %s", i - used_bytes, iofd->readbuf.buffer + used_bytes);
- used_bytes = i+1;
- iohandler_trigger_event(&callback_event);
- } else if(i + 1 - used_bytes >= IO_LINE_LEN) { //512 max
- iofd->readbuf.buffer[i] = 0;
- callback_event.data.recv_str = iofd->readbuf.buffer + used_bytes;
- iohandler_log(IOLOG_DEBUG, "parsed and stripped line (%d bytes): %s", i - used_bytes, iofd->readbuf.buffer + used_bytes);
- for(; i < iofd->readbuf.bufpos; i++) { //skip the rest of the line
- if(iofd->readbuf.buffer[i] == '\n' || (iofd->readbuf.buffer[i] == '\r' && iofd->readbuf.buffer[i+1] != '\n')) {
- break;
- }
- }
- used_bytes = i+1;
- iohandler_trigger_event(&callback_event);
- }
- }
- if(used_bytes) {
- if(used_bytes == iofd->readbuf.bufpos) {
- iofd->readbuf.bufpos = 0;
- iohandler_log(IOLOG_DEBUG, "readbuf fully processed (set buffer position to 0)");
- } else {
- iohandler_log(IOLOG_DEBUG, "readbuf rest: %d bytes (used %d bytes)", iofd->readbuf.bufpos - used_bytes, used_bytes);
- memmove(iofd->readbuf.buffer, iofd->readbuf.buffer + used_bytes, iofd->readbuf.bufpos - used_bytes);
- iofd->readbuf.bufpos -= used_bytes;
- }
- }
- callback_event.type = IOEVENT_IGNORE;
- }
- } else
- callback_event.type = IOEVENT_READABLE;
- }
- if(writeable) {
- int bytes;
- bytes = iohandler_try_write(iofd);
- if(bytes < 0) {
- iofd->state = IO_CLOSED;
- engine->update(iofd);
- callback_event.type = IOEVENT_CLOSED;
- callback_event.data.errid = errno;
- }
- }
- break;
- }
- if(callback_event.type == IOEVENT_IGNORE && !readable && !writeable)
- callback_event.type = IOEVENT_TIMEOUT;
- if(callback_event.type != IOEVENT_IGNORE)
- iohandler_trigger_event(&callback_event);
-}
-
-void iohandler_poll() {
- struct timeval timeout;
- timeout.tv_sec = IO_MAX_TIMEOUT;
- timeout.tv_usec = 0;
- iohandler_poll_timeout(timeout);
-}
-
-void iohandler_poll_timeout(struct timeval timeout) {
- if(engine) {
- IOSYNCHRONIZE(io_poll_sync); //quite senceless multithread support... better support will follow
- engine->loop(&timeout);
- IODESYNCHRONIZE(io_poll_sync);
- }
-}
-
-//debugging functions
-char *iohandler_iotype_name(enum IOType type) {
- switch(type) {
- case IOTYPE_UNKNOWN:
- return "IOTYPE_UNKNOWN";
- case IOTYPE_SERVER:
- return "IOTYPE_SERVER";
- case IOTYPE_CLIENT:
- return "IOTYPE_CLIENT";
- case IOTYPE_STDIN:
- return "IOTYPE_STDIN";
- case IOTYPE_TIMER:
- return "IOTYPE_TIMER";
- default:
- return "(UNDEFINED)";
- }
-}
-
-char *iohandler_iostatus_name(enum IOStatus status) {
- switch(status) {
- case IO_CLOSED:
- return "IO_CLOSED";
- case IO_LISTENING:
- return "IO_LISTENING";
- case IO_CONNECTING:
- return "IO_CONNECTING";
- case IO_CONNECTED:
- return "IO_CONNECTED";
- case IO_SSLWAIT:
- return "IO_SSLWAIT";
- default:
- return "(UNDEFINED)";
- }
-}
-
-char *iohandler_ioeventtype_name(enum IOEventType type) {
- switch(type) {
- case IOEVENT_IGNORE:
- return "IOEVENT_IGNORE";
- case IOEVENT_READABLE:
- return "IOEVENT_READABLE";
- case IOEVENT_RECV:
- return "IOEVENT_RECV";
- case IOEVENT_CONNECTED:
- return "IOEVENT_CONNECTED";
- case IOEVENT_NOTCONNECTED:
- return "IOEVENT_NOTCONNECTED";
- case IOEVENT_CLOSED:
- return "IOEVENT_CLOSED";
- case IOEVENT_ACCEPT:
- return "IOEVENT_ACCEPT";
- case IOEVENT_SSLACCEPT:
- return "IOEVENT_SSLACCEPT";
- case IOEVENT_TIMEOUT:
- return "IOEVENT_TIMEOUT";
- default:
- return "(UNDEFINED)";
- }
-}
+++ /dev/null
-/* IOHandler.h - IOMultiplexer
- * Copyright (C) 2012 Philipp Kreil (pk910)
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-#ifndef _IOHandler_h
-#define _IOHandler_h
-#include <stddef.h>
-#include <sys/time.h> /* struct timeval */
-
-#define IO_READ_BUFLEN 1024
-#define IO_MAX_TIMEOUT 10
-#define IO_LINE_LEN 1024
-
-struct timeval;
-struct IODescriptor;
-struct IOEvent;
-struct IOSSLNode;
-
-enum IOLogType {
- IOLOG_DEBUG,
- IOLOG_WARNING,
- IOLOG_ERROR,
- IOLOG_FATAL
-};
-
-#define IOHANDLER_CALLBACK(NAME) void NAME(struct IOEvent *event)
-typedef IOHANDLER_CALLBACK(iohandler_callback);
-
-#define IOHANDLER_LOG_BACKEND(NAME) void NAME(enum IOLogType type, const char *line)
-typedef IOHANDLER_LOG_BACKEND(iohandler_log_callback);
-
-extern iohandler_log_callback *iolog_backend;
-
-enum IOType {
- IOTYPE_UNKNOWN, /* ignore descriptor (uninitialized) */
- IOTYPE_SERVER, /* server socket */
- IOTYPE_CLIENT, /* client socket */
- IOTYPE_STDIN, /* stdin */
- IOTYPE_TIMER /* timer */
-};
-
-enum IOStatus {
- IO_CLOSED, /* descriptor is dead (socket waiting for removal or timer) */
- IO_LISTENING, /* descriptor is waiting for connections (server socket) */
- IO_CONNECTING, /* descriptor is waiting for connection approval (connecting client socket) */
- IO_CONNECTED, /* descriptor is connected (connected client socket) */
- IO_SSLWAIT /* waiting for SSL backend (e.g. handshake) */
-};
-
-enum IOEventType {
- IOEVENT_IGNORE,
- IOEVENT_READABLE, /* socket is readable - not read anything yet, could also be disconnect notification */
- IOEVENT_RECV, /* client socket received something (recv_str valid) */
- IOEVENT_CONNECTED, /* client socket connected successful */
- IOEVENT_NOTCONNECTED, /* client socket could not connect (errid valid) */
- IOEVENT_CLOSED, /* client socket lost connection (errid valid) */
- IOEVENT_ACCEPT, /* server socket accepted new connection (accept_fd valid) */
- IOEVENT_SSLACCEPT, /* SSL server socket accepted new connection (accept_iofd valid) */
- IOEVENT_TIMEOUT, /* timer timed out */
- IOEVENT_SSLFAILED /* failed to initialize SSL session */
-};
-
-struct IOBuffer {
- char *buffer;
- size_t bufpos, buflen;
-};
-
-struct IODescriptor {
- int fd;
- enum IOType type;
- enum IOStatus state;
- struct timeval timeout;
- int constant_timeout;
- iohandler_callback *callback;
- struct IOBuffer readbuf;
- struct IOBuffer writebuf;
- void *data;
- int read_lines : 1;
- int ssl : 1;
- int ssl_server_hs : 1;
- int ssl_active : 1;
- int ssl_hs_read : 1;
- int ssl_hs_write : 1;
- struct IOSSLNode *sslnode;
-
- struct IODescriptor *next, *prev;
-};
-
-struct IOEvent {
- enum IOEventType type;
- struct IODescriptor *iofd;
- union {
- char *recv_str;
- int accept_fd;
- int errid;
- struct IODescriptor *accept_iofd;
- } data;
-};
-
-#define IOHANDLER_LISTEN_IPV4 0x01
-#define IOHANDLER_LISTEN_IPV6 0x02 /* overrides IOHANDLER_LISTEN_IPV4 */
-
-#define IOHANDLER_CONNECT_IPV4 0x01
-#define IOHANDLER_CONNECT_IPV6 0x02 /* overrides IOHANDLER_CONNECT_IPV4 */
-
-#define IOHANDLER_SETTING_HIGH_PRECISION_TIMER 0x01
-
-void iohandler_set(int setting, int value);
-
-struct IODescriptor *iohandler_add(int sockfd, enum IOType type, struct timeval *timeout, iohandler_callback *callback);
-struct IODescriptor *iohandler_timer(struct timeval timeout, iohandler_callback *callback);
-struct IODescriptor *iohandler_constant_timer(int msec, iohandler_callback *callback);
-struct IODescriptor *iohandler_connect(const char *hostname, unsigned int port, int ssl, const char *bind, iohandler_callback *callback);
-struct IODescriptor *iohandler_connect_flags(const char *hostname, unsigned int port, int ssl, const char *bindhost, iohandler_callback *callback, int flags);
-struct IODescriptor *iohandler_listen(const char *hostname, unsigned int port, iohandler_callback *callback);
-struct IODescriptor *iohandler_listen_flags(const char *hostname, unsigned int port, iohandler_callback *callback, int flags);
-struct IODescriptor *iohandler_listen_ssl(const char *hostname, unsigned int port, const char *certfile, const char *keyfile, iohandler_callback *callback);
-struct IODescriptor *iohandler_listen_ssl_flags(const char *hostname, unsigned int port, const char *certfile, const char *keyfile, iohandler_callback *callback, int flags);
-void iohandler_write(struct IODescriptor *iofd, const char *line);
-void iohandler_send(struct IODescriptor *iofd, const char *data, size_t datalen);
-void iohandler_printf(struct IODescriptor *iofd, const char *text, ...);
-void iohandler_close(struct IODescriptor *iofd);
-void iohandler_update(struct IODescriptor *iofd);
-void iohandler_set_timeout(struct IODescriptor *iofd, struct timeval *timeout);
-
-void iohandler_poll();
-void iohandler_poll_timeout(struct timeval timeout);
-
-#endif
+++ /dev/null
-/* IOHandler_SSL.c - IOMultiplexer
- * Copyright (C) 2012 Philipp Kreil (pk910)
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-#include "IOEngine.h"
-#include "IOHandler_SSL.h"
-#ifdef HAVE_SSL
-
-void iohandler_ssl_init() {
- SSL_library_init();
- OpenSSL_add_all_algorithms(); /* load & register all cryptos, etc. */
- SSL_load_error_strings();
-}
-
-static void iohandler_ssl_error() {
- unsigned long e;
- while((e = ERR_get_error())) {
- iohandler_log(IOLOG_ERROR, "SSLv23 ERROR %lu: %s", e, ERR_error_string(e, NULL));
- }
-}
-
-void iohandler_ssl_connect(struct IODescriptor *iofd) {
- iofd->state = IO_SSLWAIT;
- iofd->ssl_server_hs = 0;
- struct IOSSLNode *sslnode = malloc(sizeof(*sslnode));
- sslnode->sslContext = SSL_CTX_new(SSLv23_client_method());
- if(!sslnode->sslContext) {
- iohandler_ssl_error();
- iohandler_log(IOLOG_ERROR, "SSL: could not create client SSL CTX");
- goto ssl_connect_err;
- }
- sslnode->sslHandle = SSL_new(sslnode->sslContext);
- if(!sslnode->sslHandle) {
- iohandler_ssl_error();
- iohandler_log(IOLOG_ERROR, "SSL: could not create client SSL Handle");
- goto ssl_connect_err;
- }
- if(!SSL_set_fd(sslnode->sslHandle, iofd->fd)) {
- iohandler_ssl_error();
- iohandler_log(IOLOG_ERROR, "SSL: could not set client fd in SSL Handle");
- goto ssl_connect_err;
- }
- SSL_set_connect_state(sslnode->sslHandle);
- iofd->sslnode = sslnode;
- iohandler_ssl_client_handshake(iofd);
- return;
-ssl_connect_err:
- free(sslnode);
- iohandler_events(iofd, 0, 0);
-}
-
-void iohandler_ssl_listen(struct IODescriptor *iofd, const char *certfile, const char *keyfile) {
- struct IOSSLNode *sslnode = malloc(sizeof(*sslnode));
- sslnode->sslContext = SSL_CTX_new(SSLv23_server_method());
- if(!sslnode->sslContext) {
- iohandler_ssl_error();
- iohandler_log(IOLOG_ERROR, "SSL: could not create server SSL CTX");
- goto ssl_listen_err;
- }
- /* load certificate */
- if(SSL_CTX_use_certificate_file(sslnode->sslContext, certfile, SSL_FILETYPE_PEM) <= 0) {
- iohandler_ssl_error();
- iohandler_log(IOLOG_ERROR, "SSL: could not load server certificate (%s)", certfile);
- goto ssl_listen_err;
- }
- /* load keyfile */
- if(SSL_CTX_use_PrivateKey_file(sslnode->sslContext, keyfile, SSL_FILETYPE_PEM) <= 0) {
- iohandler_ssl_error();
- iohandler_log(IOLOG_ERROR, "SSL: could not load server keyfile (%s)", keyfile);
- goto ssl_listen_err;
- }
- /* check certificate and keyfile */
- if(!SSL_CTX_check_private_key(sslnode->sslContext)) {
- iohandler_ssl_error();
- iohandler_log(IOLOG_ERROR, "SSL: server certificate (%s) and keyfile (%s) doesn't match!", certfile, keyfile);
- goto ssl_listen_err;
- }
- iofd->sslnode = sslnode;
- return;
-ssl_listen_err:
- free(sslnode);
- iofd->sslnode = NULL;
- iohandler_events(iofd, 0, 0);
-}
-
-void iohandler_ssl_client_handshake(struct IODescriptor *iofd) {
- // Perform an SSL handshake.
- int ret = SSL_do_handshake(iofd->sslnode->sslHandle);
- iofd->ssl_hs_read = 0;
- iofd->ssl_hs_write = 0;
- switch(SSL_get_error(iofd->sslnode->sslHandle, ret)) {
- case SSL_ERROR_NONE:
- iofd->state = IO_CONNECTING;
- iofd->ssl_active = 1;
- iohandler_log(IOLOG_DEBUG, "SSL handshake for %s (fd: %d) successful", iohandler_iotype_name(iofd->type), iofd->fd);
- iohandler_events(iofd, 0, 1); //perform IOEVENT_CONNECTED event
- break;
- case SSL_ERROR_WANT_READ:
- iofd->ssl_hs_read = 1;
- iohandler_log(IOLOG_DEBUG, "SSL_do_handshake for %s (fd: %d) returned SSL_ERROR_WANT_READ", iohandler_iotype_name(iofd->type), iofd->fd);
- break;
- case SSL_ERROR_WANT_WRITE:
- iofd->ssl_hs_write = 1;
- iohandler_log(IOLOG_DEBUG, "SSL_do_handshake for %s (fd: %d) returned SSL_ERROR_WANT_WRITE", iohandler_iotype_name(iofd->type), iofd->fd);
- break;
- default:
- iohandler_log(IOLOG_ERROR, "SSL_do_handshake for %s (fd: %d) failed with ", iohandler_iotype_name(iofd->type), iofd->fd);
- iohandler_events(iofd, 0, 0);
- break;
- }
-}
-
-void iohandler_ssl_client_accepted(struct IODescriptor *iofd, struct IODescriptor *client_iofd) {
- struct IOSSLNode *sslnode = malloc(sizeof(*sslnode));
- sslnode->sslHandle = SSL_new(sslnode->sslContext);
- if(!sslnode->sslHandle) {
- iohandler_ssl_error();
- iohandler_log(IOLOG_ERROR, "SSL: could not create client SSL Handle");
- goto ssl_accept_err;
- }
- if(!SSL_set_fd(sslnode->sslHandle, client_iofd->fd)) {
- iohandler_ssl_error();
- iohandler_log(IOLOG_ERROR, "SSL: could not set client fd in SSL Handle");
- goto ssl_accept_err;
- }
- client_iofd->state = IO_SSLWAIT;
- client_iofd->ssl_server_hs = 1;
- client_iofd->ssl = 1;
- client_iofd->sslnode = sslnode;
- client_iofd->callback = iofd->callback;
- client_iofd->data = iofd;
- return;
-ssl_accept_err:
- iohandler_close(client_iofd);
- free(sslnode);
-}
-
-void iohandler_ssl_server_handshake(struct IODescriptor *iofd) {
- // Perform an SSL handshake.
- int ret = SSL_accept(iofd->sslnode->sslHandle);
- iofd->ssl_hs_read = 0;
- iofd->ssl_hs_write = 0;
- switch(SSL_get_error(iofd->sslnode->sslHandle, ret)) {
- case SSL_ERROR_NONE:
- iofd->state = IO_CONNECTING;
- iofd->ssl_active = 1;
- iohandler_log(IOLOG_DEBUG, "SSL handshake for %s (fd: %d) successful", iohandler_iotype_name(iofd->type), iofd->fd);
- iohandler_events(iofd, 0, 1); //perform IOEVENT_CONNECTED event
- break;
- case SSL_ERROR_WANT_READ:
- iofd->ssl_hs_read = 1;
- iohandler_log(IOLOG_DEBUG, "SSL_do_handshake for %s (fd: %d) returned SSL_ERROR_WANT_READ", iohandler_iotype_name(iofd->type), iofd->fd);
- break;
- case SSL_ERROR_WANT_WRITE:
- iofd->ssl_hs_write = 1;
- iohandler_log(IOLOG_DEBUG, "SSL_do_handshake for %s (fd: %d) returned SSL_ERROR_WANT_WRITE", iohandler_iotype_name(iofd->type), iofd->fd);
- break;
- default:
- iohandler_log(IOLOG_ERROR, "SSL_do_handshake for %s (fd: %d) failed with ", iohandler_iotype_name(iofd->type), iofd->fd);
- iohandler_events(iofd, 0, 0);
- break;
- }
-}
-
-void iohandler_ssl_disconnect(struct IODescriptor *iofd) {
- if(!iofd->sslnode) return;
- SSL_shutdown(iofd->sslnode->sslHandle);
- SSL_free(iofd->sslnode->sslHandle);
- SSL_CTX_free(iofd->sslnode->sslContext);
- free(iofd->sslnode);
- iofd->sslnode = NULL;
- iofd->ssl_active = 0;
-}
-
-int iohandler_ssl_read(struct IODescriptor *iofd, char *buffer, int len) {
- if(!iofd->sslnode) return 0;
- int ret = SSL_read(iofd->sslnode->sslHandle, buffer, len);
- int update = (iofd->ssl_hs_read || iofd->ssl_hs_write);
- iofd->ssl_hs_read = 0;
- iofd->ssl_hs_write = 0;
- switch(SSL_get_error(iofd->sslnode->sslHandle, ret)) {
- case SSL_ERROR_NONE:
- case SSL_ERROR_ZERO_RETURN:
- if(update)
- iohandler_update(iofd);
- return ret;
- break;
- case SSL_ERROR_WANT_READ:
- iofd->ssl_hs_read = 1;
- iohandler_update(iofd);
- iohandler_log(IOLOG_DEBUG, "SSL_read for %s (fd: %d) returned SSL_ERROR_WANT_READ", iohandler_iotype_name(iofd->type), iofd->fd);
- errno = EAGAIN;
- return -1;
- break;
- case SSL_ERROR_WANT_WRITE:
- iofd->ssl_hs_write = 1;
- iohandler_update(iofd);
- iohandler_log(IOLOG_DEBUG, "SSL_read for %s (fd: %d) returned SSL_ERROR_WANT_WRITE", iohandler_iotype_name(iofd->type), iofd->fd);
- errno = EAGAIN;
- return -1;
- break;
- default:
- iohandler_log(IOLOG_ERROR, "SSL_read for %s (fd: %d) failed with ", iohandler_iotype_name(iofd->type), iofd->fd);
- return -1;
- break;
- }
-}
-
-int iohandler_ssl_write(struct IODescriptor *iofd, char *buffer, int len) {
- if(!iofd->sslnode) return 0;
- int ret = SSL_write(iofd->sslnode->sslHandle, buffer, len);
- int update = (iofd->ssl_hs_read || iofd->ssl_hs_write);
- iofd->ssl_hs_read = 0;
- iofd->ssl_hs_write = 0;
- switch(SSL_get_error(iofd->sslnode->sslHandle, ret)) {
- case SSL_ERROR_NONE:
- case SSL_ERROR_ZERO_RETURN:
- if(update)
- iohandler_update(iofd);
- return ret;
- break;
- case SSL_ERROR_WANT_READ:
- iofd->ssl_hs_read = 1;
- iohandler_update(iofd);
- iohandler_log(IOLOG_DEBUG, "SSL_write for %s (fd: %d) returned SSL_ERROR_WANT_READ", iohandler_iotype_name(iofd->type), iofd->fd);
- errno = EAGAIN;
- return -1;
- break;
- case SSL_ERROR_WANT_WRITE:
- iofd->ssl_hs_write = 1;
- iohandler_update(iofd);
- iohandler_log(IOLOG_DEBUG, "SSL_write for %s (fd: %d) returned SSL_ERROR_WANT_WRITE", iohandler_iotype_name(iofd->type), iofd->fd);
- errno = EAGAIN;
- return -1;
- break;
- default:
- iohandler_log(IOLOG_ERROR, "SSL_write for %s (fd: %d) failed with ", iohandler_iotype_name(iofd->type), iofd->fd);
- return -1;
- break;
- }
-}
-
-#else
-// NULL-backend
-
-void iohandler_ssl_init() {};
-void iohandler_ssl_connect(struct IODescriptor *iofd) {};
-void iohandler_ssl_listen(struct IODescriptor *iofd, const char *certfile, const char *keyfile) {};
-void iohandler_ssl_client_handshake(struct IODescriptor *iofd) {};
-void iohandler_ssl_client_accepted(struct IODescriptor *iofd, struct IODescriptor *client_iofd) {};
-void iohandler_ssl_server_handshake(struct IODescriptor *iofd) {};
-void iohandler_ssl_disconnect(struct IODescriptor *iofd) {};
-int iohandler_ssl_read(struct IODescriptor *iofd, char *buffer, int len) { return 0; };
-int iohandler_ssl_write(struct IODescriptor *iofd, char *buffer, int len) { return 0; };
-#endif
+++ /dev/null
-/* IOHandler_SSL.h - IOMultiplexer
- * Copyright (C) 2012 Philipp Kreil (pk910)
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-#ifndef _IOHandler_SSL_h
-#define _IOHandler_SSL_h
-
-struct IODescriptor;
-
-#ifdef HAVE_SSL
-#include <openssl/rand.h>
-#include <openssl/ssl.h>
-#include <openssl/err.h>
-
-struct IOSSLNode {
- SSL *sslHandle;
- SSL_CTX *sslContext;
-};
-#else
-struct IOSSLNode {
- //just unused
-};
-#endif
-
-void iohandler_ssl_init();
-void iohandler_ssl_connect(struct IODescriptor *iofd);
-void iohandler_ssl_listen(struct IODescriptor *iofd, const char *certfile, const char *keyfile);
-void iohandler_ssl_client_handshake(struct IODescriptor *iofd);
-void iohandler_ssl_client_accepted(struct IODescriptor *iofd, struct IODescriptor *client_iofd);
-void iohandler_ssl_server_handshake(struct IODescriptor *iofd);
-void iohandler_ssl_disconnect(struct IODescriptor *iofd);
-int iohandler_ssl_read(struct IODescriptor *iofd, char *buffer, int len);
-int iohandler_ssl_write(struct IODescriptor *iofd, char *buffer, int len);
-
-#endif
+++ /dev/null
-
-CC = gcc
-CFLAGS = -g -O0 -Wall -Wshadow -Werror -DHAVE_PTHREAD_H
-LDFLAGS = -lws2_32 -lpthread
-
-OBJ = ../../IOEngine_epoll.o ../../IOEngine_kevent.o ../../IOEngine_select.o ../../IOEngine_win32.o ../../IOHandler.o ../../IOHandler_SSL.o iotest.o
-
-all: $(OBJ)
- $(CC) $(CFLAGS) -oiotest $(OBJ) $(LDFLAGS)
-
-%.o: %.c
- $(CC) $(CFLAGS) -o$@ -c $<
+++ /dev/null
-/* main.c - IOMultiplexer
- * Copyright (C) 2012 Philipp Kreil (pk910)
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include <stdio.h>
-#include "../IOHandler.h"
-
-static IOHANDLER_CALLBACK(io_callback);
-static IOHANDLER_LOG_BACKEND(io_log);
-
-static struct IODescriptor *irc_iofd = NULL;
-
-int main(int argc, char *argv[]) {
- iolog_backend = io_log;
-
- irc_iofd = iohandler_connect("pk910.de", 6667, 0, NULL, io_callback);
-
- struct IODescriptor *iofd;
- iofd = iohandler_add(0, IOTYPE_STDIN, NULL, io_callback);
- iofd->read_lines = 1;
-
- while(1) {
- iohandler_poll();
- }
-}
-
-static IOHANDLER_CALLBACK(io_callback) {
- switch(event->type) {
- case IOEVENT_CONNECTED:
- printf("[connect]\n");
- break;
- case IOEVENT_CLOSED:
- printf("[disconnect]\n");
- break;
- case IOEVENT_RECV:
- if(event->iofd->type == IOTYPE_STDIN) {
- iohandler_printf(irc_iofd, "%s\n", event->data.recv_str);
- printf("[out] %s\n", event->data.recv_str);
- } else
- printf("[in] %s\n", event->data.recv_str);
- break;
-
- default:
- break;
- }
-}
-
-static IOHANDLER_LOG_BACKEND(io_log) {
- //printf("%s", line);
-}
+++ /dev/null
-
-CC = gcc
-CFLAGS = -g -O0 -Wall -Wshadow -Werror -DHAVE_PTHREAD_H
-LDFLAGS = -lws2_32 -lpthread
-
-OBJ = ../../IOEngine_epoll.o ../../IOEngine_kevent.o ../../IOEngine_select.o ../../IOEngine_win32.o ../../IOHandler.o ../../IOHandler_SSL.o iotest.o
-
-all: $(OBJ)
- $(CC) $(CFLAGS) -oiotest $(OBJ) $(LDFLAGS)
-
-%.o: %.c
- $(CC) $(CFLAGS) -o$@ -c $<
+++ /dev/null
-/* main.c - IOMultiplexer
- * Copyright (C) 2012 Philipp Kreil (pk910)
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include <stdio.h>
-#include "../../IOHandler.h"
-
-#define TEST_DURATION 100
-
-static IOHANDLER_CALLBACK(io_callback);
-static IOHANDLER_LOG_BACKEND(io_log);
-
-static struct timeval test_clock1, test_clock2;
-static int timercount;
-
-void add_timer(int ms) {
- struct timeval timeout;
- gettimeofday(&timeout, NULL);
- timeout.tv_usec += (ms % 1000) * 1000;
- timeout.tv_sec += (ms / 1000);
- if(timeout.tv_usec > 1000000) {
- timeout.tv_usec -= 1000000;
- timeout.tv_sec++;
- }
- iohandler_timer(timeout, io_callback);
-}
-
-int main(int argc, char *argv[]) {
- iolog_backend = io_log;
-
- iohandler_set(IOHANDLER_SETTING_HIGH_PRECISION_TIMER, 1);
-
- gettimeofday(&test_clock1, NULL);
- gettimeofday(&test_clock2, NULL);
- //add_timer(TEST_DURATION);
- iohandler_constant_timer(TEST_DURATION, io_callback);
- timercount = 0;
-
- printf("[timer 0] %ld.%ld\n", test_clock1.tv_sec, test_clock1.tv_usec);
-
- while(1) {
- iohandler_poll();
- }
-}
-
-static IOHANDLER_CALLBACK(io_callback) {
- struct timeval curr_time;
- int diff1;
- double diff2;
- switch(event->type) {
- case IOEVENT_TIMEOUT:
- //add_timer(TEST_DURATION);
- timercount++;
- gettimeofday(&curr_time, NULL);
- diff1 = (curr_time.tv_sec - test_clock1.tv_sec) * 1000 + ((curr_time.tv_usec - test_clock1.tv_usec) / 1000);
- diff2 = (curr_time.tv_sec - test_clock2.tv_sec) * 1000 + ((curr_time.tv_usec - test_clock2.tv_usec) / 1000.0);
- diff2 -= (timercount * TEST_DURATION);
- gettimeofday(&test_clock1, NULL);
- printf("[timer %03d] %ld.%06ld [%d ms] accuracy: %f ms\n", timercount, curr_time.tv_sec, curr_time.tv_usec, diff1, diff2);
- break;
- default:
- break;
- }
-}
-
-static IOHANDLER_LOG_BACKEND(io_log) {
- //printf("%s", line);
-}