[IOMultiplexer] initial commit
[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 <stdarg.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <netdb.h>
33 #include <sys/socket.h>
34 #include <netinet/in.h>
35 #include <netinet/tcp.h>
36 #endif
37
38 #define MAXLOG 1024
39 iohandler_log_callback *iolog_backend = NULL;
40
41 struct IODescriptor *first_descriptor = NULL;
42 struct IODescriptor *timer_priority = NULL;
43
44 void iohandler_log(enum IOLogType type, char *text, ...) {
45     va_list arg_list;
46     char logBuf[MAXLOG+1];
47     int pos;
48     logBuf[0] = '\0';
49     va_start(arg_list, text);
50     pos = vsnprintf(logBuf, MAXLOG - 1, text, arg_list);
51     va_end(arg_list);
52     if (pos < 0 || pos > (MAXLOG - 1)) pos = MAXLOG - 1;
53     logBuf[pos] = '\n';
54     logBuf[pos+1] = '\0';
55     
56     if(iolog_backend)
57         iolog_backend(type, logBuf);
58 }
59
60 /* IO Engines */
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
65 struct IOEngine *engine = NULL;
66
67 static void iohandler_init_engine() {
68     if(engine) return;
69     //try other engines
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;
74     
75     if (!engine) {
76         if(engine_select.init())
77             engine = &engine_select;
78         else {
79             iohandler_log(IOLOG_FATAL, "found no useable IO engine");
80             return;
81         }
82     }
83     iohandler_log(IOLOG_DEBUG, "using %s IO engine", engine->name);
84     iohandler_ssl_init();
85     #ifdef WIN32
86     WSADATA wsadata;
87     // Start Windows Sockets.
88     if (WSAStartup(MAKEWORD(2, 0), &wsadata)) {
89         iohandler_log(IOLOG_FATAL, "Unable to start Windows Sockets");
90         return;
91     }
92     #endif
93 }
94
95 static void iohandler_append(struct IODescriptor *descriptor) {
96     struct timeval *timeout = ((descriptor->timeout.tv_sec || descriptor->timeout.tv_usec) ? &descriptor->timeout : NULL);
97     if(timeout) {
98         struct IODescriptor *iofd;
99         int set_priority = 1;
100         descriptor->timeout = *timeout;
101         if(timer_priority)
102             iofd = timer_priority;
103         else
104             iofd = first_descriptor;
105         if(iofd) {
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;
111                     if(iofd->prev)
112                         iofd->prev->next = descriptor;
113                     if(set_priority)
114                         timer_priority = descriptor;
115                     break;
116                 }
117                 if(iofd == timer_priority)
118                     set_priority = 0;
119                 if(iofd->next == NULL) {
120                     descriptor->next = NULL;
121                     descriptor->prev = iofd;
122                     iofd->next = descriptor;
123                     if(set_priority)
124                         timer_priority = descriptor;
125                     break;
126                 }
127             }
128         } else {
129             descriptor->prev = NULL;
130             descriptor->next = NULL;
131             first_descriptor = descriptor;
132             timer_priority = descriptor;
133         }
134         
135     } else {
136         descriptor->prev = NULL;
137         descriptor->next = first_descriptor;
138         if(first_descriptor)
139             first_descriptor->prev = descriptor;
140         first_descriptor = descriptor;
141     }
142 }
143
144 static void iohandler_remove(struct IODescriptor *descriptor, int engine_remove) {
145     //remove IODescriptor from the list
146     if(descriptor->prev)
147         descriptor->prev->next = descriptor->next;
148     else
149         first_descriptor = descriptor->next;
150     if(descriptor->next)
151         descriptor->next->prev = descriptor->prev;
152     if(descriptor == timer_priority)
153         timer_priority = descriptor->next;
154     
155     if(engine_remove)
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));
162     free(descriptor);
163 }
164
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));
168     if(!descriptor) {
169         iohandler_log(IOLOG_ERROR, "could not allocate memory for IODescriptor in %s:%d", __FILE__, __LINE__);
170         return NULL;
171     }
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;
176     if(timeout)
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;
185     }
186     
187     if(!engine) {
188         iohandler_init_engine();
189         if(!engine) {
190             return NULL;
191         }
192     }
193     engine->add(descriptor);
194     
195     //add IODescriptor to the list
196     iohandler_append(descriptor);
197     
198     iohandler_log(IOLOG_DEBUG, "added custom socket descriptor (%d) as type `%s`", sockfd, iohandler_iotype_name(type));
199     return descriptor;
200 }
201
202 void iohandler_set_timeout(struct IODescriptor *descriptor, struct timeval *timeout) {
203     if(descriptor->prev)
204         descriptor->prev->next = descriptor->next;
205     else
206         first_descriptor = descriptor->next;
207     if(descriptor->next)
208         descriptor->next->prev = descriptor->prev;
209     if(descriptor == timer_priority)
210         timer_priority = descriptor->next;
211     if(timeout) 
212         descriptor->timeout = *timeout;
213     else {
214         descriptor->timeout.tv_sec = 0;
215         descriptor->timeout.tv_usec = 0;
216     }
217     iohandler_append(descriptor);
218 }
219
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);
223     if(new_buf) {
224         iobuf->buffer = new_buf;
225         iobuf->buflen = required;
226     }
227 }
228
229 struct IODescriptor *iohandler_timer(struct timeval timeout, iohandler_callback *callback) {
230     struct IODescriptor *descriptor;
231     descriptor = iohandler_add(-1, IOTYPE_TIMER, &timeout, callback);
232     if(!descriptor) {
233         iohandler_log(IOLOG_ERROR, "could not allocate memory for IODescriptor in %s:%d", __FILE__, __LINE__);
234         return NULL;
235     }
236     iohandler_log(IOLOG_DEBUG, "added timer descriptor (sec: %d; usec: %d)", timeout.tv_sec, timeout.tv_usec);
237     return descriptor;
238 }
239
240 struct IODescriptor *iohandler_connect(const char *hostname, unsigned int port, int ssl, const char *bindhost, iohandler_callback *callback) {
241     //non-blocking connect
242     int sockfd, result;
243     struct addrinfo hints, *res;
244     struct sockaddr_in *ip4 = NULL;
245     struct sockaddr_in6 *ip6 = NULL;
246     size_t dstaddrlen;
247     struct sockaddr *dstaddr = NULL;
248     struct IODescriptor *descriptor;
249     
250     if(!engine) {
251         iohandler_init_engine();
252         if(!engine) return NULL;
253     }
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);
260         return NULL;
261     }
262     while (res) {
263         switch (res->ai_family) {
264         case AF_INET:
265             ip4 = (struct sockaddr_in *) res->ai_addr;
266             break;
267         case AF_INET6:
268             ip6 = (struct sockaddr_in6 *) res->ai_addr;
269             break;
270         }
271         res = res->ai_next;
272         freeaddrinfo(res);
273     }
274     
275     if(ip6) {
276         sockfd = socket(AF_INET6, SOCK_STREAM, 0);
277         if(sockfd == -1) {
278             iohandler_log(IOLOG_ERROR, "could not create socket in %s:%d", __FILE__, __LINE__);
279             return NULL;
280         }
281         
282         ip6->sin6_family = AF_INET6;
283         ip6->sin6_port = htons(port);
284         
285         struct sockaddr_in6 *ip6vhost = NULL;
286         if (bindhost && !getaddrinfo(bindhost, NULL, &hints, &res)) {
287             while (res) {
288                 switch (res->ai_family) {
289                 case AF_INET6:
290                     ip6vhost = (struct sockaddr_in6 *) res->ai_addr;
291                     break;
292                 }
293                 res = res->ai_next;
294                 freeaddrinfo(res);
295             }
296         }
297         if(ip6vhost) {
298             ip6vhost->sin6_family = AF_INET6;
299             ip6vhost->sin6_port = htons(0);
300             bind(sockfd, (struct sockaddr*)ip6vhost, sizeof(*ip6vhost));
301         }
302         dstaddr = (struct sockaddr*)ip6;
303         dstaddrlen = sizeof(*ip6);
304     } else if(ip4) {
305         sockfd = socket(AF_INET, SOCK_STREAM, 0);
306         if(sockfd == -1) {
307             iohandler_log(IOLOG_ERROR, "could not create socket in %s:%d", __FILE__, __LINE__);
308             return NULL;
309         }
310         
311         ip4->sin_family = AF_INET;
312         ip4->sin_port = htons(port);
313         
314         struct sockaddr_in *ip4vhost = NULL;
315         if (bindhost && !getaddrinfo(bindhost, NULL, &hints, &res)) {
316             while (res) {
317                 switch (res->ai_family) {
318                 case AF_INET:
319                     ip4vhost = (struct sockaddr_in *) res->ai_addr;
320                     break;
321                 }
322                 res = res->ai_next;
323                 freeaddrinfo(res);
324             }
325         }
326         if(ip4vhost) {
327             ip4vhost->sin_family = AF_INET;
328             ip4vhost->sin_port = htons(0);
329             bind(sockfd, (struct sockaddr*)ip4vhost, sizeof(*ip4vhost));
330         }
331         dstaddr = (struct sockaddr*)ip4;
332         dstaddrlen = sizeof(*ip4);
333     } else
334         return NULL;
335     //make sockfd unblocking
336 #if defined(F_GETFL)
337     {
338         int flags;
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);
343     }
344 #else
345     /* I hope you're using the Win32 backend or something else that
346      * automatically marks the file descriptor non-blocking...
347      */
348 #endif
349     descriptor = iohandler_add(sockfd, IOTYPE_CLIENT, NULL, callback);
350     if(!descriptor) {
351         close(sockfd);
352         return NULL;
353     }
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);
360     return descriptor;
361 }
362
363 struct IODescriptor *iohandler_listen(const char *hostname, unsigned int port, iohandler_callback *callback) {
364     int sockfd;
365     struct addrinfo hints, *res;
366     struct sockaddr_in *ip4 = NULL;
367     struct sockaddr_in6 *ip6 = NULL;
368     struct IODescriptor *descriptor;
369     unsigned int opt;
370     
371     if(!engine) {
372         iohandler_init_engine();
373         if(!engine) return NULL;
374     }
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)) {
380         return NULL;
381     }
382     while (res) {
383         switch (res->ai_family) {
384         case AF_INET:
385             ip4 = (struct sockaddr_in *) res->ai_addr;
386             break;
387         case AF_INET6:
388             ip6 = (struct sockaddr_in6 *) res->ai_addr;
389             break;
390         }
391         res = res->ai_next;
392         freeaddrinfo(res);
393     }
394     
395     if(ip6) {
396         sockfd = socket(AF_INET6, SOCK_STREAM, 0);
397         if(sockfd == -1) return NULL;
398         
399         opt = 1;
400         setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt));
401         
402         ip6->sin6_family = AF_INET6;
403         ip6->sin6_port = htons(port);
404         
405         bind(sockfd, (struct sockaddr*)ip6, sizeof(*ip6));
406     } else if(ip4) {
407         sockfd = socket(AF_INET, SOCK_STREAM, 0);
408         if(sockfd == -1) return NULL;
409         
410         opt = 1;
411         setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt));
412         
413         ip4->sin_family = AF_INET;
414         ip4->sin_port = htons(port);
415         
416         bind(sockfd, (struct sockaddr*)ip4, sizeof(*ip4));
417     } else
418         return NULL;
419     //make sockfd unblocking
420 #if defined(F_GETFL)
421     {
422         int flags;
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);
427     }
428 #else
429     /* I hope you're using the Win32 backend or something else that
430      * automatically marks the file descriptor non-blocking...
431      */
432 #endif
433     descriptor = iohandler_add(sockfd, IOTYPE_SERVER, NULL, callback);
434     if(!descriptor) {
435         close(sockfd);
436         return NULL;
437     }
438     listen(sockfd, 1);
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);
442     return descriptor;
443 }
444
445 void iohandler_write(struct IODescriptor *iofd, const char *line) {
446     size_t linelen = strlen(line);
447     iohandler_send(iofd, line, linelen);
448 }
449
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"));
453         return;
454     }
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));
461             return;
462         }
463     }
464     memcpy(iofd->writebuf.buffer + iofd->writebuf.bufpos, data, datalen);
465     iofd->writebuf.bufpos += datalen;
466     engine->update(iofd);
467 }
468
469 void iohandler_printf(struct IODescriptor *iofd, const char *text, ...) {
470     va_list arg_list;
471     char sendBuf[IO_LINE_LEN];
472     int pos;
473     sendBuf[0] = '\0';
474     va_start(arg_list, text);
475     pos = vsnprintf(sendBuf, IO_LINE_LEN - 2, text, arg_list);
476     va_end(arg_list);
477     if (pos < 0 || pos > (IO_LINE_LEN - 2)) pos = IO_LINE_LEN - 2;
478     sendBuf[pos] = '\n';
479     sendBuf[pos+1] = '\0';
480     iohandler_send(iofd, sendBuf, pos+1);
481 }
482
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);
486     int res;
487     if(iofd->ssl_active)
488         res = iohandler_ssl_write(iofd, iofd->writebuf.buffer, iofd->writebuf.bufpos);
489     else
490         res = send(iofd->fd, iofd->writebuf.buffer, iofd->writebuf.bufpos, 0);
491     if(res < 0) {
492         if (errno != EAGAIN) {
493             iohandler_log(IOLOG_ERROR, "could not write to socket (fd: %d): %d - %s", iofd->fd, errno, strerror(errno));
494         }
495     } else {
496         iofd->writebuf.bufpos -= res;
497         if(iofd->state != IO_CLOSED)
498             engine->update(iofd);
499     }
500 }
501
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
507 #if defined(F_GETFL)
508         {
509             int flags;
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);
514         }
515 #else
516         engine_remove = 0;
517         engine->remove(iofd);
518 #endif
519         iohandler_try_write(iofd);
520     }
521     //close IODescriptor
522     if(iofd->ssl)
523         iohandler_ssl_disconnect(iofd);
524     if(iofd->type == IOTYPE_SERVER || iofd->type == IOTYPE_CLIENT || iofd->type == IOTYPE_STDIN)
525         close(iofd->fd);
526     iohandler_remove(iofd, engine_remove);
527 }
528
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);
532 }
533
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);
538 }
539
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) {
545         case IO_SSLWAIT:
546             if(!readable && !writeable) {
547                 callback_event.type = IOEVENT_SSLFAILED;
548                 iofd->state = IO_CLOSED;
549             } else {
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);
552             }
553             break;
554         case IO_CLOSED:
555             if(iofd->type == IOTYPE_TIMER)
556                 callback_event.type = IOEVENT_TIMEOUT;
557             break;
558         case IO_LISTENING:
559             if(readable) {
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));
563                 } else
564                     callback_event.type = IOEVENT_ACCEPT;
565             }
566             break;
567         case IO_CONNECTING:
568             if(readable) { //could not connect
569                 callback_event.type = IOEVENT_NOTCONNECTED;
570                 //socklen_t arglen;
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);
580                     return;
581                 }
582                 callback_event.type = IOEVENT_CONNECTED;
583                 iofd->state = IO_CONNECTED;
584                 engine->update(iofd);
585             }
586             break;
587         case IO_CONNECTED:
588             if(readable) {
589                 if(iofd->read_lines) {
590                     int bytes;
591                     
592                     if(iofd->ssl_active)
593                         bytes = iohandler_ssl_read(iofd, iofd->readbuf.buffer + iofd->readbuf.bufpos, iofd->readbuf.buflen - iofd->readbuf.bufpos);
594                     else {
595                         if(iofd->type == IOTYPE_STDIN)
596                             #ifdef WIN32
597                             bytes = readable;
598                             #else
599                             bytes = read(iofd->fd, iofd->readbuf.buffer + iofd->readbuf.bufpos, iofd->readbuf.buflen - iofd->readbuf.bufpos);
600                             #endif
601                         else
602                             bytes = recv(iofd->fd, iofd->readbuf.buffer + iofd->readbuf.bufpos, iofd->readbuf.buflen - iofd->readbuf.bufpos, 0);
603                     }
604                     if(bytes <= 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;
610                         }
611                     } else {
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);
623                                 used_bytes = i+1;
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')) {
631                                         break;
632                                     }
633                                 }
634                                 used_bytes = i+1;
635                                 iohandler_trigger_event(&callback_event);
636                             }
637                         }
638                         if(used_bytes) {
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)");
642                             } else {
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;
646                             }
647                         }
648                         callback_event.type = IOEVENT_IGNORE;
649                     }
650                 } else
651                     callback_event.type = IOEVENT_READABLE;
652             }
653             if(writeable) {
654                 iohandler_try_write(iofd);
655             }
656             break;
657     }
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);
662 }
663
664 void iohandler_poll() {
665     if(engine) {
666         struct timeval timeout;
667         timeout.tv_sec = IO_MAX_TIMEOUT;
668         timeout.tv_usec = 0;
669         engine->loop(&timeout);
670     }
671 }
672
673 //debugging functions
674 char *iohandler_iotype_name(enum IOType type) {
675     switch(type) {
676         case IOTYPE_UNKNOWN:
677             return "IOTYPE_UNKNOWN";
678         case IOTYPE_SERVER:
679             return "IOTYPE_SERVER";
680         case IOTYPE_CLIENT:
681             return "IOTYPE_CLIENT";
682         case IOTYPE_STDIN:
683             return "IOTYPE_STDIN";
684         case IOTYPE_TIMER:
685             return "IOTYPE_TIMER";
686         default:
687             return "(UNDEFINED)";
688     }
689 }
690
691 char *iohandler_iostatus_name(enum IOStatus status) {
692     switch(status) {
693         case IO_CLOSED:
694             return "IO_CLOSED";
695         case IO_LISTENING:
696             return "IO_LISTENING";
697         case IO_CONNECTING:
698             return "IO_CONNECTING";
699         case IO_CONNECTED:
700             return "IO_CONNECTED";
701         case IO_SSLWAIT:
702             return "IO_SSLWAIT";
703         default:
704             return "(UNDEFINED)";
705     }
706 }
707
708 char *iohandler_ioeventtype_name(enum IOEventType type) {
709     switch(type) {
710         case IOEVENT_IGNORE:
711             return "IOEVENT_IGNORE";
712         case IOEVENT_READABLE:
713             return "IOEVENT_READABLE";
714         case IOEVENT_RECV:
715             return "IOEVENT_RECV";
716         case IOEVENT_CONNECTED:
717             return "IOEVENT_CONNECTED";
718         case IOEVENT_NOTCONNECTED:
719             return "IOEVENT_NOTCONNECTED";
720         case IOEVENT_CLOSED:
721             return "IOEVENT_CLOSED";
722         case IOEVENT_ACCEPT:
723             return "IOEVENT_ACCEPT";
724         case IOEVENT_TIMEOUT:
725             return "IOEVENT_TIMEOUT";
726         default:
727             return "(UNDEFINED)";
728     }
729 }