1 /* IOHandler.c - IOMultiplexer
2 * Copyright (C) 2012 Philipp Kreil (pk910)
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 #include "IOHandler.h"
19 #include "IOHandler_SSL.h"
24 #define _WIN32_WINNT 0x501
33 #include <sys/socket.h>
34 #include <netinet/in.h>
35 #include <netinet/tcp.h>
39 iohandler_log_callback *iolog_backend = NULL;
41 struct IODescriptor *first_descriptor = NULL;
42 struct IODescriptor *timer_priority = NULL;
44 void iohandler_log(enum IOLogType type, char *text, ...) {
46 char logBuf[MAXLOG+1];
49 va_start(arg_list, text);
50 pos = vsnprintf(logBuf, MAXLOG - 1, text, arg_list);
52 if (pos < 0 || pos > (MAXLOG - 1)) pos = MAXLOG - 1;
57 iolog_backend(type, logBuf);
61 extern struct IOEngine engine_select; /* select system call (should always be useable) */
62 extern struct IOEngine engine_kevent;
63 extern struct IOEngine engine_epoll;
65 struct IOEngine *engine = NULL;
67 static void iohandler_init_engine() {
70 if(!engine && engine_kevent.init && engine_kevent.init())
71 engine = &engine_kevent;
72 if(!engine && engine_epoll.init && engine_epoll.init())
73 engine = &engine_epoll;
76 if(engine_select.init())
77 engine = &engine_select;
79 iohandler_log(IOLOG_FATAL, "found no useable IO engine");
83 iohandler_log(IOLOG_DEBUG, "using %s IO engine", engine->name);
87 // Start Windows Sockets.
88 if (WSAStartup(MAKEWORD(2, 0), &wsadata)) {
89 iohandler_log(IOLOG_FATAL, "Unable to start Windows Sockets");
95 static void iohandler_append(struct IODescriptor *descriptor) {
96 struct timeval *timeout = ((descriptor->timeout.tv_sec || descriptor->timeout.tv_usec) ? &descriptor->timeout : NULL);
98 struct IODescriptor *iofd;
100 descriptor->timeout = *timeout;
102 iofd = timer_priority;
104 iofd = first_descriptor;
106 for(;;iofd = iofd->next) {
107 if(timeval_is_smaler(timeout, (&iofd->timeout))) {
108 descriptor->prev = iofd->prev;
109 descriptor->next = iofd;
110 iofd->prev = descriptor;
112 iofd->prev->next = descriptor;
114 timer_priority = descriptor;
117 if(iofd == timer_priority)
119 if(iofd->next == NULL) {
120 descriptor->next = NULL;
121 descriptor->prev = iofd;
122 iofd->next = descriptor;
124 timer_priority = descriptor;
129 descriptor->prev = NULL;
130 descriptor->next = NULL;
131 first_descriptor = descriptor;
132 timer_priority = descriptor;
136 descriptor->prev = NULL;
137 descriptor->next = first_descriptor;
139 first_descriptor->prev = descriptor;
140 first_descriptor = descriptor;
144 static void iohandler_remove(struct IODescriptor *descriptor, int engine_remove) {
145 //remove IODescriptor from the list
147 descriptor->prev->next = descriptor->next;
149 first_descriptor = descriptor->next;
151 descriptor->next->prev = descriptor->prev;
152 if(descriptor == timer_priority)
153 timer_priority = descriptor->next;
156 engine->remove(descriptor);
157 if(descriptor->readbuf.buffer)
158 free(descriptor->readbuf.buffer);
159 if(descriptor->writebuf.buffer)
160 free(descriptor->writebuf.buffer);
161 iohandler_log(IOLOG_DEBUG, "removed IODescriptor (%d) of type `%s`", descriptor->fd, iohandler_iotype_name(descriptor->type));
165 struct IODescriptor *iohandler_add(int sockfd, enum IOType type, struct timeval *timeout, iohandler_callback *callback) {
166 //just add a new IODescriptor
167 struct IODescriptor *descriptor = calloc(1, sizeof(*descriptor));
169 iohandler_log(IOLOG_ERROR, "could not allocate memory for IODescriptor in %s:%d", __FILE__, __LINE__);
172 descriptor->fd = (type == IOTYPE_STDIN ? fileno(stdin) : sockfd);
173 descriptor->type = type;
174 descriptor->state = (type == IOTYPE_STDIN ? IO_CONNECTED : IO_CLOSED);
175 descriptor->callback = callback;
177 descriptor->timeout = *timeout;
178 if(type != IOTYPE_TIMER) {
179 descriptor->readbuf.buffer = malloc(IO_READ_BUFLEN + 2);
180 descriptor->readbuf.bufpos = 0;
181 descriptor->readbuf.buflen = IO_READ_BUFLEN;
182 descriptor->writebuf.buffer = malloc(IO_READ_BUFLEN + 2);
183 descriptor->writebuf.bufpos = 0;
184 descriptor->writebuf.buflen = IO_READ_BUFLEN;
188 iohandler_init_engine();
193 engine->add(descriptor);
195 //add IODescriptor to the list
196 iohandler_append(descriptor);
198 iohandler_log(IOLOG_DEBUG, "added custom socket descriptor (%d) as type `%s`", sockfd, iohandler_iotype_name(type));
202 void iohandler_set_timeout(struct IODescriptor *descriptor, struct timeval *timeout) {
204 descriptor->prev->next = descriptor->next;
206 first_descriptor = descriptor->next;
208 descriptor->next->prev = descriptor->prev;
209 if(descriptor == timer_priority)
210 timer_priority = descriptor->next;
212 descriptor->timeout = *timeout;
214 descriptor->timeout.tv_sec = 0;
215 descriptor->timeout.tv_usec = 0;
217 iohandler_append(descriptor);
220 static void iohandler_increase_iobuf(struct IOBuffer *iobuf, size_t required) {
221 if(iobuf->buflen >= required) return;
222 char *new_buf = realloc(iobuf->buffer, required + 2);
224 iobuf->buffer = new_buf;
225 iobuf->buflen = required;
229 struct IODescriptor *iohandler_timer(struct timeval timeout, iohandler_callback *callback) {
230 struct IODescriptor *descriptor;
231 descriptor = iohandler_add(-1, IOTYPE_TIMER, &timeout, callback);
233 iohandler_log(IOLOG_ERROR, "could not allocate memory for IODescriptor in %s:%d", __FILE__, __LINE__);
236 iohandler_log(IOLOG_DEBUG, "added timer descriptor (sec: %d; usec: %d)", timeout.tv_sec, timeout.tv_usec);
240 struct IODescriptor *iohandler_connect(const char *hostname, unsigned int port, int ssl, const char *bindhost, iohandler_callback *callback) {
241 //non-blocking connect
243 struct addrinfo hints, *res;
244 struct sockaddr_in *ip4 = NULL;
245 struct sockaddr_in6 *ip6 = NULL;
247 struct sockaddr *dstaddr = NULL;
248 struct IODescriptor *descriptor;
251 iohandler_init_engine();
252 if(!engine) return NULL;
254 memset (&hints, 0, sizeof (hints));
255 hints.ai_family = PF_UNSPEC;
256 hints.ai_socktype = SOCK_STREAM;
257 hints.ai_flags |= AI_CANONNAME;
258 if ((result = getaddrinfo (hostname, NULL, &hints, &res))) {
259 iohandler_log(IOLOG_ERROR, "could not resolve %s to an IP address (%d)", hostname, result);
263 switch (res->ai_family) {
265 ip4 = (struct sockaddr_in *) res->ai_addr;
268 ip6 = (struct sockaddr_in6 *) res->ai_addr;
276 sockfd = socket(AF_INET6, SOCK_STREAM, 0);
278 iohandler_log(IOLOG_ERROR, "could not create socket in %s:%d", __FILE__, __LINE__);
282 ip6->sin6_family = AF_INET6;
283 ip6->sin6_port = htons(port);
285 struct sockaddr_in6 *ip6vhost = NULL;
286 if (bindhost && !getaddrinfo(bindhost, NULL, &hints, &res)) {
288 switch (res->ai_family) {
290 ip6vhost = (struct sockaddr_in6 *) res->ai_addr;
298 ip6vhost->sin6_family = AF_INET6;
299 ip6vhost->sin6_port = htons(0);
300 bind(sockfd, (struct sockaddr*)ip6vhost, sizeof(*ip6vhost));
302 dstaddr = (struct sockaddr*)ip6;
303 dstaddrlen = sizeof(*ip6);
305 sockfd = socket(AF_INET, SOCK_STREAM, 0);
307 iohandler_log(IOLOG_ERROR, "could not create socket in %s:%d", __FILE__, __LINE__);
311 ip4->sin_family = AF_INET;
312 ip4->sin_port = htons(port);
314 struct sockaddr_in *ip4vhost = NULL;
315 if (bindhost && !getaddrinfo(bindhost, NULL, &hints, &res)) {
317 switch (res->ai_family) {
319 ip4vhost = (struct sockaddr_in *) res->ai_addr;
327 ip4vhost->sin_family = AF_INET;
328 ip4vhost->sin_port = htons(0);
329 bind(sockfd, (struct sockaddr*)ip4vhost, sizeof(*ip4vhost));
331 dstaddr = (struct sockaddr*)ip4;
332 dstaddrlen = sizeof(*ip4);
335 //make sockfd unblocking
339 flags = fcntl(sockfd, F_GETFL);
340 fcntl(sockfd, F_SETFL, flags|O_NONBLOCK);
341 flags = fcntl(sockfd, F_GETFD);
342 fcntl(sockfd, F_SETFD, flags|FD_CLOEXEC);
345 /* I hope you're using the Win32 backend or something else that
346 * automatically marks the file descriptor non-blocking...
349 descriptor = iohandler_add(sockfd, IOTYPE_CLIENT, NULL, callback);
354 connect(sockfd, dstaddr, dstaddrlen); //returns EINPROGRESS here (nonblocking)
355 descriptor->state = IO_CONNECTING;
356 descriptor->ssl = (ssl ? 1 : 0);
357 descriptor->read_lines = 1;
358 engine->update(descriptor);
359 iohandler_log(IOLOG_DEBUG, "added client socket (%d) connecting to %s:%d", sockfd, hostname, port);
363 struct IODescriptor *iohandler_listen(const char *hostname, unsigned int port, iohandler_callback *callback) {
365 struct addrinfo hints, *res;
366 struct sockaddr_in *ip4 = NULL;
367 struct sockaddr_in6 *ip6 = NULL;
368 struct IODescriptor *descriptor;
372 iohandler_init_engine();
373 if(!engine) return NULL;
375 memset (&hints, 0, sizeof (hints));
376 hints.ai_family = PF_UNSPEC;
377 hints.ai_socktype = SOCK_STREAM;
378 hints.ai_flags |= AI_CANONNAME;
379 if (getaddrinfo (hostname, NULL, &hints, &res)) {
383 switch (res->ai_family) {
385 ip4 = (struct sockaddr_in *) res->ai_addr;
388 ip6 = (struct sockaddr_in6 *) res->ai_addr;
396 sockfd = socket(AF_INET6, SOCK_STREAM, 0);
397 if(sockfd == -1) return NULL;
400 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt));
402 ip6->sin6_family = AF_INET6;
403 ip6->sin6_port = htons(port);
405 bind(sockfd, (struct sockaddr*)ip6, sizeof(*ip6));
407 sockfd = socket(AF_INET, SOCK_STREAM, 0);
408 if(sockfd == -1) return NULL;
411 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt));
413 ip4->sin_family = AF_INET;
414 ip4->sin_port = htons(port);
416 bind(sockfd, (struct sockaddr*)ip4, sizeof(*ip4));
419 //make sockfd unblocking
423 flags = fcntl(sockfd, F_GETFL);
424 fcntl(sockfd, F_SETFL, flags|O_NONBLOCK);
425 flags = fcntl(sockfd, F_GETFD);
426 fcntl(sockfd, F_SETFD, flags|FD_CLOEXEC);
429 /* I hope you're using the Win32 backend or something else that
430 * automatically marks the file descriptor non-blocking...
433 descriptor = iohandler_add(sockfd, IOTYPE_SERVER, NULL, callback);
439 descriptor->state = IO_LISTENING;
440 engine->update(descriptor);
441 iohandler_log(IOLOG_DEBUG, "added server socket (%d) listening on %s:%d", sockfd, hostname, port);
445 void iohandler_write(struct IODescriptor *iofd, const char *line) {
446 size_t linelen = strlen(line);
447 iohandler_send(iofd, line, linelen);
450 void iohandler_send(struct IODescriptor *iofd, const char *data, size_t datalen) {
451 if(iofd->type == IOTYPE_TIMER || iofd->state == IO_CLOSED) {
452 iohandler_log(IOLOG_ERROR, "could not write to socket (%s)", (iofd->type == IOTYPE_TIMER ? "IOTYPE_TIMER" : "IO_CLOSED"));
455 iohandler_log(IOLOG_DEBUG, "add %d to writebuf (fd: %d): %s", datalen, iofd->fd, data);
456 if(iofd->writebuf.buflen < iofd->writebuf.bufpos + datalen) {
457 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));
458 iohandler_increase_iobuf(&iofd->writebuf, iofd->writebuf.bufpos + datalen);
459 if(iofd->writebuf.buflen < iofd->writebuf.bufpos + datalen) {
460 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));
464 memcpy(iofd->writebuf.buffer + iofd->writebuf.bufpos, data, datalen);
465 iofd->writebuf.bufpos += datalen;
466 engine->update(iofd);
469 void iohandler_printf(struct IODescriptor *iofd, const char *text, ...) {
471 char sendBuf[IO_LINE_LEN];
474 va_start(arg_list, text);
475 pos = vsnprintf(sendBuf, IO_LINE_LEN - 2, text, arg_list);
477 if (pos < 0 || pos > (IO_LINE_LEN - 2)) pos = IO_LINE_LEN - 2;
479 sendBuf[pos+1] = '\0';
480 iohandler_send(iofd, sendBuf, pos+1);
483 void iohandler_try_write(struct IODescriptor *iofd) {
484 if(!iofd->writebuf.bufpos) return;
485 iohandler_log(IOLOG_DEBUG, "write writebuf (%d bytes) to socket (fd: %d)", iofd->writebuf.bufpos, iofd->fd);
488 res = iohandler_ssl_write(iofd, iofd->writebuf.buffer, iofd->writebuf.bufpos);
490 res = send(iofd->fd, iofd->writebuf.buffer, iofd->writebuf.bufpos, 0);
492 if (errno != EAGAIN) {
493 iohandler_log(IOLOG_ERROR, "could not write to socket (fd: %d): %d - %s", iofd->fd, errno, strerror(errno));
496 iofd->writebuf.bufpos -= res;
497 if(iofd->state != IO_CLOSED)
498 engine->update(iofd);
502 void iohandler_close(struct IODescriptor *iofd) {
503 int engine_remove = 1;
504 iofd->state = IO_CLOSED;
505 if(iofd->writebuf.bufpos) {
506 //try to send everything before closing
510 flags = fcntl(iofd->fd, F_GETFL);
511 fcntl(iofd->fd, F_SETFL, flags & ~O_NONBLOCK);
512 flags = fcntl(iofd->fd, F_GETFD);
513 fcntl(iofd->fd, F_SETFD, flags|FD_CLOEXEC);
517 engine->remove(iofd);
519 iohandler_try_write(iofd);
523 iohandler_ssl_disconnect(iofd);
524 if(iofd->type == IOTYPE_SERVER || iofd->type == IOTYPE_CLIENT || iofd->type == IOTYPE_STDIN)
526 iohandler_remove(iofd, engine_remove);
529 void iohandler_update(struct IODescriptor *iofd) {
530 iohandler_log(IOLOG_DEBUG, "external call to iohandler_update (fd: %d)", iofd->fd);
531 engine->update(iofd);
534 static void iohandler_trigger_event(struct IOEvent *event) {
535 if(!event->iofd->callback) return;
536 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);
537 event->iofd->callback(event);
540 void iohandler_events(struct IODescriptor *iofd, int readable, int writeable) {
541 struct IOEvent callback_event;
542 callback_event.type = IOEVENT_IGNORE;
543 callback_event.iofd = iofd;
544 switch(iofd->state) {
546 if(!readable && !writeable) {
547 callback_event.type = IOEVENT_SSLFAILED;
548 iofd->state = IO_CLOSED;
550 iohandler_log(IOLOG_DEBUG, "triggering iohandler_ssl_client_handshake for %s (fd: %d)", iohandler_iotype_name(iofd->type), iofd->fd);
551 iohandler_ssl_client_handshake(iofd);
555 if(iofd->type == IOTYPE_TIMER)
556 callback_event.type = IOEVENT_TIMEOUT;
560 callback_event.data.accept_fd = accept(iofd->fd, NULL, 0);
561 if(callback_event.data.accept_fd < 0) {
562 iohandler_log(IOLOG_ERROR, "could not accept client (server fd: %d): %d - %s", iofd->fd, errno, strerror(errno));
564 callback_event.type = IOEVENT_ACCEPT;
568 if(readable) { //could not connect
569 callback_event.type = IOEVENT_NOTCONNECTED;
571 //arglen = sizeof(callback_event.data.errid);
572 //if (getsockopt(iofd->fd, SOL_SOCKET, SO_ERROR, &callback_event.data.errid, &arglen) < 0)
573 // callback_event.data.errid = errno;
574 iofd->state = IO_CLOSED;
575 engine->update(iofd);
576 } else if(writeable) {
577 if(iofd->ssl && !iofd->ssl_active) {
578 iohandler_log(IOLOG_DEBUG, "triggering iohandler_ssl_connect for %s (fd: %d)", iohandler_iotype_name(iofd->type), iofd->fd);
579 iohandler_ssl_connect(iofd);
582 callback_event.type = IOEVENT_CONNECTED;
583 iofd->state = IO_CONNECTED;
584 engine->update(iofd);
589 if(iofd->read_lines) {
593 bytes = iohandler_ssl_read(iofd, iofd->readbuf.buffer + iofd->readbuf.bufpos, iofd->readbuf.buflen - iofd->readbuf.bufpos);
595 if(iofd->type == IOTYPE_STDIN)
599 bytes = read(iofd->fd, iofd->readbuf.buffer + iofd->readbuf.bufpos, iofd->readbuf.buflen - iofd->readbuf.bufpos);
602 bytes = recv(iofd->fd, iofd->readbuf.buffer + iofd->readbuf.bufpos, iofd->readbuf.buflen - iofd->readbuf.bufpos, 0);
605 if (errno != EAGAIN) {
606 iofd->state = IO_CLOSED;
607 engine->update(iofd);
608 callback_event.type = IOEVENT_CLOSED;
609 callback_event.data.errid = errno;
612 int i, used_bytes = 0;
613 iohandler_log(IOLOG_DEBUG, "received %d bytes (fd: %d). readbuf position: %d", bytes, iofd->fd, iofd->readbuf.bufpos);
614 iofd->readbuf.bufpos += bytes;
615 callback_event.type = IOEVENT_RECV;
616 for(i = 0; i < iofd->readbuf.bufpos; i++) {
617 if(iofd->readbuf.buffer[i] == '\r' && iofd->readbuf.buffer[i+1] == '\n')
618 iofd->readbuf.buffer[i] = 0;
619 else if(iofd->readbuf.buffer[i] == '\n' || iofd->readbuf.buffer[i] == '\r') {
620 iofd->readbuf.buffer[i] = 0;
621 callback_event.data.recv_str = iofd->readbuf.buffer + used_bytes;
622 iohandler_log(IOLOG_DEBUG, "parsed line (%d bytes): %s", i - used_bytes, iofd->readbuf.buffer + used_bytes);
624 iohandler_trigger_event(&callback_event);
625 } else if(i + 1 - used_bytes >= IO_LINE_LEN) { //512 max
626 iofd->readbuf.buffer[i] = 0;
627 callback_event.data.recv_str = iofd->readbuf.buffer + used_bytes;
628 iohandler_log(IOLOG_DEBUG, "parsed and stripped line (%d bytes): %s", i - used_bytes, iofd->readbuf.buffer + used_bytes);
629 for(; i < iofd->readbuf.bufpos; i++) { //skip the rest of the line
630 if(iofd->readbuf.buffer[i] == '\n' || (iofd->readbuf.buffer[i] == '\r' && iofd->readbuf.buffer[i+1] != '\n')) {
635 iohandler_trigger_event(&callback_event);
639 if(used_bytes == iofd->readbuf.bufpos) {
640 iofd->readbuf.bufpos = 0;
641 iohandler_log(IOLOG_DEBUG, "readbuf fully processed (set buffer position to 0)");
643 iohandler_log(IOLOG_DEBUG, "readbuf rest: %d bytes (used %d bytes)", iofd->readbuf.bufpos - used_bytes, used_bytes);
644 memmove(iofd->readbuf.buffer, iofd->readbuf.buffer + used_bytes, iofd->readbuf.bufpos - used_bytes);
645 iofd->readbuf.bufpos -= used_bytes;
648 callback_event.type = IOEVENT_IGNORE;
651 callback_event.type = IOEVENT_READABLE;
654 iohandler_try_write(iofd);
658 if(callback_event.type == IOEVENT_IGNORE && !readable && !writeable)
659 callback_event.type = IOEVENT_TIMEOUT;
660 if(callback_event.type != IOEVENT_IGNORE)
661 iohandler_trigger_event(&callback_event);
664 void iohandler_poll() {
666 struct timeval timeout;
667 timeout.tv_sec = IO_MAX_TIMEOUT;
669 engine->loop(&timeout);
673 //debugging functions
674 char *iohandler_iotype_name(enum IOType type) {
677 return "IOTYPE_UNKNOWN";
679 return "IOTYPE_SERVER";
681 return "IOTYPE_CLIENT";
683 return "IOTYPE_STDIN";
685 return "IOTYPE_TIMER";
687 return "(UNDEFINED)";
691 char *iohandler_iostatus_name(enum IOStatus status) {
696 return "IO_LISTENING";
698 return "IO_CONNECTING";
700 return "IO_CONNECTED";
704 return "(UNDEFINED)";
708 char *iohandler_ioeventtype_name(enum IOEventType type) {
711 return "IOEVENT_IGNORE";
712 case IOEVENT_READABLE:
713 return "IOEVENT_READABLE";
715 return "IOEVENT_RECV";
716 case IOEVENT_CONNECTED:
717 return "IOEVENT_CONNECTED";
718 case IOEVENT_NOTCONNECTED:
719 return "IOEVENT_NOTCONNECTED";
721 return "IOEVENT_CLOSED";
723 return "IOEVENT_ACCEPT";
724 case IOEVENT_TIMEOUT:
725 return "IOEVENT_TIMEOUT";
727 return "(UNDEFINED)";