Finalize Networker; native modern linux.
[citadel] / 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                 syslog(LOG_DEBUG, "****************nbytes: %ld ChunkRemain: %ldx.\n", 
601                        nbytes, IO->IOB.ChunkSendRemain);
602                 if (nbytes < 0)
603                         StrBufPlain(IO->ErrMsg, errmsg, -1);
604                 else 
605                 {
606                         if (IO->IOB.ChunkSendRemain == 0)
607                         {
608                                 IO->NextState = eSendReply;
609                                 syslog(LOG_DEBUG, "***********************************xxxx.\n");
610                         }
611                         else
612                                 return;
613                 }
614                 break;
615         default:
616                 nbytes = StrBuf_read_one_chunk_callback(watcher->fd, 0 /*TODO */, &IO->RecvBuf);
617                 break;
618         }
619
620 #ifdef BIGBAD_IODBG
621         {
622                 int rv = 0;
623                 char fn [SIZ];
624                 FILE *fd;
625                 const char *pch = ChrPtr(IO->RecvBuf.Buf);
626                 const char *pchh = IO->RecvBuf.ReadWritePointer;
627                 long nbytes;
628                 
629                 if (pchh == NULL)
630                         pchh = pch;
631                 
632                 nbytes = StrLength(IO->RecvBuf.Buf) - (pchh - pch);
633                 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
634                          ((CitContext*)(IO->CitContext))->ServiceName, 
635                          IO->SendBuf.fd);
636                 
637                 fd = fopen(fn, "a+");
638                 fprintf(fd, "Read: BufSize: %ld BufContent: [",
639                         nbytes);
640                 rv = fwrite(pchh, nbytes, 1, fd);
641                 if (!rv) printf("failed to write debug to %s!\n", fn);
642                 fprintf(fd, "]\n");
643                 
644                 
645                 fclose(fd);
646         }
647 #endif
648         if (nbytes > 0) {
649                 HandleInbound(IO);
650         } else if (nbytes == 0) {
651                 assert(IO->Timeout);
652
653                 switch (IO->Timeout(IO))
654                 {
655                 case eAbort:
656                         ShutDownCLient(IO);
657                 default:
658                         break;
659                 }
660                 return;
661         } else if (nbytes == -1) {
662 /// TODO: FD is gone. kick it.        sock_buff_invoke_free(sb, errno);
663                 syslog(LOG_DEBUG, 
664                        "EVENT: Socket Invalid! %s \n",
665                        strerror(errno));
666                 ShutDownCLient(IO);
667                 return;
668         }
669 }
670
671 void
672 IO_postdns_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
673 {
674         AsyncIO *IO = watcher->data;
675         syslog(LOG_DEBUG, "event: %s\n", __FUNCTION__);
676         become_session(IO->CitContext);
677         assert(IO->DNSFail);
678         assert(IO->DNSQuery->PostDNS);
679         switch (IO->DNSQuery->PostDNS(IO))
680         {
681         case eAbort:
682                 IO->DNSFail(IO);
683         default:
684             break;
685         }
686 }
687
688 eNextState event_connect_socket(AsyncIO *IO, double conn_timeout, double first_rw_timeout)
689 {
690         int fdflags; 
691         int rc = -1;
692
693         IO->SendBuf.fd = IO->RecvBuf.fd = 
694                 socket(
695                         (IO->ConnectMe->IPv6)?PF_INET6:PF_INET, 
696                         SOCK_STREAM, 
697                         IPPROTO_TCP);
698
699         if (IO->SendBuf.fd < 0) {
700                 syslog(LOG_ERR, "EVENT: socket() failed: %s\n", strerror(errno));
701                 StrBufPrintf(IO->ErrMsg, "Failed to create socket: %s", strerror(errno));
702                 return eAbort;
703         }
704         fdflags = fcntl(IO->SendBuf.fd, F_GETFL);
705         if (fdflags < 0) {
706                 syslog(LOG_DEBUG, 
707                        "EVENT: unable to get socket flags! %s \n",
708                        strerror(errno));
709                 StrBufPrintf(IO->ErrMsg, "Failed to get socket flags: %s", strerror(errno));
710                 return eAbort;
711         }
712         fdflags = fdflags | O_NONBLOCK;
713         if (fcntl(IO->SendBuf.fd, F_SETFL, fdflags) < 0) {
714                 syslog(LOG_DEBUG, 
715                        "EVENT: unable to set socket nonblocking flags! %s \n",
716                        strerror(errno));
717                 StrBufPrintf(IO->ErrMsg, "Failed to set socket flags: %s", strerror(errno));
718                 close(IO->SendBuf.fd);
719                 IO->SendBuf.fd = IO->RecvBuf.fd = -1;
720                 return eAbort;
721         }
722 /* TODO: maye we could use offsetof() to calc the position of data... 
723  * http://doc.dvgu.ru/devel/ev.html#associating_custom_data_with_a_watcher
724  */
725         ev_io_init(&IO->recv_event, IO_recv_callback, IO->RecvBuf.fd, EV_READ);
726         IO->recv_event.data = IO;
727         ev_io_init(&IO->send_event, IO_send_callback, IO->SendBuf.fd, EV_WRITE);
728         IO->send_event.data = IO;
729
730         ev_timer_init(&IO->conn_fail, IO_connfail_callback, conn_timeout, 0);
731         IO->conn_fail.data = IO;
732         ev_timer_init(&IO->rw_timeout, IO_Timeout_callback, first_rw_timeout, 0);
733         IO->rw_timeout.data = IO;
734
735
736         /*  Bypass it like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
737 ///     ((struct sockaddr_in)IO->ConnectMe->Addr).sin_addr.s_addr = inet_addr("127.0.0.1");
738         if (IO->ConnectMe->IPv6)
739                 rc = connect(IO->SendBuf.fd, &IO->ConnectMe->Addr, sizeof(struct sockaddr_in6));
740         else
741                 rc = connect(IO->SendBuf.fd, (struct sockaddr_in *)&IO->ConnectMe->Addr, sizeof(struct sockaddr_in));
742
743         if (rc >= 0){
744                 syslog(LOG_DEBUG, "connect() immediate success.\n");
745                 set_start_callback(event_base, IO, 0);
746                 ev_timer_start(event_base, &IO->rw_timeout);
747                 return IO->NextState;
748         }
749         else if (errno == EINPROGRESS) {
750                 syslog(LOG_DEBUG, "connect() have to wait now.\n");
751
752                 ev_io_init(&IO->conn_event, IO_connestd_callback, IO->SendBuf.fd, EV_READ|EV_WRITE);
753                 IO->conn_event.data = IO;
754
755                 ev_io_start(event_base, &IO->conn_event);
756                 ev_timer_start(event_base, &IO->conn_fail);
757                 return IO->NextState;
758         }
759         else {
760                 ev_idle_init(&IO->conn_fail_immediate,
761                              IO_connfailimmediate_callback);
762                 IO->conn_fail_immediate.data = IO;
763                 ev_idle_start(event_base, &IO->conn_fail_immediate);
764                 
765                 syslog(LOG_ERR, "connect() failed: %s\n", strerror(errno));
766                 StrBufPrintf(IO->ErrMsg, "Failed to connect: %s", strerror(errno));
767                 return IO->NextState;
768         }
769         return IO->NextState;
770 }
771
772 void SetNextTimeout(AsyncIO *IO, double timeout)
773 {
774         IO->rw_timeout.repeat = timeout;
775         ev_timer_again (event_base,  &IO->rw_timeout);
776 }
777
778 eNextState InitEventIO(AsyncIO *IO, 
779                        void *pData, 
780                        double conn_timeout, 
781                        double first_rw_timeout,
782                        int ReadFirst)
783 {
784         IO->Data = pData;
785         become_session(IO->CitContext);
786         
787         if (ReadFirst) {
788                 IO->NextState = eReadMessage;
789         }
790         else {
791                 IO->NextState = eSendReply;
792         }
793         return event_connect_socket(IO, conn_timeout, first_rw_timeout);
794 }
795
796 eNextState ReAttachIO(AsyncIO *IO, 
797                       void *pData, 
798                       int ReadFirst)
799 {
800         IO->Data = pData;
801         become_session(IO->CitContext);
802         ev_cleanup_start(event_base, &IO->abort_by_shutdown);
803         if (ReadFirst) {
804                 IO->NextState = eReadMessage;
805         }
806         else {
807                 IO->NextState = eSendReply;
808         }
809         set_start_callback(event_base, IO, 0);
810
811         return IO->NextState;
812 }