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