remove debug output.
[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 == eReadFile)||
274                 (IO->NextState == eReadPayload)))
275         {
276                 if (IO->RecvBuf.nBlobBytesWanted != 0) { 
277                                 
278                 }
279                 else { /* Reading lines... */
280 //// lex line reply in callback, or do it ourselves. as nnn-blabla means continue reading in SMTP
281                         if ((IO->NextState == eReadFile) && 
282                             (Finished == eBufferNotEmpty))
283                         {
284                                 Finished = WriteIOBAlreadyRead(&IO->IOB, &Err);
285                                 if (Finished == eReadSuccess)
286                                 {
287                                         IO->NextState = eSendReply;                             
288                                 }
289                         }
290                         else if (IO->LineReader)
291                                 Finished = IO->LineReader(IO);
292                         else 
293                                 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
294                                 
295                         switch (Finished) {
296                         case eMustReadMore: /// read new from socket... 
297                                 break;
298                         case eBufferNotEmpty: /* shouldn't happen... */
299                         case eReadSuccess: /// done for now...
300                                 break;
301                         case eReadFail: /// WHUT?
302                                 ///todo: shut down! 
303                                 break;
304                         }
305                                         
306                 }
307                         
308                 if (Finished != eMustReadMore) {
309                         assert(IO->ReadDone);
310                         ev_io_stop(event_base, &IO->recv_event);
311                         IO->NextState = IO->ReadDone(IO);
312                         Finished = StrBufCheckBuffer(&IO->RecvBuf);
313                 }
314         }
315
316         switch (IO->NextState) {
317         case eSendFile:
318                 ev_io_start(event_base, &IO->send_event);
319                 break;
320         case eSendReply:
321         case eSendMore:
322                 assert(IO->SendDone);
323                 IO->NextState = IO->SendDone(IO);
324                 ev_io_start(event_base, &IO->send_event);
325                 break;
326         case eReadPayload:
327         case eReadMore:
328         case eReadFile:
329                 ev_io_start(event_base, &IO->recv_event);
330                 break;
331         case eTerminateConnection:
332 //////TODOxxxx
333                 break;
334         case eAbort:
335                 ShutDownCLient(IO);
336                 break;
337         case eSendDNSQuery:
338         case eReadDNSReply:
339         case eDBQuery:
340         case eConnect:
341         case eReadMessage:
342                 break;
343         }
344         return Finished;
345 }
346
347
348 static void
349 IO_send_callback(struct ev_loop *loop, ev_io *watcher, int revents)
350 {
351         int rc;
352         AsyncIO *IO = watcher->data;
353         const char *errmsg = NULL;
354
355         become_session(IO->CitContext);
356 #ifdef BIGBAD_IODBG
357         {
358                 int rv = 0;
359                 char fn [SIZ];
360                 FILE *fd;
361                 const char *pch = ChrPtr(IO->SendBuf.Buf);
362                 const char *pchh = IO->SendBuf.ReadWritePointer;
363                 long nbytes;
364                 
365                 if (pchh == NULL)
366                         pchh = pch;
367                 
368                 nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
369                 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
370                          ((CitContext*)(IO->CitContext))->ServiceName,
371                          IO->SendBuf.fd);
372                 
373                 fd = fopen(fn, "a+");
374                 fprintf(fd, "Send: BufSize: %ld BufContent: [",
375                         nbytes);
376                 rv = fwrite(pchh, nbytes, 1, fd);
377                 if (!rv) printf("failed to write debug to %s!\n", fn);
378                 fprintf(fd, "]\n");
379 #endif
380                 switch (IO->NextState) {
381                 case eSendFile:
382                         rc = FileSendChunked(&IO->IOB, &errmsg);
383                         if (rc < 0)
384                                 StrBufPlain(IO->ErrMsg, errmsg, -1);
385                         break;
386                 default:
387                         rc = StrBuf_write_one_chunk_callback(watcher->fd, 0/*TODO*/, &IO->SendBuf);
388                 }
389
390 #ifdef BIGBAD_IODBG
391                 fprintf(fd, "Sent: BufSize: %d bytes.\n", rc);
392                 fclose(fd);
393         }
394 #endif
395         if (rc == 0)
396         {
397                 ev_io_stop(event_base, &IO->send_event);
398                 switch (IO->NextState) {
399                 case eSendMore:
400                         assert(IO->SendDone);
401                         IO->NextState = IO->SendDone(IO);
402
403                         if ((IO->NextState == eTerminateConnection) ||
404                             (IO->NextState == eAbort) )
405                                 ShutDownCLient(IO);
406                         else {
407                                 ev_io_start(event_base, &IO->send_event);
408                         }
409                         break;
410                 case eSendFile:
411                         if (IO->IOB.ChunkSendRemain > 0) {
412                                 ev_io_start(event_base, &IO->recv_event);
413                         } else {
414                                 assert(IO->ReadDone);
415                                 IO->NextState = IO->ReadDone(IO);
416                                 switch(IO->NextState) {
417                                 case eSendDNSQuery:
418                                 case eReadDNSReply:
419                                 case eDBQuery:
420                                 case eConnect:
421                                         break;
422                                 case eSendReply: 
423                                 case eSendMore:
424                                 case eSendFile:
425                                         ev_io_start(event_base, &IO->send_event);
426                                         break;
427                                 case eReadMessage: 
428                                 case eReadMore:
429                                 case eReadPayload:
430                                 case eReadFile:
431                                         break;
432                                 case eTerminateConnection:
433                                 case eAbort:
434                                         break;
435                                 }
436                         }
437                         break;
438                 case eSendReply:
439                     if (StrBufCheckBuffer(&IO->SendBuf) != eReadSuccess) 
440                         break;
441                     IO->NextState = eReadMore;
442                 case eReadMore:
443                 case eReadMessage:
444                 case eReadPayload:
445                 case eReadFile:
446                         if (StrBufCheckBuffer(&IO->RecvBuf) == eBufferNotEmpty) {
447                                 HandleInbound(IO);
448                         }
449                         else {
450                                 ev_io_start(event_base, &IO->recv_event);
451                         }
452
453                         break;
454                 case eDBQuery:
455                         /* we now live in another queue, so we have to unregister. */
456                         ev_cleanup_stop(loop, &IO->abort_by_shutdown);
457                         break;
458                 case eSendDNSQuery:
459                 case eReadDNSReply:
460                 case eConnect:
461                 case eTerminateConnection:
462                 case eAbort:
463                         break;
464                 }
465         }
466         else if (rc < 0) {
467                 assert(IO->Timeout);
468                 IO->Timeout(IO);
469         }
470         /* else : must write more. */
471 }
472 static void
473 set_start_callback(struct ev_loop *loop, AsyncIO *IO, int revents)
474 {
475         
476         switch(IO->NextState) {
477         case eReadMore:
478         case eReadMessage:
479         case eReadFile:
480                 ev_io_start(event_base, &IO->recv_event);
481                 break;
482         case eSendReply:
483         case eSendMore:
484         case eReadPayload:
485         case eSendFile:
486                 become_session(IO->CitContext);
487                 IO_send_callback(loop, &IO->send_event, revents);
488                 break;
489         case eDBQuery:
490         case eSendDNSQuery:
491         case eReadDNSReply:
492         case eConnect:
493         case eTerminateConnection:
494         case eAbort:
495                 /// TODO: WHUT?
496                 break;
497         }
498 }
499
500 static void
501 IO_Timeout_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
502 {
503         AsyncIO *IO = watcher->data;
504
505         ev_timer_stop (event_base, &IO->rw_timeout);
506         become_session(IO->CitContext);
507
508         if (IO->SendBuf.fd != 0)
509         {
510                 ev_io_stop(event_base, &IO->send_event);
511                 ev_io_stop(event_base, &IO->recv_event);
512                 ev_timer_stop (event_base, &IO->rw_timeout);
513                 close(IO->SendBuf.fd);
514                 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
515         }
516
517         assert(IO->Timeout);
518         switch (IO->Timeout(IO))
519         {
520         case eAbort:
521                 ShutDownCLient(IO);
522         default:
523                 break;
524         }
525 }
526
527 static void
528 IO_connfail_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
529 {
530         AsyncIO *IO = watcher->data;
531
532         ev_timer_stop (event_base, &IO->conn_fail);
533
534         if (IO->SendBuf.fd != 0)
535         {
536                 ev_io_stop(loop, &IO->conn_event);
537                 ev_io_stop(event_base, &IO->send_event);
538                 ev_io_stop(event_base, &IO->recv_event);
539                 ev_timer_stop (event_base, &IO->rw_timeout);
540                 close(IO->SendBuf.fd);
541                 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
542         }
543         become_session(IO->CitContext);
544
545         assert(IO->ConnFail);
546         switch (IO->ConnFail(IO))
547         {
548         case eAbort:
549                 ShutDownCLient(IO);
550         default:
551                 break;
552
553         }
554 }
555
556 static void
557 IO_connfailimmediate_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
558 {
559         AsyncIO *IO = watcher->data;
560
561         ev_idle_stop (event_base, &IO->conn_fail_immediate);
562
563         if (IO->SendBuf.fd != 0)
564         {
565                 close(IO->SendBuf.fd);
566                 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
567         }
568         become_session(IO->CitContext);
569
570         assert(IO->ConnFail);
571         switch (IO->ConnFail(IO))
572         {
573         case eAbort:
574                 ShutDownCLient(IO);
575         default:
576                 break;
577
578         }
579 }
580
581 static void
582 IO_connestd_callback(struct ev_loop *loop, ev_io *watcher, int revents)
583 {
584         AsyncIO *IO = watcher->data;
585
586         ev_io_stop(loop, &IO->conn_event);
587         ev_timer_stop (event_base, &IO->conn_fail);
588         set_start_callback(loop, IO, revents);
589 }
590 static void
591 IO_recv_callback(struct ev_loop *loop, ev_io *watcher, int revents)
592 {
593         const char *errmsg;
594         ssize_t nbytes;
595         AsyncIO *IO = watcher->data;
596
597         switch (IO->NextState) {
598         case eReadFile:
599                 nbytes = FileRecvChunked(&IO->IOB, &errmsg);
600                 if (nbytes < 0)
601                         StrBufPlain(IO->ErrMsg, errmsg, -1);
602                 else 
603                 {
604                         if (IO->IOB.ChunkSendRemain == 0)
605                         {
606                                 IO->NextState = eSendReply;
607                         }
608                         else
609                                 return;
610                 }
611                 break;
612         default:
613                 nbytes = StrBuf_read_one_chunk_callback(watcher->fd, 0 /*TODO */, &IO->RecvBuf);
614                 break;
615         }
616
617 #ifdef BIGBAD_IODBG
618         {
619                 int rv = 0;
620                 char fn [SIZ];
621                 FILE *fd;
622                 const char *pch = ChrPtr(IO->RecvBuf.Buf);
623                 const char *pchh = IO->RecvBuf.ReadWritePointer;
624                 long nbytes;
625                 
626                 if (pchh == NULL)
627                         pchh = pch;
628                 
629                 nbytes = StrLength(IO->RecvBuf.Buf) - (pchh - pch);
630                 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
631                          ((CitContext*)(IO->CitContext))->ServiceName, 
632                          IO->SendBuf.fd);
633                 
634                 fd = fopen(fn, "a+");
635                 fprintf(fd, "Read: BufSize: %ld BufContent: [",
636                         nbytes);
637                 rv = fwrite(pchh, nbytes, 1, fd);
638                 if (!rv) printf("failed to write debug to %s!\n", fn);
639                 fprintf(fd, "]\n");
640                 
641                 
642                 fclose(fd);
643         }
644 #endif
645         if (nbytes > 0) {
646                 HandleInbound(IO);
647         } else if (nbytes == 0) {
648                 assert(IO->Timeout);
649
650                 switch (IO->Timeout(IO))
651                 {
652                 case eAbort:
653                         ShutDownCLient(IO);
654                 default:
655                         break;
656                 }
657                 return;
658         } else if (nbytes == -1) {
659 /// TODO: FD is gone. kick it.        sock_buff_invoke_free(sb, errno);
660                 syslog(LOG_DEBUG, 
661                        "EVENT: Socket Invalid! %s \n",
662                        strerror(errno));
663                 ShutDownCLient(IO);
664                 return;
665         }
666 }
667
668 void
669 IO_postdns_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
670 {
671         AsyncIO *IO = watcher->data;
672         syslog(LOG_DEBUG, "event: %s\n", __FUNCTION__);
673         become_session(IO->CitContext);
674         assert(IO->DNSFail);
675         assert(IO->DNSQuery->PostDNS);
676         switch (IO->DNSQuery->PostDNS(IO))
677         {
678         case eAbort:
679                 IO->DNSFail(IO);
680         default:
681             break;
682         }
683 }
684
685 eNextState event_connect_socket(AsyncIO *IO, double conn_timeout, double first_rw_timeout)
686 {
687         int fdflags; 
688         int rc = -1;
689
690         IO->SendBuf.fd = IO->RecvBuf.fd = 
691                 socket(
692                         (IO->ConnectMe->IPv6)?PF_INET6:PF_INET, 
693                         SOCK_STREAM, 
694                         IPPROTO_TCP);
695
696         if (IO->SendBuf.fd < 0) {
697                 syslog(LOG_ERR, "EVENT: socket() failed: %s\n", strerror(errno));
698                 StrBufPrintf(IO->ErrMsg, "Failed to create socket: %s", strerror(errno));
699                 return eAbort;
700         }
701         fdflags = fcntl(IO->SendBuf.fd, F_GETFL);
702         if (fdflags < 0) {
703                 syslog(LOG_DEBUG, 
704                        "EVENT: unable to get socket flags! %s \n",
705                        strerror(errno));
706                 StrBufPrintf(IO->ErrMsg, "Failed to get socket flags: %s", strerror(errno));
707                 return eAbort;
708         }
709         fdflags = fdflags | O_NONBLOCK;
710         if (fcntl(IO->SendBuf.fd, F_SETFL, fdflags) < 0) {
711                 syslog(LOG_DEBUG, 
712                        "EVENT: unable to set socket nonblocking flags! %s \n",
713                        strerror(errno));
714                 StrBufPrintf(IO->ErrMsg, "Failed to set socket flags: %s", strerror(errno));
715                 close(IO->SendBuf.fd);
716                 IO->SendBuf.fd = IO->RecvBuf.fd = -1;
717                 return eAbort;
718         }
719 /* TODO: maye we could use offsetof() to calc the position of data... 
720  * http://doc.dvgu.ru/devel/ev.html#associating_custom_data_with_a_watcher
721  */
722         ev_io_init(&IO->recv_event, IO_recv_callback, IO->RecvBuf.fd, EV_READ);
723         IO->recv_event.data = IO;
724         ev_io_init(&IO->send_event, IO_send_callback, IO->SendBuf.fd, EV_WRITE);
725         IO->send_event.data = IO;
726
727         ev_timer_init(&IO->conn_fail, IO_connfail_callback, conn_timeout, 0);
728         IO->conn_fail.data = IO;
729         ev_timer_init(&IO->rw_timeout, IO_Timeout_callback, first_rw_timeout, 0);
730         IO->rw_timeout.data = IO;
731
732
733         /*  Bypass it like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
734 ///     ((struct sockaddr_in)IO->ConnectMe->Addr).sin_addr.s_addr = inet_addr("127.0.0.1");
735         if (IO->ConnectMe->IPv6)
736                 rc = connect(IO->SendBuf.fd, &IO->ConnectMe->Addr, sizeof(struct sockaddr_in6));
737         else
738                 rc = connect(IO->SendBuf.fd, (struct sockaddr_in *)&IO->ConnectMe->Addr, sizeof(struct sockaddr_in));
739
740         if (rc >= 0){
741                 syslog(LOG_DEBUG, "connect() immediate success.\n");
742                 set_start_callback(event_base, IO, 0);
743                 ev_timer_start(event_base, &IO->rw_timeout);
744                 return IO->NextState;
745         }
746         else if (errno == EINPROGRESS) {
747                 syslog(LOG_DEBUG, "connect() have to wait now.\n");
748
749                 ev_io_init(&IO->conn_event, IO_connestd_callback, IO->SendBuf.fd, EV_READ|EV_WRITE);
750                 IO->conn_event.data = IO;
751
752                 ev_io_start(event_base, &IO->conn_event);
753                 ev_timer_start(event_base, &IO->conn_fail);
754                 return IO->NextState;
755         }
756         else {
757                 ev_idle_init(&IO->conn_fail_immediate,
758                              IO_connfailimmediate_callback);
759                 IO->conn_fail_immediate.data = IO;
760                 ev_idle_start(event_base, &IO->conn_fail_immediate);
761                 
762                 syslog(LOG_ERR, "connect() failed: %s\n", strerror(errno));
763                 StrBufPrintf(IO->ErrMsg, "Failed to connect: %s", strerror(errno));
764                 return IO->NextState;
765         }
766         return IO->NextState;
767 }
768
769 void SetNextTimeout(AsyncIO *IO, double timeout)
770 {
771         IO->rw_timeout.repeat = timeout;
772         ev_timer_again (event_base,  &IO->rw_timeout);
773 }
774
775 eNextState InitEventIO(AsyncIO *IO, 
776                        void *pData, 
777                        double conn_timeout, 
778                        double first_rw_timeout,
779                        int ReadFirst)
780 {
781         IO->Data = pData;
782         become_session(IO->CitContext);
783         
784         if (ReadFirst) {
785                 IO->NextState = eReadMessage;
786         }
787         else {
788                 IO->NextState = eSendReply;
789         }
790         return event_connect_socket(IO, conn_timeout, first_rw_timeout);
791 }
792
793 eNextState ReAttachIO(AsyncIO *IO, 
794                       void *pData, 
795                       int ReadFirst)
796 {
797         IO->Data = pData;
798         become_session(IO->CitContext);
799         ev_cleanup_start(event_base, &IO->abort_by_shutdown);
800         if (ReadFirst) {
801                 IO->NextState = eReadMessage;
802         }
803         else {
804                 IO->NextState = eSendReply;
805         }
806         set_start_callback(event_base, IO, 0);
807
808         return IO->NextState;
809 }