07cd794e9be73afb33dba2eccb065369f4d5e5e1
[NeonServV5.git] / src / IOHandler.c
1 /* IOHandler.c - IOMultiplexer
2  * Copyright (C) 2012  Philipp Kreil (pk910)
3  * 
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.
8  * 
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.
13  * 
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/>. 
16  */
17 #include "IOHandler.h"
18 #include "IOEngine.h"
19 #include "IOHandler_SSL.h"
20 #include <errno.h>
21 #include <stdio.h>
22 #include <unistd.h>
23 #ifdef WIN32
24 #define _WIN32_WINNT 0x501
25 #include <windows.h>
26 #include <winsock2.h>
27 #include <ws2tcpip.h>
28 #else
29 #include <signal.h>
30 #include <stdarg.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <netdb.h>
34 #include <sys/socket.h>
35 #include <netinet/in.h>
36 #include <netinet/tcp.h>
37 #endif
38
39 #ifndef EWOULDBLOCK
40 #define EWOULDBLOCK EAGAIN
41 #endif
42
43 #define MAXLOG 1024
44 iohandler_log_callback *iolog_backend = NULL;
45
46 struct IODescriptor *first_descriptor = NULL;
47 struct IODescriptor *timer_priority = NULL;
48
49 #ifdef HAVE_PTHREAD_H
50 static pthread_mutex_t io_thread_sync;
51 static pthread_mutex_t io_poll_sync;
52 #endif
53
54 void iohandler_log(enum IOLogType type, char *text, ...) {
55     va_list arg_list;
56     char logBuf[MAXLOG+1];
57     int pos;
58     logBuf[0] = '\0';
59     va_start(arg_list, text);
60     pos = vsnprintf(logBuf, MAXLOG - 1, text, arg_list);
61     va_end(arg_list);
62     if (pos < 0 || pos > (MAXLOG - 1)) pos = MAXLOG - 1;
63     logBuf[pos] = '\n';
64     logBuf[pos+1] = '\0';
65     
66     if(iolog_backend)
67         iolog_backend(type, logBuf);
68 }
69
70 /* IO Engines */
71 extern struct IOEngine engine_select; /* select system call (should always be useable) */
72 extern struct IOEngine engine_kevent;
73 extern struct IOEngine engine_epoll;
74 extern struct IOEngine engine_win32;
75
76 int iohandler_settings = 0;
77 struct IOEngine *engine = NULL;
78
79 void iohandler_set(int setting, int value) {
80     if(value)
81         iohandler_settings |= setting;
82     else
83         iohandler_settings &= ~setting;
84 }
85
86 static void iohandler_init_engine() {
87     if(engine) return;
88     IOTHREAD_MUTEX_INIT(io_thread_sync);
89     IOTHREAD_MUTEX_INIT(io_poll_sync);
90     
91     //try other engines
92     if(!(iohandler_settings & IOHANDLER_SETTING_HIGH_PRECISION_TIMER)) {
93         if(!engine && engine_kevent.init && engine_kevent.init())
94             engine = &engine_kevent;
95         if(!engine && engine_epoll.init && engine_epoll.init())
96             engine = &engine_epoll;
97         if(!engine && engine_win32.init && engine_win32.init())
98             engine = &engine_win32;
99     }
100     
101     if (!engine) {
102         if(engine_select.init())
103             engine = &engine_select;
104         else {
105             iohandler_log(IOLOG_FATAL, "found no useable IO engine");
106             return;
107         }
108     }
109     iohandler_log(IOLOG_DEBUG, "using %s IO engine", engine->name);
110     iohandler_ssl_init();
111 }
112
113 static void iohandler_append(struct IODescriptor *descriptor) {
114     IOSYNCHRONIZE(io_thread_sync);
115     struct timeval *timeout = ((descriptor->timeout.tv_sec || descriptor->timeout.tv_usec) ? &descriptor->timeout : NULL);
116     if(timeout) {
117         struct IODescriptor *iofd;
118         int set_priority = 1;
119         descriptor->timeout = *timeout;
120         if(timer_priority)
121             iofd = timer_priority;
122         else
123             iofd = first_descriptor;
124         if(iofd) {
125             for(;;iofd = iofd->next) {
126                 if(timeval_is_smaler(timeout, (&iofd->timeout))) {
127                     descriptor->prev = iofd->prev;
128                     descriptor->next = iofd;
129                     if(iofd->prev)
130                         iofd->prev->next = descriptor;
131                     iofd->prev = descriptor;
132                     if(set_priority)
133                         timer_priority = descriptor;
134                     break;
135                 }
136                 if(iofd == timer_priority)
137                     set_priority = 0;
138                 if(iofd->next == NULL) {
139                     descriptor->next = NULL;
140                     descriptor->prev = iofd;
141                     iofd->next = descriptor;
142                     if(set_priority)
143                         timer_priority = descriptor;
144                     break;
145                 }
146             }
147         } else {
148             descriptor->prev = NULL;
149             descriptor->next = NULL;
150             first_descriptor = descriptor;
151             timer_priority = descriptor;
152         }
153         
154     } else {
155         descriptor->prev = NULL;
156         descriptor->next = first_descriptor;
157         if(first_descriptor)
158             first_descriptor->prev = descriptor;
159         first_descriptor = descriptor;
160     }
161     IODESYNCHRONIZE(io_thread_sync);
162 }
163
164 static void iohandler_remove(struct IODescriptor *descriptor, int engine_remove) {
165     //remove IODescriptor from the list
166     IOSYNCHRONIZE(io_thread_sync);
167     if(descriptor->prev)
168         descriptor->prev->next = descriptor->next;
169     else
170         first_descriptor = descriptor->next;
171     if(descriptor->next)
172         descriptor->next->prev = descriptor->prev;
173     if(descriptor == timer_priority)
174         timer_priority = descriptor->next;
175     
176     if(engine_remove)
177         engine->remove(descriptor);
178     if(descriptor->readbuf.buffer)
179         free(descriptor->readbuf.buffer);
180     if(descriptor->writebuf.buffer)
181         free(descriptor->writebuf.buffer);
182     iohandler_log(IOLOG_DEBUG, "removed IODescriptor (%d) of type `%s`", descriptor->fd, iohandler_iotype_name(descriptor->type));
183     free(descriptor);
184     IODESYNCHRONIZE(io_thread_sync);
185 }
186
187 struct IODescriptor *iohandler_add(int sockfd, enum IOType type, struct timeval *timeout, iohandler_callback *callback) {
188     //just add a new IODescriptor
189     struct IODescriptor *descriptor = calloc(1, sizeof(*descriptor));
190     if(!descriptor) {
191         iohandler_log(IOLOG_ERROR, "could not allocate memory for IODescriptor in %s:%d", __FILE__, __LINE__);
192         return NULL;
193     }
194     descriptor->fd = (type == IOTYPE_STDIN ? fileno(stdin) : sockfd);
195     descriptor->type = type;
196     descriptor->state = (type == IOTYPE_STDIN ? IO_CONNECTED : IO_CLOSED);
197     descriptor->callback = callback;
198     if(timeout) {
199         descriptor->timeout = *timeout;
200         if(descriptor->timeout.tv_usec > 1000000) {
201             descriptor->timeout.tv_usec -= 1000000;
202             descriptor->timeout.tv_sec++;
203         }
204     }
205     if(type != IOTYPE_TIMER) {
206         descriptor->readbuf.buffer = malloc(IO_READ_BUFLEN + 2);
207         descriptor->readbuf.bufpos = 0;
208         descriptor->readbuf.buflen = IO_READ_BUFLEN;
209         descriptor->writebuf.buffer = malloc(IO_READ_BUFLEN + 2);
210         descriptor->writebuf.bufpos = 0;
211         descriptor->writebuf.buflen = IO_READ_BUFLEN;
212     }
213     
214     if(!engine) {
215         iohandler_init_engine();
216         if(!engine) {
217             return NULL;
218         }
219     }
220     engine->add(descriptor);
221     
222     //add IODescriptor to the list
223     iohandler_append(descriptor);
224     
225     iohandler_log(IOLOG_DEBUG, "added custom socket descriptor (%d) as type `%s`", sockfd, iohandler_iotype_name(type));
226     return descriptor;
227 }
228
229 void iohandler_set_timeout(struct IODescriptor *descriptor, struct timeval *timeout) {
230     if(descriptor->prev)
231         descriptor->prev->next = descriptor->next;
232     else
233         first_descriptor = descriptor->next;
234     if(descriptor->next)
235         descriptor->next->prev = descriptor->prev;
236     if(descriptor == timer_priority)
237         timer_priority = descriptor->next;
238     if(timeout) {
239         descriptor->timeout = *timeout;
240         if(descriptor->timeout.tv_usec > 1000000) {
241             descriptor->timeout.tv_usec -= 1000000;
242             descriptor->timeout.tv_sec++;
243         }
244     } else {
245         descriptor->timeout.tv_sec = 0;
246         descriptor->timeout.tv_usec = 0;
247     }
248     iohandler_append(descriptor);
249 }
250
251 static void iohandler_increase_iobuf(struct IOBuffer *iobuf, size_t required) {
252     if(iobuf->buflen >= required) return;
253     char *new_buf = realloc(iobuf->buffer, required + 2);
254     if(new_buf) {
255         iobuf->buffer = new_buf;
256         iobuf->buflen = required;
257     }
258 }
259
260 struct IODescriptor *iohandler_timer(struct timeval timeout, iohandler_callback *callback) {
261     struct IODescriptor *descriptor;
262     descriptor = iohandler_add(-1, IOTYPE_TIMER, &timeout, callback);
263     if(!descriptor) {
264         iohandler_log(IOLOG_ERROR, "could not allocate memory for IODescriptor in %s:%d", __FILE__, __LINE__);
265         return NULL;
266     }
267     iohandler_log(IOLOG_DEBUG, "added timer descriptor (sec: %d; usec: %d)", timeout.tv_sec, timeout.tv_usec);
268     return descriptor;
269 }
270
271 struct IODescriptor *iohandler_connect(const char *hostname, unsigned int port, int ssl, const char *bindhost, iohandler_callback *callback) {
272     return iohandler_connect_flags(hostname, port, ssl, bindhost, callback, IOHANDLER_CONNECT_IPV4 | IOHANDLER_CONNECT_IPV6);
273 }
274
275 struct IODescriptor *iohandler_connect_flags(const char *hostname, unsigned int port, int ssl, const char *bindhost, iohandler_callback *callback, int flags) {
276     //non-blocking connect
277     int sockfd, result;
278     struct addrinfo hints, *res;
279     struct sockaddr_in *ip4 = NULL;
280     struct sockaddr_in6 *ip6 = NULL;
281     size_t dstaddrlen;
282     struct sockaddr *dstaddr = NULL;
283     struct IODescriptor *descriptor;
284     
285     if(!engine) {
286         iohandler_init_engine();
287         if(!engine) return NULL;
288     }
289     memset (&hints, 0, sizeof (hints));
290     hints.ai_family = PF_UNSPEC;
291     hints.ai_socktype = SOCK_STREAM;
292     hints.ai_flags |= AI_CANONNAME;
293     if ((result = getaddrinfo (hostname, NULL, &hints, &res))) {
294         iohandler_log(IOLOG_ERROR, "could not resolve %s to an IP address (%d)", hostname, result);
295         return NULL;
296     }
297     while (res) {
298         switch (res->ai_family) {
299         case AF_INET:
300             ip4 = (struct sockaddr_in *) res->ai_addr;
301             break;
302         case AF_INET6:
303             ip6 = (struct sockaddr_in6 *) res->ai_addr;
304             break;
305         }
306         res = res->ai_next;
307         freeaddrinfo(res);
308     }
309     
310     if(ip6 && (flags & IOHANDLER_CONNECT_IPV6)) {
311         sockfd = socket(AF_INET6, SOCK_STREAM, 0);
312         if(sockfd == -1) {
313             iohandler_log(IOLOG_ERROR, "could not create socket in %s:%d", __FILE__, __LINE__);
314             return NULL;
315         }
316         
317         ip6->sin6_family = AF_INET6;
318         ip6->sin6_port = htons(port);
319         
320         struct sockaddr_in6 *ip6vhost = NULL;
321         if (bindhost && !getaddrinfo(bindhost, NULL, &hints, &res)) {
322             while (res) {
323                 switch (res->ai_family) {
324                 case AF_INET6:
325                     ip6vhost = (struct sockaddr_in6 *) res->ai_addr;
326                     break;
327                 }
328                 res = res->ai_next;
329                 freeaddrinfo(res);
330             }
331         }
332         if(ip6vhost) {
333             ip6vhost->sin6_family = AF_INET6;
334             ip6vhost->sin6_port = htons(0);
335             bind(sockfd, (struct sockaddr*)ip6vhost, sizeof(*ip6vhost));
336         }
337         dstaddr = (struct sockaddr*)ip6;
338         dstaddrlen = sizeof(*ip6);
339     } else if(ip4 && (flags & IOHANDLER_CONNECT_IPV4)) {
340         sockfd = socket(AF_INET, SOCK_STREAM, 0);
341         if(sockfd == -1) {
342             iohandler_log(IOLOG_ERROR, "could not create socket in %s:%d", __FILE__, __LINE__);
343             return NULL;
344         }
345         
346         ip4->sin_family = AF_INET;
347         ip4->sin_port = htons(port);
348         
349         struct sockaddr_in *ip4vhost = NULL;
350         if (bindhost && !getaddrinfo(bindhost, NULL, &hints, &res)) {
351             while (res) {
352                 switch (res->ai_family) {
353                 case AF_INET:
354                     ip4vhost = (struct sockaddr_in *) res->ai_addr;
355                     break;
356                 }
357                 res = res->ai_next;
358                 freeaddrinfo(res);
359             }
360         }
361         if(ip4vhost) {
362             ip4vhost->sin_family = AF_INET;
363             ip4vhost->sin_port = htons(0);
364             bind(sockfd, (struct sockaddr*)ip4vhost, sizeof(*ip4vhost));
365         }
366         dstaddr = (struct sockaddr*)ip4;
367         dstaddrlen = sizeof(*ip4);
368     } else
369         return NULL;
370     //prevent SIGPIPE
371     #ifndef WIN32
372     #if defined(SO_NOSIGPIPE)
373     {
374         int set = 1;
375         setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&set, sizeof(int));
376     }
377     #else
378     signal(SIGPIPE, SIG_IGN);
379     #endif
380     #endif
381     //make sockfd unblocking
382     #if defined(F_GETFL)
383     {
384         int flags;
385         flags = fcntl(sockfd, F_GETFL);
386         fcntl(sockfd, F_SETFL, flags|O_NONBLOCK);
387         flags = fcntl(sockfd, F_GETFD);
388         fcntl(sockfd, F_SETFD, flags|FD_CLOEXEC);
389     }
390     #else
391     /* I hope you're using the Win32 backend or something else that
392      * automatically marks the file descriptor non-blocking...
393      */
394     #endif
395     descriptor = iohandler_add(sockfd, IOTYPE_CLIENT, NULL, callback);
396     if(!descriptor) {
397         close(sockfd);
398         return NULL;
399     }
400     connect(sockfd, dstaddr, dstaddrlen); //returns EINPROGRESS here (nonblocking)
401     descriptor->state = IO_CONNECTING;
402     descriptor->ssl = (ssl ? 1 : 0);
403     descriptor->read_lines = 1;
404     engine->update(descriptor);
405     iohandler_log(IOLOG_DEBUG, "added client socket (%d) connecting to %s:%d", sockfd, hostname, port);
406     return descriptor;
407 }
408
409 struct IODescriptor *iohandler_listen(const char *hostname, unsigned int port, iohandler_callback *callback) {
410     return iohandler_listen_flags(hostname, port, callback, IOHANDLER_LISTEN_IPV4 | IOHANDLER_LISTEN_IPV6);
411 }
412
413 struct IODescriptor *iohandler_listen_flags(const char *hostname, unsigned int port, iohandler_callback *callback, int flags) {
414     int sockfd;
415     struct addrinfo hints, *res;
416     struct sockaddr_in *ip4 = NULL;
417     struct sockaddr_in6 *ip6 = NULL;
418     struct IODescriptor *descriptor;
419     unsigned int opt;
420     
421     if(!engine) {
422         iohandler_init_engine();
423         if(!engine) return NULL;
424     }
425     memset (&hints, 0, sizeof (hints));
426     hints.ai_family = PF_UNSPEC;
427     hints.ai_socktype = SOCK_STREAM;
428     hints.ai_flags |= AI_CANONNAME;
429     if (getaddrinfo (hostname, NULL, &hints, &res)) {
430         return NULL;
431     }
432     while (res) {
433         switch (res->ai_family) {
434         case AF_INET:
435             ip4 = (struct sockaddr_in *) res->ai_addr;
436             break;
437         case AF_INET6:
438             ip6 = (struct sockaddr_in6 *) res->ai_addr;
439             break;
440         }
441         res = res->ai_next;
442         freeaddrinfo(res);
443     }
444     
445     if(ip6 && (flags & IOHANDLER_LISTEN_IPV6)) {
446         sockfd = socket(AF_INET6, SOCK_STREAM, 0);
447         if(sockfd == -1) return NULL;
448         
449         opt = 1;
450         setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt));
451         
452         ip6->sin6_family = AF_INET6;
453         ip6->sin6_port = htons(port);
454         
455         bind(sockfd, (struct sockaddr*)ip6, sizeof(*ip6));
456     } else if(ip4 && (flags && IOHANDLER_LISTEN_IPV4)) {
457         sockfd = socket(AF_INET, SOCK_STREAM, 0);
458         if(sockfd == -1) return NULL;
459         
460         opt = 1;
461         setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt));
462         
463         ip4->sin_family = AF_INET;
464         ip4->sin_port = htons(port);
465         
466         bind(sockfd, (struct sockaddr*)ip4, sizeof(*ip4));
467     } else
468         return NULL;
469     //prevent SIGPIPE
470     #ifndef WIN32
471     #if defined(SO_NOSIGPIPE)
472     {
473         int set = 1;
474         setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&set, sizeof(int));
475     }
476     #else
477     signal(SIGPIPE, SIG_IGN);
478     #endif
479     #endif
480     //make sockfd unblocking
481     #if defined(F_GETFL)
482     {
483         int flag;
484         flag = fcntl(sockfd, F_GETFL);
485         fcntl(sockfd, F_SETFL, flag|O_NONBLOCK);
486         flag = fcntl(sockfd, F_GETFD);
487         fcntl(sockfd, F_SETFD, flag|FD_CLOEXEC);
488     }
489     #else
490     /* I hope you're using the Win32 backend or something else that
491      * automatically marks the file descriptor non-blocking...
492      */
493     #endif
494     descriptor = iohandler_add(sockfd, IOTYPE_SERVER, NULL, callback);
495     if(!descriptor) {
496         close(sockfd);
497         return NULL;
498     }
499     listen(sockfd, 1);
500     descriptor->state = IO_LISTENING;
501     engine->update(descriptor);
502     iohandler_log(IOLOG_DEBUG, "added server socket (%d) listening on %s:%d", sockfd, hostname, port);
503     return descriptor;
504 }
505
506 struct IODescriptor *iohandler_listen_ssl(const char *hostname, unsigned int port, const char *certfile, const char *keyfile, iohandler_callback *callback) {
507     return iohandler_listen_ssl_flags(hostname, port, certfile, keyfile, callback, IOHANDLER_LISTEN_IPV4 | IOHANDLER_LISTEN_IPV6);
508 }
509
510 struct IODescriptor *iohandler_listen_ssl_flags(const char *hostname, unsigned int port, const char *certfile, const char *keyfile, iohandler_callback *callback, int flags) {
511     struct IODescriptor *descriptor = iohandler_listen_flags(hostname, port, callback, flags);
512     if(!descriptor)
513         return NULL;
514     //SSL Server Socket
515     iohandler_ssl_listen(descriptor, certfile, keyfile);
516     if(descriptor->sslnode)
517         descriptor->ssl = 1;
518     return descriptor;
519 }
520
521 void iohandler_write(struct IODescriptor *iofd, const char *line) {
522     size_t linelen = strlen(line);
523     iohandler_send(iofd, line, linelen);
524 }
525
526 void iohandler_send(struct IODescriptor *iofd, const char *data, size_t datalen) {
527     if(iofd->type == IOTYPE_TIMER || iofd->state == IO_CLOSED) {
528         iohandler_log(IOLOG_ERROR, "could not write to socket (%s)", (iofd->type == IOTYPE_TIMER ? "IOTYPE_TIMER" : "IO_CLOSED"));
529         return;
530     }
531     iohandler_log(IOLOG_DEBUG, "add %d to writebuf (fd: %d): %s", datalen, iofd->fd, data);
532     if(iofd->writebuf.buflen < iofd->writebuf.bufpos + datalen) {
533         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));
534         iohandler_increase_iobuf(&iofd->writebuf, iofd->writebuf.bufpos + datalen);
535         if(iofd->writebuf.buflen < iofd->writebuf.bufpos + datalen) {
536             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));
537             return;
538         }
539     }
540     memcpy(iofd->writebuf.buffer + iofd->writebuf.bufpos, data, datalen);
541     iofd->writebuf.bufpos += datalen;
542     engine->update(iofd);
543 }
544
545 void iohandler_printf(struct IODescriptor *iofd, const char *text, ...) {
546     va_list arg_list;
547     char sendBuf[IO_LINE_LEN];
548     int pos;
549     sendBuf[0] = '\0';
550     va_start(arg_list, text);
551     pos = vsnprintf(sendBuf, IO_LINE_LEN - 2, text, arg_list);
552     va_end(arg_list);
553     if (pos < 0 || pos > (IO_LINE_LEN - 2)) pos = IO_LINE_LEN - 2;
554     sendBuf[pos] = '\n';
555     sendBuf[pos+1] = '\0';
556     iohandler_send(iofd, sendBuf, pos+1);
557 }
558
559 static int iohandler_try_write(struct IODescriptor *iofd) {
560     if(!iofd->writebuf.bufpos) return 0;
561     iohandler_log(IOLOG_DEBUG, "write writebuf (%d bytes) to socket (fd: %d)", iofd->writebuf.bufpos, iofd->fd);
562     int res;
563     if(iofd->ssl_active)
564         res = iohandler_ssl_write(iofd, iofd->writebuf.buffer, iofd->writebuf.bufpos);
565     else
566         res = send(iofd->fd, iofd->writebuf.buffer, iofd->writebuf.bufpos, 0);
567     if(res < 0) {
568         if (errno != EAGAIN && errno != EWOULDBLOCK)
569             iohandler_log(IOLOG_ERROR, "could not write to socket (fd: %d): %d - %s", iofd->fd, errno, strerror(errno));
570         else
571             res = 0;
572     } else {
573         iofd->writebuf.bufpos -= res;
574         if(iofd->state != IO_CLOSED)
575             engine->update(iofd);
576     }
577     return res;
578 }
579
580 void iohandler_close(struct IODescriptor *iofd) {
581     int engine_remove = 1;
582     iofd->state = IO_CLOSED;
583     if(iofd->writebuf.bufpos) {
584         //try to send everything before closing
585 #if defined(F_GETFL)
586         {
587             int flags;
588             flags = fcntl(iofd->fd, F_GETFL);
589             fcntl(iofd->fd, F_SETFL, flags & ~O_NONBLOCK);
590             flags = fcntl(iofd->fd, F_GETFD);
591             fcntl(iofd->fd, F_SETFD, flags|FD_CLOEXEC);
592         }
593 #else
594         engine_remove = 0;
595         engine->remove(iofd);
596 #endif
597         iohandler_try_write(iofd);
598     }
599     //close IODescriptor
600     if(iofd->ssl)
601         iohandler_ssl_disconnect(iofd);
602     if(iofd->type == IOTYPE_SERVER || iofd->type == IOTYPE_CLIENT || iofd->type == IOTYPE_STDIN)
603         close(iofd->fd);
604     iohandler_remove(iofd, engine_remove);
605 }
606
607 void iohandler_update(struct IODescriptor *iofd) {
608     iohandler_log(IOLOG_DEBUG, "external call to iohandler_update (fd: %d)", iofd->fd);
609     engine->update(iofd);
610 }
611
612 static void iohandler_trigger_event(struct IOEvent *event) {
613     if(!event->iofd->callback) return;
614     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);
615     event->iofd->callback(event);
616 }
617
618 void iohandler_events(struct IODescriptor *iofd, int readable, int writeable) {
619     struct IOEvent callback_event;
620     callback_event.type = IOEVENT_IGNORE;
621     callback_event.iofd = iofd;
622     switch(iofd->state) {
623         case IO_SSLWAIT:
624             if(!readable && !writeable) {
625                 if(!iofd->ssl_server_hs) {
626                     callback_event.type = IOEVENT_SSLFAILED;
627                     iofd->state = IO_CLOSED;
628                     engine->update(iofd);
629                 } else
630                     iohandler_close(iofd);
631             } else if(iofd->ssl_server_hs) {
632                 iohandler_log(IOLOG_DEBUG, "triggering iohandler_ssl_server_handshake for %s (fd: %d)", iohandler_iotype_name(iofd->type), iofd->fd);
633                 iohandler_ssl_server_handshake(iofd);
634             } else {
635                 iohandler_log(IOLOG_DEBUG, "triggering iohandler_ssl_client_handshake for %s (fd: %d)", iohandler_iotype_name(iofd->type), iofd->fd);
636                 iohandler_ssl_client_handshake(iofd);
637             }
638             break;
639         case IO_CLOSED:
640             if(iofd->type == IOTYPE_TIMER)
641                 callback_event.type = IOEVENT_TIMEOUT;
642             break;
643         case IO_LISTENING:
644             if(readable) {
645                 callback_event.data.accept_fd = accept(iofd->fd, NULL, 0);
646                 if(callback_event.data.accept_fd < 0) {
647                     iohandler_log(IOLOG_ERROR, "could not accept client (server fd: %d): %d - %s", iofd->fd, errno, strerror(errno));
648                 } else if(iofd->ssl) {
649                     struct IODescriptor *client_iofd = iohandler_add(callback_event.data.accept_fd, IOTYPE_CLIENT, NULL, NULL);
650                     iohandler_ssl_client_accepted(iofd, client_iofd);
651                 } else
652                     callback_event.type = IOEVENT_ACCEPT;
653             }
654             break;
655         case IO_CONNECTING:
656             if(readable) { //could not connect
657                 callback_event.type = IOEVENT_NOTCONNECTED;
658                 //socklen_t arglen;
659                 //arglen = sizeof(callback_event.data.errid);
660                 //if (getsockopt(iofd->fd, SOL_SOCKET, SO_ERROR, &callback_event.data.errid, &arglen) < 0)
661                 //    callback_event.data.errid = errno;
662                 iofd->state = IO_CLOSED;
663                                 engine->update(iofd);
664             } else if(writeable) {
665                 if(iofd->ssl && !iofd->ssl_active) {
666                     iohandler_log(IOLOG_DEBUG, "triggering iohandler_ssl_connect for %s (fd: %d)", iohandler_iotype_name(iofd->type), iofd->fd);
667                     iohandler_ssl_connect(iofd);
668                     return;
669                 }
670                 if(iofd->ssl && iofd->ssl_server_hs) {
671                     callback_event.type = IOEVENT_SSLACCEPT;
672                     callback_event.iofd = iofd->data;
673                     callback_event.data.accept_iofd = iofd;
674                     iofd->data = NULL;
675                 }
676                 else 
677                     callback_event.type = IOEVENT_CONNECTED;
678                 iofd->state = IO_CONNECTED;
679                 engine->update(iofd);
680             }
681             break;
682         case IO_CONNECTED:
683             if(readable) {
684                 if(iofd->read_lines) {
685                     int bytes;
686                     
687                     if(iofd->ssl_active)
688                         bytes = iohandler_ssl_read(iofd, iofd->readbuf.buffer + iofd->readbuf.bufpos, iofd->readbuf.buflen - iofd->readbuf.bufpos);
689                     else {
690                         if(iofd->type == IOTYPE_STDIN)
691                             #ifdef WIN32
692                             bytes = readable;
693                             #else
694                             bytes = read(iofd->fd, iofd->readbuf.buffer + iofd->readbuf.bufpos, iofd->readbuf.buflen - iofd->readbuf.bufpos);
695                             #endif
696                         else
697                             bytes = recv(iofd->fd, iofd->readbuf.buffer + iofd->readbuf.bufpos, iofd->readbuf.buflen - iofd->readbuf.bufpos, 0);
698                     }
699                     if(bytes <= 0) {
700                         if (errno != EAGAIN || errno != EWOULDBLOCK) {
701                             iofd->state = IO_CLOSED;
702                                                         engine->update(iofd);
703                             callback_event.type = IOEVENT_CLOSED;
704                             callback_event.data.errid = errno;
705                         }
706                     } else {
707                         int i, used_bytes = 0;
708                         iohandler_log(IOLOG_DEBUG, "received %d bytes (fd: %d). readbuf position: %d", bytes, iofd->fd, iofd->readbuf.bufpos);
709                         iofd->readbuf.bufpos += bytes;
710                         callback_event.type = IOEVENT_RECV;
711                         for(i = 0; i < iofd->readbuf.bufpos; i++) {
712                             if(iofd->readbuf.buffer[i] == '\r' && iofd->readbuf.buffer[i+1] == '\n')
713                                 iofd->readbuf.buffer[i] = 0;
714                             else if(iofd->readbuf.buffer[i] == '\n' || iofd->readbuf.buffer[i] == '\r') {
715                                 iofd->readbuf.buffer[i] = 0;
716                                 callback_event.data.recv_str = iofd->readbuf.buffer + used_bytes;
717                                 iohandler_log(IOLOG_DEBUG, "parsed line (%d bytes): %s", i - used_bytes, iofd->readbuf.buffer + used_bytes);
718                                 used_bytes = i+1;
719                                 iohandler_trigger_event(&callback_event);
720                             } else if(i + 1 - used_bytes >= IO_LINE_LEN) { //512 max
721                                 iofd->readbuf.buffer[i] = 0;
722                                 callback_event.data.recv_str = iofd->readbuf.buffer + used_bytes;
723                                 iohandler_log(IOLOG_DEBUG, "parsed and stripped line (%d bytes): %s", i - used_bytes, iofd->readbuf.buffer + used_bytes);
724                                 for(; i < iofd->readbuf.bufpos; i++) { //skip the rest of the line
725                                     if(iofd->readbuf.buffer[i] == '\n' || (iofd->readbuf.buffer[i] == '\r' && iofd->readbuf.buffer[i+1] != '\n')) {
726                                         break;
727                                     }
728                                 }
729                                 used_bytes = i+1;
730                                 iohandler_trigger_event(&callback_event);
731                             }
732                         }
733                         if(used_bytes) {
734                             if(used_bytes == iofd->readbuf.bufpos) {
735                                 iofd->readbuf.bufpos = 0;
736                                 iohandler_log(IOLOG_DEBUG, "readbuf fully processed (set buffer position to 0)");
737                             } else {
738                                 iohandler_log(IOLOG_DEBUG, "readbuf rest: %d bytes (used %d bytes)", iofd->readbuf.bufpos - used_bytes, used_bytes);
739                                 memmove(iofd->readbuf.buffer, iofd->readbuf.buffer + used_bytes, iofd->readbuf.bufpos - used_bytes);
740                                 iofd->readbuf.bufpos -= used_bytes;
741                             }
742                         }
743                         callback_event.type = IOEVENT_IGNORE;
744                     }
745                 } else
746                     callback_event.type = IOEVENT_READABLE;
747             }
748             if(writeable) {
749                 int bytes;
750                 bytes = iohandler_try_write(iofd);
751                 if(bytes < 0) {
752                     iofd->state = IO_CLOSED;
753                     engine->update(iofd);
754                     callback_event.type = IOEVENT_CLOSED;
755                     callback_event.data.errid = errno;
756                 }
757             }
758             break;
759     }
760     if(callback_event.type == IOEVENT_IGNORE && !readable && !writeable) 
761         callback_event.type = IOEVENT_TIMEOUT;
762     if(callback_event.type != IOEVENT_IGNORE)
763         iohandler_trigger_event(&callback_event);
764 }
765
766 void iohandler_poll() {
767     struct timeval timeout;
768     timeout.tv_sec = IO_MAX_TIMEOUT;
769     timeout.tv_usec = 0;
770     iohandler_poll_timeout(timeout);
771 }
772
773 void iohandler_poll_timeout(struct timeval timeout) {
774     if(engine) {
775         IOSYNCHRONIZE(io_poll_sync); //quite senceless multithread support... better support will follow
776         engine->loop(&timeout);
777         IODESYNCHRONIZE(io_poll_sync);
778     }
779 }
780
781 //debugging functions
782 char *iohandler_iotype_name(enum IOType type) {
783     switch(type) {
784         case IOTYPE_UNKNOWN:
785             return "IOTYPE_UNKNOWN";
786         case IOTYPE_SERVER:
787             return "IOTYPE_SERVER";
788         case IOTYPE_CLIENT:
789             return "IOTYPE_CLIENT";
790         case IOTYPE_STDIN:
791             return "IOTYPE_STDIN";
792         case IOTYPE_TIMER:
793             return "IOTYPE_TIMER";
794         default:
795             return "(UNDEFINED)";
796     }
797 }
798
799 char *iohandler_iostatus_name(enum IOStatus status) {
800     switch(status) {
801         case IO_CLOSED:
802             return "IO_CLOSED";
803         case IO_LISTENING:
804             return "IO_LISTENING";
805         case IO_CONNECTING:
806             return "IO_CONNECTING";
807         case IO_CONNECTED:
808             return "IO_CONNECTED";
809         case IO_SSLWAIT:
810             return "IO_SSLWAIT";
811         default:
812             return "(UNDEFINED)";
813     }
814 }
815
816 char *iohandler_ioeventtype_name(enum IOEventType type) {
817     switch(type) {
818         case IOEVENT_IGNORE:
819             return "IOEVENT_IGNORE";
820         case IOEVENT_READABLE:
821             return "IOEVENT_READABLE";
822         case IOEVENT_RECV:
823             return "IOEVENT_RECV";
824         case IOEVENT_CONNECTED:
825             return "IOEVENT_CONNECTED";
826         case IOEVENT_NOTCONNECTED:
827             return "IOEVENT_NOTCONNECTED";
828         case IOEVENT_CLOSED:
829             return "IOEVENT_CLOSED";
830         case IOEVENT_ACCEPT:
831             return "IOEVENT_ACCEPT";
832         case IOEVENT_SSLACCEPT:
833             return "IOEVENT_SSLACCEPT";
834         case IOEVENT_TIMEOUT:
835             return "IOEVENT_TIMEOUT";
836         default:
837             return "(UNDEFINED)";
838     }
839 }