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;
64 extern struct IOEngine engine_win32;
66 struct IOEngine *engine = NULL;
68 static void iohandler_init_engine() {
71 if(!engine && engine_kevent.init && engine_kevent.init())
72 engine = &engine_kevent;
73 if(!engine && engine_epoll.init && engine_epoll.init())
74 engine = &engine_epoll;
75 if(!engine && engine_win32.init && engine_win32.init())
76 engine = &engine_win32;
79 if(engine_select.init())
80 engine = &engine_select;
82 iohandler_log(IOLOG_FATAL, "found no useable IO engine");
86 iohandler_log(IOLOG_DEBUG, "using %s IO engine", engine->name);
90 static void iohandler_append(struct IODescriptor *descriptor) {
91 struct timeval *timeout = ((descriptor->timeout.tv_sec || descriptor->timeout.tv_usec) ? &descriptor->timeout : NULL);
93 struct IODescriptor *iofd;
95 descriptor->timeout = *timeout;
97 iofd = timer_priority;
99 iofd = first_descriptor;
101 for(;;iofd = iofd->next) {
102 if(timeval_is_smaler(timeout, (&iofd->timeout))) {
103 descriptor->prev = iofd->prev;
104 descriptor->next = iofd;
105 iofd->prev = descriptor;
107 iofd->prev->next = descriptor;
109 timer_priority = descriptor;
112 if(iofd == timer_priority)
114 if(iofd->next == NULL) {
115 descriptor->next = NULL;
116 descriptor->prev = iofd;
117 iofd->next = descriptor;
119 timer_priority = descriptor;
124 descriptor->prev = NULL;
125 descriptor->next = NULL;
126 first_descriptor = descriptor;
127 timer_priority = descriptor;
131 descriptor->prev = NULL;
132 descriptor->next = first_descriptor;
134 first_descriptor->prev = descriptor;
135 first_descriptor = descriptor;
139 static void iohandler_remove(struct IODescriptor *descriptor, int engine_remove) {
140 //remove IODescriptor from the list
142 descriptor->prev->next = descriptor->next;
144 first_descriptor = descriptor->next;
146 descriptor->next->prev = descriptor->prev;
147 if(descriptor == timer_priority)
148 timer_priority = descriptor->next;
151 engine->remove(descriptor);
152 if(descriptor->readbuf.buffer)
153 free(descriptor->readbuf.buffer);
154 if(descriptor->writebuf.buffer)
155 free(descriptor->writebuf.buffer);
156 iohandler_log(IOLOG_DEBUG, "removed IODescriptor (%d) of type `%s`", descriptor->fd, iohandler_iotype_name(descriptor->type));
160 struct IODescriptor *iohandler_add(int sockfd, enum IOType type, struct timeval *timeout, iohandler_callback *callback) {
161 //just add a new IODescriptor
162 struct IODescriptor *descriptor = calloc(1, sizeof(*descriptor));
164 iohandler_log(IOLOG_ERROR, "could not allocate memory for IODescriptor in %s:%d", __FILE__, __LINE__);
167 descriptor->fd = (type == IOTYPE_STDIN ? fileno(stdin) : sockfd);
168 descriptor->type = type;
169 descriptor->state = (type == IOTYPE_STDIN ? IO_CONNECTED : IO_CLOSED);
170 descriptor->callback = callback;
172 descriptor->timeout = *timeout;
173 if(type != IOTYPE_TIMER) {
174 descriptor->readbuf.buffer = malloc(IO_READ_BUFLEN + 2);
175 descriptor->readbuf.bufpos = 0;
176 descriptor->readbuf.buflen = IO_READ_BUFLEN;
177 descriptor->writebuf.buffer = malloc(IO_READ_BUFLEN + 2);
178 descriptor->writebuf.bufpos = 0;
179 descriptor->writebuf.buflen = IO_READ_BUFLEN;
183 iohandler_init_engine();
188 engine->add(descriptor);
190 //add IODescriptor to the list
191 iohandler_append(descriptor);
193 iohandler_log(IOLOG_DEBUG, "added custom socket descriptor (%d) as type `%s`", sockfd, iohandler_iotype_name(type));
197 void iohandler_set_timeout(struct IODescriptor *descriptor, struct timeval *timeout) {
199 descriptor->prev->next = descriptor->next;
201 first_descriptor = descriptor->next;
203 descriptor->next->prev = descriptor->prev;
204 if(descriptor == timer_priority)
205 timer_priority = descriptor->next;
207 descriptor->timeout = *timeout;
209 descriptor->timeout.tv_sec = 0;
210 descriptor->timeout.tv_usec = 0;
212 iohandler_append(descriptor);
215 static void iohandler_increase_iobuf(struct IOBuffer *iobuf, size_t required) {
216 if(iobuf->buflen >= required) return;
217 char *new_buf = realloc(iobuf->buffer, required + 2);
219 iobuf->buffer = new_buf;
220 iobuf->buflen = required;
224 struct IODescriptor *iohandler_timer(struct timeval timeout, iohandler_callback *callback) {
225 struct IODescriptor *descriptor;
226 descriptor = iohandler_add(-1, IOTYPE_TIMER, &timeout, callback);
228 iohandler_log(IOLOG_ERROR, "could not allocate memory for IODescriptor in %s:%d", __FILE__, __LINE__);
231 iohandler_log(IOLOG_DEBUG, "added timer descriptor (sec: %d; usec: %d)", timeout.tv_sec, timeout.tv_usec);
235 struct IODescriptor *iohandler_connect(const char *hostname, unsigned int port, int ssl, const char *bindhost, iohandler_callback *callback) {
236 //non-blocking connect
238 struct addrinfo hints, *res;
239 struct sockaddr_in *ip4 = NULL;
240 struct sockaddr_in6 *ip6 = NULL;
242 struct sockaddr *dstaddr = NULL;
243 struct IODescriptor *descriptor;
246 iohandler_init_engine();
247 if(!engine) return NULL;
249 memset (&hints, 0, sizeof (hints));
250 hints.ai_family = PF_UNSPEC;
251 hints.ai_socktype = SOCK_STREAM;
252 hints.ai_flags |= AI_CANONNAME;
253 if ((result = getaddrinfo (hostname, NULL, &hints, &res))) {
254 iohandler_log(IOLOG_ERROR, "could not resolve %s to an IP address (%d)", hostname, result);
258 switch (res->ai_family) {
260 ip4 = (struct sockaddr_in *) res->ai_addr;
263 ip6 = (struct sockaddr_in6 *) res->ai_addr;
271 sockfd = socket(AF_INET6, SOCK_STREAM, 0);
273 iohandler_log(IOLOG_ERROR, "could not create socket in %s:%d", __FILE__, __LINE__);
277 ip6->sin6_family = AF_INET6;
278 ip6->sin6_port = htons(port);
280 struct sockaddr_in6 *ip6vhost = NULL;
281 if (bindhost && !getaddrinfo(bindhost, NULL, &hints, &res)) {
283 switch (res->ai_family) {
285 ip6vhost = (struct sockaddr_in6 *) res->ai_addr;
293 ip6vhost->sin6_family = AF_INET6;
294 ip6vhost->sin6_port = htons(0);
295 bind(sockfd, (struct sockaddr*)ip6vhost, sizeof(*ip6vhost));
297 dstaddr = (struct sockaddr*)ip6;
298 dstaddrlen = sizeof(*ip6);
300 sockfd = socket(AF_INET, SOCK_STREAM, 0);
302 iohandler_log(IOLOG_ERROR, "could not create socket in %s:%d", __FILE__, __LINE__);
306 ip4->sin_family = AF_INET;
307 ip4->sin_port = htons(port);
309 struct sockaddr_in *ip4vhost = NULL;
310 if (bindhost && !getaddrinfo(bindhost, NULL, &hints, &res)) {
312 switch (res->ai_family) {
314 ip4vhost = (struct sockaddr_in *) res->ai_addr;
322 ip4vhost->sin_family = AF_INET;
323 ip4vhost->sin_port = htons(0);
324 bind(sockfd, (struct sockaddr*)ip4vhost, sizeof(*ip4vhost));
326 dstaddr = (struct sockaddr*)ip4;
327 dstaddrlen = sizeof(*ip4);
330 //make sockfd unblocking
334 flags = fcntl(sockfd, F_GETFL);
335 fcntl(sockfd, F_SETFL, flags|O_NONBLOCK);
336 flags = fcntl(sockfd, F_GETFD);
337 fcntl(sockfd, F_SETFD, flags|FD_CLOEXEC);
340 /* I hope you're using the Win32 backend or something else that
341 * automatically marks the file descriptor non-blocking...
344 descriptor = iohandler_add(sockfd, IOTYPE_CLIENT, NULL, callback);
349 connect(sockfd, dstaddr, dstaddrlen); //returns EINPROGRESS here (nonblocking)
350 descriptor->state = IO_CONNECTING;
351 descriptor->ssl = (ssl ? 1 : 0);
352 descriptor->read_lines = 1;
353 engine->update(descriptor);
354 iohandler_log(IOLOG_DEBUG, "added client socket (%d) connecting to %s:%d", sockfd, hostname, port);
358 struct IODescriptor *iohandler_listen(const char *hostname, unsigned int port, iohandler_callback *callback) {
360 struct addrinfo hints, *res;
361 struct sockaddr_in *ip4 = NULL;
362 struct sockaddr_in6 *ip6 = NULL;
363 struct IODescriptor *descriptor;
367 iohandler_init_engine();
368 if(!engine) return NULL;
370 memset (&hints, 0, sizeof (hints));
371 hints.ai_family = PF_UNSPEC;
372 hints.ai_socktype = SOCK_STREAM;
373 hints.ai_flags |= AI_CANONNAME;
374 if (getaddrinfo (hostname, NULL, &hints, &res)) {
378 switch (res->ai_family) {
380 ip4 = (struct sockaddr_in *) res->ai_addr;
383 ip6 = (struct sockaddr_in6 *) res->ai_addr;
391 sockfd = socket(AF_INET6, SOCK_STREAM, 0);
392 if(sockfd == -1) return NULL;
395 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt));
397 ip6->sin6_family = AF_INET6;
398 ip6->sin6_port = htons(port);
400 bind(sockfd, (struct sockaddr*)ip6, sizeof(*ip6));
402 sockfd = socket(AF_INET, SOCK_STREAM, 0);
403 if(sockfd == -1) return NULL;
406 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt));
408 ip4->sin_family = AF_INET;
409 ip4->sin_port = htons(port);
411 bind(sockfd, (struct sockaddr*)ip4, sizeof(*ip4));
414 //make sockfd unblocking
418 flags = fcntl(sockfd, F_GETFL);
419 fcntl(sockfd, F_SETFL, flags|O_NONBLOCK);
420 flags = fcntl(sockfd, F_GETFD);
421 fcntl(sockfd, F_SETFD, flags|FD_CLOEXEC);
424 /* I hope you're using the Win32 backend or something else that
425 * automatically marks the file descriptor non-blocking...
428 descriptor = iohandler_add(sockfd, IOTYPE_SERVER, NULL, callback);
434 descriptor->state = IO_LISTENING;
435 engine->update(descriptor);
436 iohandler_log(IOLOG_DEBUG, "added server socket (%d) listening on %s:%d", sockfd, hostname, port);
440 void iohandler_write(struct IODescriptor *iofd, const char *line) {
441 size_t linelen = strlen(line);
442 iohandler_send(iofd, line, linelen);
445 void iohandler_send(struct IODescriptor *iofd, const char *data, size_t datalen) {
446 if(iofd->type == IOTYPE_TIMER || iofd->state == IO_CLOSED) {
447 iohandler_log(IOLOG_ERROR, "could not write to socket (%s)", (iofd->type == IOTYPE_TIMER ? "IOTYPE_TIMER" : "IO_CLOSED"));
450 iohandler_log(IOLOG_DEBUG, "add %d to writebuf (fd: %d): %s", datalen, iofd->fd, data);
451 if(iofd->writebuf.buflen < iofd->writebuf.bufpos + datalen) {
452 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));
453 iohandler_increase_iobuf(&iofd->writebuf, iofd->writebuf.bufpos + datalen);
454 if(iofd->writebuf.buflen < iofd->writebuf.bufpos + datalen) {
455 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));
459 memcpy(iofd->writebuf.buffer + iofd->writebuf.bufpos, data, datalen);
460 iofd->writebuf.bufpos += datalen;
461 engine->update(iofd);
464 void iohandler_printf(struct IODescriptor *iofd, const char *text, ...) {
466 char sendBuf[IO_LINE_LEN];
469 va_start(arg_list, text);
470 pos = vsnprintf(sendBuf, IO_LINE_LEN - 2, text, arg_list);
472 if (pos < 0 || pos > (IO_LINE_LEN - 2)) pos = IO_LINE_LEN - 2;
474 sendBuf[pos+1] = '\0';
475 iohandler_send(iofd, sendBuf, pos+1);
478 void iohandler_try_write(struct IODescriptor *iofd) {
479 if(!iofd->writebuf.bufpos) return;
480 iohandler_log(IOLOG_DEBUG, "write writebuf (%d bytes) to socket (fd: %d)", iofd->writebuf.bufpos, iofd->fd);
483 res = iohandler_ssl_write(iofd, iofd->writebuf.buffer, iofd->writebuf.bufpos);
485 res = send(iofd->fd, iofd->writebuf.buffer, iofd->writebuf.bufpos, 0);
487 if (errno != EAGAIN) {
488 iohandler_log(IOLOG_ERROR, "could not write to socket (fd: %d): %d - %s", iofd->fd, errno, strerror(errno));
491 iofd->writebuf.bufpos -= res;
492 if(iofd->state != IO_CLOSED)
493 engine->update(iofd);
497 void iohandler_close(struct IODescriptor *iofd) {
498 int engine_remove = 1;
499 iofd->state = IO_CLOSED;
500 if(iofd->writebuf.bufpos) {
501 //try to send everything before closing
505 flags = fcntl(iofd->fd, F_GETFL);
506 fcntl(iofd->fd, F_SETFL, flags & ~O_NONBLOCK);
507 flags = fcntl(iofd->fd, F_GETFD);
508 fcntl(iofd->fd, F_SETFD, flags|FD_CLOEXEC);
512 engine->remove(iofd);
514 iohandler_try_write(iofd);
518 iohandler_ssl_disconnect(iofd);
519 if(iofd->type == IOTYPE_SERVER || iofd->type == IOTYPE_CLIENT || iofd->type == IOTYPE_STDIN)
521 iohandler_remove(iofd, engine_remove);
524 void iohandler_update(struct IODescriptor *iofd) {
525 iohandler_log(IOLOG_DEBUG, "external call to iohandler_update (fd: %d)", iofd->fd);
526 engine->update(iofd);
529 static void iohandler_trigger_event(struct IOEvent *event) {
530 if(!event->iofd->callback) return;
531 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);
532 event->iofd->callback(event);
535 void iohandler_events(struct IODescriptor *iofd, int readable, int writeable) {
536 struct IOEvent callback_event;
537 callback_event.type = IOEVENT_IGNORE;
538 callback_event.iofd = iofd;
539 switch(iofd->state) {
541 if(!readable && !writeable) {
542 callback_event.type = IOEVENT_SSLFAILED;
543 iofd->state = IO_CLOSED;
545 iohandler_log(IOLOG_DEBUG, "triggering iohandler_ssl_client_handshake for %s (fd: %d)", iohandler_iotype_name(iofd->type), iofd->fd);
546 iohandler_ssl_client_handshake(iofd);
550 if(iofd->type == IOTYPE_TIMER)
551 callback_event.type = IOEVENT_TIMEOUT;
555 callback_event.data.accept_fd = accept(iofd->fd, NULL, 0);
556 if(callback_event.data.accept_fd < 0) {
557 iohandler_log(IOLOG_ERROR, "could not accept client (server fd: %d): %d - %s", iofd->fd, errno, strerror(errno));
559 callback_event.type = IOEVENT_ACCEPT;
563 if(readable) { //could not connect
564 callback_event.type = IOEVENT_NOTCONNECTED;
566 //arglen = sizeof(callback_event.data.errid);
567 //if (getsockopt(iofd->fd, SOL_SOCKET, SO_ERROR, &callback_event.data.errid, &arglen) < 0)
568 // callback_event.data.errid = errno;
569 iofd->state = IO_CLOSED;
570 engine->update(iofd);
571 } else if(writeable) {
572 if(iofd->ssl && !iofd->ssl_active) {
573 iohandler_log(IOLOG_DEBUG, "triggering iohandler_ssl_connect for %s (fd: %d)", iohandler_iotype_name(iofd->type), iofd->fd);
574 iohandler_ssl_connect(iofd);
577 callback_event.type = IOEVENT_CONNECTED;
578 iofd->state = IO_CONNECTED;
579 engine->update(iofd);
584 if(iofd->read_lines) {
588 bytes = iohandler_ssl_read(iofd, iofd->readbuf.buffer + iofd->readbuf.bufpos, iofd->readbuf.buflen - iofd->readbuf.bufpos);
590 if(iofd->type == IOTYPE_STDIN)
594 bytes = read(iofd->fd, iofd->readbuf.buffer + iofd->readbuf.bufpos, iofd->readbuf.buflen - iofd->readbuf.bufpos);
597 bytes = recv(iofd->fd, iofd->readbuf.buffer + iofd->readbuf.bufpos, iofd->readbuf.buflen - iofd->readbuf.bufpos, 0);
600 if (errno != EAGAIN) {
601 iofd->state = IO_CLOSED;
602 engine->update(iofd);
603 callback_event.type = IOEVENT_CLOSED;
604 callback_event.data.errid = errno;
607 int i, used_bytes = 0;
608 iohandler_log(IOLOG_DEBUG, "received %d bytes (fd: %d). readbuf position: %d", bytes, iofd->fd, iofd->readbuf.bufpos);
609 iofd->readbuf.bufpos += bytes;
610 callback_event.type = IOEVENT_RECV;
611 for(i = 0; i < iofd->readbuf.bufpos; i++) {
612 if(iofd->readbuf.buffer[i] == '\r' && iofd->readbuf.buffer[i+1] == '\n')
613 iofd->readbuf.buffer[i] = 0;
614 else if(iofd->readbuf.buffer[i] == '\n' || iofd->readbuf.buffer[i] == '\r') {
615 iofd->readbuf.buffer[i] = 0;
616 callback_event.data.recv_str = iofd->readbuf.buffer + used_bytes;
617 iohandler_log(IOLOG_DEBUG, "parsed line (%d bytes): %s", i - used_bytes, iofd->readbuf.buffer + used_bytes);
619 iohandler_trigger_event(&callback_event);
620 } else if(i + 1 - used_bytes >= IO_LINE_LEN) { //512 max
621 iofd->readbuf.buffer[i] = 0;
622 callback_event.data.recv_str = iofd->readbuf.buffer + used_bytes;
623 iohandler_log(IOLOG_DEBUG, "parsed and stripped line (%d bytes): %s", i - used_bytes, iofd->readbuf.buffer + used_bytes);
624 for(; i < iofd->readbuf.bufpos; i++) { //skip the rest of the line
625 if(iofd->readbuf.buffer[i] == '\n' || (iofd->readbuf.buffer[i] == '\r' && iofd->readbuf.buffer[i+1] != '\n')) {
630 iohandler_trigger_event(&callback_event);
634 if(used_bytes == iofd->readbuf.bufpos) {
635 iofd->readbuf.bufpos = 0;
636 iohandler_log(IOLOG_DEBUG, "readbuf fully processed (set buffer position to 0)");
638 iohandler_log(IOLOG_DEBUG, "readbuf rest: %d bytes (used %d bytes)", iofd->readbuf.bufpos - used_bytes, used_bytes);
639 memmove(iofd->readbuf.buffer, iofd->readbuf.buffer + used_bytes, iofd->readbuf.bufpos - used_bytes);
640 iofd->readbuf.bufpos -= used_bytes;
643 callback_event.type = IOEVENT_IGNORE;
646 callback_event.type = IOEVENT_READABLE;
649 iohandler_try_write(iofd);
653 if(callback_event.type == IOEVENT_IGNORE && !readable && !writeable)
654 callback_event.type = IOEVENT_TIMEOUT;
655 if(callback_event.type != IOEVENT_IGNORE)
656 iohandler_trigger_event(&callback_event);
659 void iohandler_poll() {
661 struct timeval timeout;
662 timeout.tv_sec = IO_MAX_TIMEOUT;
664 engine->loop(&timeout);
668 //debugging functions
669 char *iohandler_iotype_name(enum IOType type) {
672 return "IOTYPE_UNKNOWN";
674 return "IOTYPE_SERVER";
676 return "IOTYPE_CLIENT";
678 return "IOTYPE_STDIN";
680 return "IOTYPE_TIMER";
682 return "(UNDEFINED)";
686 char *iohandler_iostatus_name(enum IOStatus status) {
691 return "IO_LISTENING";
693 return "IO_CONNECTING";
695 return "IO_CONNECTED";
699 return "(UNDEFINED)";
703 char *iohandler_ioeventtype_name(enum IOEventType type) {
706 return "IOEVENT_IGNORE";
707 case IOEVENT_READABLE:
708 return "IOEVENT_READABLE";
710 return "IOEVENT_RECV";
711 case IOEVENT_CONNECTED:
712 return "IOEVENT_CONNECTED";
713 case IOEVENT_NOTCONNECTED:
714 return "IOEVENT_NOTCONNECTED";
716 return "IOEVENT_CLOSED";
718 return "IOEVENT_ACCEPT";
719 case IOEVENT_TIMEOUT:
720 return "IOEVENT_TIMEOUT";
722 return "(UNDEFINED)";