Implement asynchroneous networking.
[citadel.git] / citadel / event_client.c
1 /*
2  *
3  * Copyright (c) 1998-2009 by the citadel.org team
4  *
5  *  This program is free software; you can redistribute it and/or modify
6  *  it under the terms of the GNU General Public License as published by
7  *  the Free Software Foundation; either version 3 of the License, or
8  *  (at your option) any later version.
9  *
10  *  This program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *  GNU General Public License for more details.
14  *
15  *  You should have received a copy of the GNU General Public License
16  *  along with this program; if not, write to the Free Software
17  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  */
19
20 #include "sysdep.h"
21 #include <stdlib.h>
22 #include <unistd.h>
23 #include <stdio.h>
24 #include <termios.h>
25 #include <fcntl.h>
26 #include <signal.h>
27 #include <pwd.h>
28 #include <errno.h>
29 #include <sys/types.h>
30 #include <syslog.h>
31
32 #if TIME_WITH_SYS_TIME
33 # include <sys/time.h>
34 # include <time.h>
35 #else
36 # if HAVE_SYS_TIME_H
37 #  include <sys/time.h>
38 # else
39 #  include <time.h>
40 # endif
41 #endif
42 #include <sys/wait.h>
43 #include <ctype.h>
44 #include <string.h>
45 #include <limits.h>
46 #include <sys/socket.h>
47 #include <netinet/in.h>
48 #include <arpa/inet.h>
49 #include <assert.h>
50
51 #include <libcitadel.h>
52 #include "citadel.h"
53 #include "server.h"
54 #include "citserver.h"
55 #include "support.h"
56 #include "config.h"
57 #include "control.h"
58 #include "user_ops.h"
59 #include "database.h"
60 #include "msgbase.h"
61 #include "internet_addressing.h"
62 #include "genstamp.h"
63 #include "domain.h"
64 #include "clientsocket.h"
65 #include "locate_host.h"
66 #include "citadel_dirs.h"
67
68 #include "event_client.h"
69
70 static void IO_abort_shutdown_callback(struct ev_loop *loop, ev_cleanup *watcher, int revents)
71 {
72         syslog(LOG_DEBUG, "EVENT Q: %s\n", __FUNCTION__);
73
74         AsyncIO *IO = watcher->data;
75         assert(IO->ShutdownAbort);
76         IO->ShutdownAbort(IO);
77 }
78
79
80 /*--------------------------------------------------------------------------------
81  * Server DB IO 
82  */
83 extern int evdb_count;
84 extern pthread_mutex_t DBEventQueueMutex;
85 extern HashList *DBInboundEventQueue;
86 extern struct ev_loop *event_db;
87 extern ev_async DBAddJob;   
88 extern ev_async DBExitEventLoop;
89
90 eNextState QueueDBOperation(AsyncIO *IO, IO_CallBack CB)
91 {
92         IOAddHandler *h;
93         int i;
94
95         h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
96         h->IO = IO;
97         h->EvAttch = CB;
98         ev_cleanup_init(&IO->db_abort_by_shutdown, 
99                         IO_abort_shutdown_callback);
100         IO->db_abort_by_shutdown.data = IO;
101         ev_cleanup_start(event_db, &IO->db_abort_by_shutdown);
102
103         pthread_mutex_lock(&DBEventQueueMutex);
104         syslog(LOG_DEBUG, "DBEVENT Q\n");
105         i = ++evdb_count ;
106         Put(DBInboundEventQueue, IKEY(i), h, NULL);
107         pthread_mutex_unlock(&DBEventQueueMutex);
108
109         ev_async_send (event_db, &DBAddJob);
110         syslog(LOG_DEBUG, "DBEVENT Q Done.\n");
111         return eDBQuery;
112 }
113
114 void ShutDownDBCLient(AsyncIO *IO)
115 {
116         CitContext *Ctx =IO->CitContext;
117         become_session(Ctx);
118
119         syslog(LOG_DEBUG, "DBEVENT\n");
120         ev_cleanup_stop(event_db, &IO->db_abort_by_shutdown);
121
122         assert(IO->Terminate);
123         IO->Terminate(IO);      
124
125         Ctx->state = CON_IDLE;
126         Ctx->kill_me = 1;
127 }
128
129 void
130 DB_PerformNext(struct ev_loop *loop, ev_idle *watcher, int revents)
131 {
132         AsyncIO *IO = watcher->data;
133         syslog(LOG_DEBUG, "event: %s\n", __FUNCTION__);
134         become_session(IO->CitContext);
135         
136         ev_idle_stop(event_db, &IO->db_unwind_stack);
137
138         assert(IO->NextDBOperation);
139         switch (IO->NextDBOperation(IO))
140         {
141         case eDBQuery:
142                 break;
143         case eSendDNSQuery:
144         case eReadDNSReply:
145         case eConnect:
146         case eSendReply: 
147         case eSendMore:
148         case eSendFile:
149         case eReadMessage: 
150         case eReadMore:
151         case eReadPayload:
152         case eReadFile:
153                 ev_cleanup_stop(loop, &IO->db_abort_by_shutdown);
154                 break;
155         case eTerminateConnection:
156         case eAbort:
157             ShutDownDBCLient(IO);
158         }
159 }
160
161 eNextState NextDBOperation(AsyncIO *IO, IO_CallBack CB)
162 {
163         IO->NextDBOperation = CB;
164         ev_idle_init(&IO->db_unwind_stack,
165                      DB_PerformNext);
166         IO->db_unwind_stack.data = IO;
167         ev_idle_start(event_db, &IO->db_unwind_stack);
168         return eDBQuery;
169 }
170
171 /*--------------------------------------------------------------------------------
172  * Client IO 
173  */
174 extern int evbase_count;
175 extern pthread_mutex_t EventQueueMutex;
176 extern HashList *InboundEventQueue;
177 extern struct ev_loop *event_base;
178 extern ev_async AddJob;   
179 extern ev_async ExitEventLoop;
180
181
182 eNextState QueueEventContext(AsyncIO *IO, IO_CallBack CB)
183 {
184         IOAddHandler *h;
185         int i;
186
187         h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
188         h->IO = IO;
189         h->EvAttch = CB;
190         ev_cleanup_init(&IO->abort_by_shutdown, 
191                         IO_abort_shutdown_callback);
192         IO->abort_by_shutdown.data = IO;
193         ev_cleanup_start(event_base, &IO->abort_by_shutdown);
194
195         pthread_mutex_lock(&EventQueueMutex);
196         syslog(LOG_DEBUG, "EVENT Q\n");
197         i = ++evbase_count;
198         Put(InboundEventQueue, IKEY(i), h, NULL);
199         pthread_mutex_unlock(&EventQueueMutex);
200
201         ev_async_send (event_base, &AddJob);
202         syslog(LOG_DEBUG, "EVENT Q Done.\n");
203         return eSendReply;
204 }
205
206 int ShutDownEventQueue(void)
207 {
208         pthread_mutex_lock(&DBEventQueueMutex);
209         ev_async_send (event_db, &DBExitEventLoop);
210         pthread_mutex_unlock(&DBEventQueueMutex);
211
212         pthread_mutex_lock(&EventQueueMutex);
213         ev_async_send (EV_DEFAULT_ &ExitEventLoop);
214         pthread_mutex_unlock(&EventQueueMutex);
215         return 0;
216 }
217
218 void FreeAsyncIOContents(AsyncIO *IO)
219 {
220         FreeStrBuf(&IO->IOBuf);
221         FreeStrBuf(&IO->SendBuf.Buf);
222         FreeStrBuf(&IO->RecvBuf.Buf);
223 }
224
225
226 void StopClientWatchers(AsyncIO *IO)
227 {
228         ev_timer_stop(event_base, &IO->conn_fail);
229         ev_io_stop(event_base, &IO->conn_event);
230         ev_idle_stop(event_base, &IO->unwind_stack);
231
232         ev_io_stop(event_base, &IO->send_event);
233         ev_io_stop(event_base, &IO->recv_event);
234         ev_timer_stop (event_base, &IO->rw_timeout);
235         close(IO->SendBuf.fd);
236         IO->SendBuf.fd = 0;
237         IO->RecvBuf.fd = 0;
238 }
239
240 void ShutDownCLient(AsyncIO *IO)
241 {
242         CitContext *Ctx =IO->CitContext;
243         become_session(Ctx);
244
245         syslog(LOG_DEBUG, "EVENT x %d\n", IO->SendBuf.fd);
246
247         ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
248         StopClientWatchers(IO);
249
250         if (IO->DNSChannel != NULL) {
251                 ares_destroy(IO->DNSChannel);
252                 ev_io_stop(event_base, &IO->dns_recv_event);
253                 ev_io_stop(event_base, &IO->dns_send_event);
254                 IO->DNSChannel = NULL;
255         }
256         assert(IO->Terminate);
257         IO->Terminate(IO);
258         Ctx->state = CON_IDLE;
259         Ctx->kill_me = 1;
260 }
261
262
263 eReadState HandleInbound(AsyncIO *IO)
264 {
265         const char *Err = NULL;
266         eReadState Finished = eBufferNotEmpty;
267         
268         become_session(IO->CitContext);
269
270         while ((Finished == eBufferNotEmpty) && 
271                ((IO->NextState == eReadMessage)||
272                 (IO->NextState == eReadMore)||
273                 (IO->NextState == eReadPayload)))
274         {
275                 if (IO->RecvBuf.nBlobBytesWanted != 0) { 
276                                 
277                 }
278                 else { /* Reading lines... */
279 //// lex line reply in callback, or do it ourselves. as nnn-blabla means continue reading in SMTP
280                         if (IO->LineReader)
281                                 Finished = IO->LineReader(IO);
282                         else 
283                                 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
284                                 
285                         switch (Finished) {
286                         case eMustReadMore: /// read new from socket... 
287                                 break;
288                         case eBufferNotEmpty: /* shouldn't happen... */
289                         case eReadSuccess: /// done for now...
290                                 break;
291                         case eReadFail: /// WHUT?
292                                 ///todo: shut down! 
293                                 break;
294                         }
295                                         
296                 }
297                         
298                 if (Finished != eMustReadMore) {
299                         assert(IO->ReadDone);
300                         ev_io_stop(event_base, &IO->recv_event);
301                         IO->NextState = IO->ReadDone(IO);
302                         Finished = StrBufCheckBuffer(&IO->RecvBuf);
303                         if ((IO->NextState == eReadFile) && 
304                             (Finished == eBufferNotEmpty))
305                         {
306                                 Finished = WriteIOBAlreadyRead(&IO->IOB, &Err);
307                                 if (Finished == eReadSuccess)
308                                 {
309                                         IO->NextState = eSendReply;                             
310                                 }
311                         }
312                 }
313         }
314
315         switch (IO->NextState) {
316         case eSendFile:
317                 ev_io_start(event_base, &IO->send_event);
318                 break;
319         case eSendReply:
320         case eSendMore:
321                 assert(IO->SendDone);
322                 IO->NextState = IO->SendDone(IO);
323                 ev_io_start(event_base, &IO->send_event);
324                 break;
325         case eReadPayload:
326         case eReadMore:
327         case eReadFile:
328                 ev_io_start(event_base, &IO->recv_event);
329                 break;
330         case eTerminateConnection:
331 //////TODOxxxx
332                 break;
333         case eAbort:
334                 ShutDownCLient(IO);
335                 break;
336         case eSendDNSQuery:
337         case eReadDNSReply:
338         case eDBQuery:
339         case eConnect:
340         case eReadMessage:
341                 break;
342         }
343         return Finished;
344 }
345
346
347 static void
348 IO_send_callback(struct ev_loop *loop, ev_io *watcher, int revents)
349 {
350         int rc;
351         AsyncIO *IO = watcher->data;
352         const char *errmsg = NULL;
353
354         become_session(IO->CitContext);
355 #ifdef BIGBAD_IODBG
356         {
357                 int rv = 0;
358                 char fn [SIZ];
359                 FILE *fd;
360                 const char *pch = ChrPtr(IO->SendBuf.Buf);
361                 const char *pchh = IO->SendBuf.ReadWritePointer;
362                 long nbytes;
363                 
364                 if (pchh == NULL)
365                         pchh = pch;
366                 
367                 nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
368                 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
369                          ((CitContext*)(IO->CitContext))->ServiceName,
370                          IO->SendBuf.fd);
371                 
372                 fd = fopen(fn, "a+");
373                 fprintf(fd, "Send: BufSize: %ld BufContent: [",
374                         nbytes);
375                 rv = fwrite(pchh, nbytes, 1, fd);
376                 if (!rv) printf("failed to write debug to %s!\n", fn);
377                 fprintf(fd, "]\n");
378 #endif
379                 switch (IO->NextState) {
380                 case eSendFile:
381                         rc = FileSendChunked(&IO->IOB, &errmsg);
382                         if (rc < 0)
383                                 StrBufPlain(IO->ErrMsg, errmsg, -1);
384                         break;
385                 default:
386                         rc = StrBuf_write_one_chunk_callback(watcher->fd, 0/*TODO*/, &IO->SendBuf);
387                 }
388
389 #ifdef BIGBAD_IODBG
390                 fprintf(fd, "Sent: BufSize: %d bytes.\n", rc);
391                 fclose(fd);
392         }
393 #endif
394         if (rc == 0)
395         {
396                 ev_io_stop(event_base, &IO->send_event);
397                 switch (IO->NextState) {
398                 case eSendMore:
399                         assert(IO->SendDone);
400                         IO->NextState = IO->SendDone(IO);
401
402                         if ((IO->NextState == eTerminateConnection) ||
403                             (IO->NextState == eAbort) )
404                                 ShutDownCLient(IO);
405                         else {
406                                 ev_io_start(event_base, &IO->send_event);
407                         }
408                         break;
409                 case eSendFile:
410                         if (IO->IOB.ChunkSendRemain > 0) {
411                                 ev_io_start(event_base, &IO->recv_event);
412                         } else {
413                                 assert(IO->ReadDone);
414                                 IO->NextState = IO->ReadDone(IO);
415                                 switch(IO->NextState) {
416                                 case eSendDNSQuery:
417                                 case eReadDNSReply:
418                                 case eDBQuery:
419                                 case eConnect:
420                                         break;
421                                 case eSendReply: 
422                                 case eSendMore:
423                                 case eSendFile:
424                                         ev_io_start(event_base, &IO->send_event);
425                                         break;
426                                 case eReadMessage: 
427                                 case eReadMore:
428                                 case eReadPayload:
429                                 case eReadFile:
430                                         break;
431                                 case eTerminateConnection:
432                                 case eAbort:
433                                         break;
434                                 }
435                         }
436                         break;
437                 case eSendReply:
438                     if (StrBufCheckBuffer(&IO->SendBuf) != eReadSuccess) 
439                         break;
440                     IO->NextState = eReadMore;
441                 case eReadMore:
442                 case eReadMessage:
443                 case eReadPayload:
444                 case eReadFile:
445                         if (StrBufCheckBuffer(&IO->RecvBuf) == eBufferNotEmpty) {
446                                 HandleInbound(IO);
447                         }
448                         else {
449                                 ev_io_start(event_base, &IO->recv_event);
450                         }
451
452                         break;
453                 case eDBQuery:
454                         /* we now live in another queue, so we have to unregister. */
455                         ev_cleanup_stop(loop, &IO->abort_by_shutdown);
456                         break;
457                 case eSendDNSQuery:
458                 case eReadDNSReply:
459                 case eConnect:
460                 case eTerminateConnection:
461                 case eAbort:
462                         break;
463                 }
464         }
465         else if (rc < 0) {
466                 assert(IO->Timeout);
467                 IO->Timeout(IO);
468         }
469         /* else : must write more. */
470 }
471 static void
472 set_start_callback(struct ev_loop *loop, AsyncIO *IO, int revents)
473 {
474         
475         switch(IO->NextState) {
476         case eReadMore:
477         case eReadMessage:
478         case eReadFile:
479                 ev_io_start(event_base, &IO->recv_event);
480                 break;
481         case eSendReply:
482         case eSendMore:
483         case eReadPayload:
484         case eSendFile:
485                 become_session(IO->CitContext);
486                 IO_send_callback(loop, &IO->send_event, revents);
487                 break;
488         case eDBQuery:
489         case eSendDNSQuery:
490         case eReadDNSReply:
491         case eConnect:
492         case eTerminateConnection:
493         case eAbort:
494                 /// TODO: WHUT?
495                 break;
496         }
497 }
498
499 static void
500 IO_Timeout_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
501 {
502         AsyncIO *IO = watcher->data;
503
504         ev_timer_stop (event_base, &IO->rw_timeout);
505         become_session(IO->CitContext);
506
507         if (IO->SendBuf.fd != 0)
508         {
509                 ev_io_stop(event_base, &IO->send_event);
510                 ev_io_stop(event_base, &IO->recv_event);
511                 ev_timer_stop (event_base, &IO->rw_timeout);
512                 close(IO->SendBuf.fd);
513                 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
514         }
515
516         assert(IO->Timeout);
517         switch (IO->Timeout(IO))
518         {
519         case eAbort:
520                 ShutDownCLient(IO);
521         default:
522                 break;
523         }
524 }
525
526 static void
527 IO_connfail_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
528 {
529         AsyncIO *IO = watcher->data;
530
531         ev_timer_stop (event_base, &IO->conn_fail);
532
533         if (IO->SendBuf.fd != 0)
534         {
535                 ev_io_stop(loop, &IO->conn_event);
536                 ev_io_stop(event_base, &IO->send_event);
537                 ev_io_stop(event_base, &IO->recv_event);
538                 ev_timer_stop (event_base, &IO->rw_timeout);
539                 close(IO->SendBuf.fd);
540                 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
541         }
542         become_session(IO->CitContext);
543
544         assert(IO->ConnFail);
545         switch (IO->ConnFail(IO))
546         {
547         case eAbort:
548                 ShutDownCLient(IO);
549         default:
550                 break;
551
552         }
553 }
554
555 static void
556 IO_connfailimmediate_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
557 {
558         AsyncIO *IO = watcher->data;
559
560         ev_idle_stop (event_base, &IO->conn_fail_immediate);
561
562         if (IO->SendBuf.fd != 0)
563         {
564                 close(IO->SendBuf.fd);
565                 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
566         }
567         become_session(IO->CitContext);
568
569         assert(IO->ConnFail);
570         switch (IO->ConnFail(IO))
571         {
572         case eAbort:
573                 ShutDownCLient(IO);
574         default:
575                 break;
576
577         }
578 }
579
580 static void
581 IO_connestd_callback(struct ev_loop *loop, ev_io *watcher, int revents)
582 {
583         AsyncIO *IO = watcher->data;
584
585         ev_io_stop(loop, &IO->conn_event);
586         ev_timer_stop (event_base, &IO->conn_fail);
587         set_start_callback(loop, IO, revents);
588 }
589 static void
590 IO_recv_callback(struct ev_loop *loop, ev_io *watcher, int revents)
591 {
592         const char *errmsg;
593         long rc;
594         ssize_t nbytes;
595         AsyncIO *IO = watcher->data;
596
597         switch (IO->NextState) {
598         case eReadFile:
599                 rc = FileRecvChunked(&IO->IOB, &errmsg);
600                 if (rc < 0)
601                         StrBufPlain(IO->ErrMsg, errmsg, -1);
602                 break;
603         default:
604                 nbytes = StrBuf_read_one_chunk_callback(watcher->fd, 0 /*TODO */, &IO->RecvBuf);
605                 break;
606         }
607 #ifdef BIGBAD_IODBG
608         {
609                 int rv = 0;
610                 char fn [SIZ];
611                 FILE *fd;
612                 const char *pch = ChrPtr(IO->RecvBuf.Buf);
613                 const char *pchh = IO->RecvBuf.ReadWritePointer;
614                 long nbytes;
615                 
616                 if (pchh == NULL)
617                         pchh = pch;
618                 
619                 nbytes = StrLength(IO->RecvBuf.Buf) - (pchh - pch);
620                 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
621                          ((CitContext*)(IO->CitContext))->ServiceName, 
622                          IO->SendBuf.fd);
623                 
624                 fd = fopen(fn, "a+");
625                 fprintf(fd, "Read: BufSize: %ld BufContent: [",
626                         nbytes);
627                 rv = fwrite(pchh, nbytes, 1, fd);
628                 if (!rv) printf("failed to write debug to %s!\n", fn);
629                 fprintf(fd, "]\n");
630                 
631                 
632                 fclose(fd);
633         }
634 #endif
635         if (nbytes > 0) {
636                 HandleInbound(IO);
637         } else if (nbytes == 0) {
638                 assert(IO->Timeout);
639
640                 switch (IO->Timeout(IO))
641                 {
642                 case eAbort:
643                         ShutDownCLient(IO);
644                 default:
645                         break;
646                 }
647                 return;
648         } else if (nbytes == -1) {
649 /// TODO: FD is gone. kick it.        sock_buff_invoke_free(sb, errno);
650                 syslog(LOG_DEBUG, 
651                        "EVENT: Socket Invalid! %s \n",
652                        strerror(errno));
653                 return;
654         }
655 }
656
657 void
658 IO_postdns_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
659 {
660         AsyncIO *IO = watcher->data;
661         syslog(LOG_DEBUG, "event: %s\n", __FUNCTION__);
662         become_session(IO->CitContext);
663         assert(IO->DNSFail);
664         switch (IO->DNSQuery->PostDNS(IO))
665         {
666         case eAbort:
667                 IO->DNSFail(IO);
668         default:
669             break;
670         }
671 }
672
673 eNextState event_connect_socket(AsyncIO *IO, double conn_timeout, double first_rw_timeout)
674 {
675         int fdflags; 
676         int rc = -1;
677
678         IO->SendBuf.fd = IO->RecvBuf.fd = 
679                 socket(
680                         (IO->ConnectMe->IPv6)?PF_INET6:PF_INET, 
681                         SOCK_STREAM, 
682                         IPPROTO_TCP);
683
684         if (IO->SendBuf.fd < 0) {
685                 syslog(LOG_ERR, "EVENT: socket() failed: %s\n", strerror(errno));
686                 StrBufPrintf(IO->ErrMsg, "Failed to create socket: %s", strerror(errno));
687                 return eAbort;
688         }
689         fdflags = fcntl(IO->SendBuf.fd, F_GETFL);
690         if (fdflags < 0) {
691                 syslog(LOG_DEBUG, 
692                        "EVENT: unable to get socket flags! %s \n",
693                        strerror(errno));
694                 StrBufPrintf(IO->ErrMsg, "Failed to get socket flags: %s", strerror(errno));
695                 return eAbort;
696         }
697         fdflags = fdflags | O_NONBLOCK;
698         if (fcntl(IO->SendBuf.fd, F_SETFL, fdflags) < 0) {
699                 syslog(LOG_DEBUG, 
700                        "EVENT: unable to set socket nonblocking flags! %s \n",
701                        strerror(errno));
702                 StrBufPrintf(IO->ErrMsg, "Failed to set socket flags: %s", strerror(errno));
703                 close(IO->SendBuf.fd);
704                 IO->SendBuf.fd = IO->RecvBuf.fd = -1;
705                 return eAbort;
706         }
707 /* TODO: maye we could use offsetof() to calc the position of data... 
708  * http://doc.dvgu.ru/devel/ev.html#associating_custom_data_with_a_watcher
709  */
710         ev_io_init(&IO->recv_event, IO_recv_callback, IO->RecvBuf.fd, EV_READ);
711         IO->recv_event.data = IO;
712         ev_io_init(&IO->send_event, IO_send_callback, IO->SendBuf.fd, EV_WRITE);
713         IO->send_event.data = IO;
714
715         ev_timer_init(&IO->conn_fail, IO_connfail_callback, conn_timeout, 0);
716         IO->conn_fail.data = IO;
717         ev_timer_init(&IO->rw_timeout, IO_Timeout_callback, first_rw_timeout, 0);
718         IO->rw_timeout.data = IO;
719
720
721         /*  Bypass it like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
722 ///     ((struct sockaddr_in)IO->ConnectMe->Addr).sin_addr.s_addr = inet_addr("127.0.0.1");
723         if (IO->ConnectMe->IPv6)
724                 rc = connect(IO->SendBuf.fd, &IO->ConnectMe->Addr, sizeof(struct sockaddr_in6));
725         else
726                 rc = connect(IO->SendBuf.fd, (struct sockaddr_in *)&IO->ConnectMe->Addr, sizeof(struct sockaddr_in));
727
728         if (rc >= 0){
729                 syslog(LOG_DEBUG, "connect() immediate success.\n");
730                 set_start_callback(event_base, IO, 0);
731                 ev_timer_start(event_base, &IO->rw_timeout);
732                 return IO->NextState;
733         }
734         else if (errno == EINPROGRESS) {
735                 syslog(LOG_DEBUG, "connect() have to wait now.\n");
736
737                 ev_io_init(&IO->conn_event, IO_connestd_callback, IO->SendBuf.fd, EV_READ|EV_WRITE);
738                 IO->conn_event.data = IO;
739
740                 ev_io_start(event_base, &IO->conn_event);
741                 ev_timer_start(event_base, &IO->conn_fail);
742                 return IO->NextState;
743         }
744         else {
745                 ev_idle_init(&IO->conn_fail_immediate,
746                              IO_connfailimmediate_callback);
747                 IO->conn_fail_immediate.data = IO;
748                 ev_idle_start(event_base, &IO->conn_fail_immediate);
749                 
750                 syslog(LOG_ERR, "connect() failed: %s\n", strerror(errno));
751                 StrBufPrintf(IO->ErrMsg, "Failed to connect: %s", strerror(errno));
752                 return IO->NextState;
753         }
754         return IO->NextState;
755 }
756
757 void SetNextTimeout(AsyncIO *IO, double timeout)
758 {
759         IO->rw_timeout.repeat = timeout;
760         ev_timer_again (event_base,  &IO->rw_timeout);
761 }
762
763 eNextState InitEventIO(AsyncIO *IO, 
764                        void *pData, 
765                        double conn_timeout, 
766                        double first_rw_timeout,
767                        int ReadFirst)
768 {
769         IO->Data = pData;
770         become_session(IO->CitContext);
771         
772         if (ReadFirst) {
773                 IO->NextState = eReadMessage;
774         }
775         else {
776                 IO->NextState = eSendReply;
777         }
778         return event_connect_socket(IO, conn_timeout, first_rw_timeout);
779 }
780
781 eNextState ReAttachIO(AsyncIO *IO, 
782                       void *pData, 
783                       int ReadFirst)
784 {
785         IO->Data = pData;
786         become_session(IO->CitContext);
787         ev_cleanup_start(event_base, &IO->abort_by_shutdown);
788         if (ReadFirst) {
789                 IO->NextState = eReadMessage;
790         }
791         else {
792                 IO->NextState = eSendReply;
793         }
794         set_start_callback(event_base, IO, 0);
795
796         return IO->NextState;
797 }