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