rename InitEventIO to EvConnectSock, since this suits better what this function does...
[citadel.git] / citadel / event_client.c
1 /*
2  *
3  * Copyright (c) 1998-2009 by the citadel.org team
4  *
5  *  This program is open source 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         AsyncIO *IO = watcher->data;
73         EV_syslog(LOG_DEBUG, "EVENT Q: %s\n", __FUNCTION__);
74
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         EVM_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         EVM_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         EVM_syslog(LOG_DEBUG, "DBEVENT Terminating.\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         EV_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                 ev_idle_stop(event_db, &IO->db_unwind_stack);
158                 ev_cleanup_stop(loop, &IO->db_abort_by_shutdown);
159                 ShutDownDBCLient(IO);
160         }
161 }
162
163 eNextState NextDBOperation(AsyncIO *IO, IO_CallBack CB)
164 {
165         IO->NextDBOperation = CB;
166         ev_idle_init(&IO->db_unwind_stack,
167                      DB_PerformNext);
168         IO->db_unwind_stack.data = IO;
169         ev_idle_start(event_db, &IO->db_unwind_stack);
170         return eDBQuery;
171 }
172
173 /*--------------------------------------------------------------------------------
174  * Client IO 
175  */
176 extern int evbase_count;
177 extern pthread_mutex_t EventQueueMutex;
178 extern HashList *InboundEventQueue;
179 extern struct ev_loop *event_base;
180 extern ev_async AddJob;   
181 extern ev_async ExitEventLoop;
182
183
184 eNextState QueueEventContext(AsyncIO *IO, IO_CallBack CB)
185 {
186         IOAddHandler *h;
187         int i;
188
189         h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
190         h->IO = IO;
191         h->EvAttch = CB;
192         ev_cleanup_init(&IO->abort_by_shutdown, 
193                         IO_abort_shutdown_callback);
194         IO->abort_by_shutdown.data = IO;
195         ev_cleanup_start(event_base, &IO->abort_by_shutdown);
196
197         pthread_mutex_lock(&EventQueueMutex);
198         EVM_syslog(LOG_DEBUG, "EVENT Q\n");
199         i = ++evbase_count;
200         Put(InboundEventQueue, IKEY(i), h, NULL);
201         pthread_mutex_unlock(&EventQueueMutex);
202
203         ev_async_send (event_base, &AddJob);
204         EVM_syslog(LOG_DEBUG, "EVENT Q Done.\n");
205         return eSendReply;
206 }
207
208 extern eNextState evcurl_handle_start(AsyncIO *IO);
209
210 eNextState QueueCurlContext(AsyncIO *IO)
211 {
212         IOAddHandler *h;
213         int i;
214
215         h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
216         h->IO = IO;
217         h->EvAttch = evcurl_handle_start;
218
219         pthread_mutex_lock(&EventQueueMutex);
220         EVM_syslog(LOG_DEBUG, "EVENT Q\n");
221         i = ++evbase_count;
222         Put(InboundEventQueue, IKEY(i), h, NULL);
223         pthread_mutex_unlock(&EventQueueMutex);
224
225         ev_async_send (event_base, &AddJob);
226         EVM_syslog(LOG_DEBUG, "EVENT Q Done.\n");
227         return eSendReply;
228 }
229
230 void FreeAsyncIOContents(AsyncIO *IO)
231 {
232         FreeStrBuf(&IO->IOBuf);
233         FreeStrBuf(&IO->SendBuf.Buf);
234         FreeStrBuf(&IO->RecvBuf.Buf);
235 }
236
237
238 void StopClientWatchers(AsyncIO *IO)
239 {
240         ev_timer_stop(event_base, &IO->conn_fail);
241         ev_io_stop(event_base, &IO->conn_event);
242         ev_idle_stop(event_base, &IO->unwind_stack);
243
244         ev_io_stop(event_base, &IO->send_event);
245         ev_io_stop(event_base, &IO->recv_event);
246         ev_timer_stop (event_base, &IO->rw_timeout);
247         close(IO->SendBuf.fd);
248         IO->SendBuf.fd = 0;
249         IO->RecvBuf.fd = 0;
250 }
251
252 void ShutDownCLient(AsyncIO *IO)
253 {
254         CitContext *Ctx =IO->CitContext;
255         become_session(Ctx);
256
257         EVM_syslog(LOG_DEBUG, "EVENT Terminating \n");
258
259         ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
260         StopClientWatchers(IO);
261
262         if (IO->DNS.Channel != NULL) {
263                 ares_destroy(IO->DNS.Channel);
264                 ev_io_stop(event_base, &IO->DNS.recv_event);
265                 ev_io_stop(event_base, &IO->DNS.send_event);
266                 IO->DNS.Channel = NULL;
267         }
268         assert(IO->Terminate);
269         IO->Terminate(IO);
270         Ctx->state = CON_IDLE;
271         Ctx->kill_me = 1;
272 }
273
274
275 eReadState HandleInbound(AsyncIO *IO)
276 {
277         const char *Err = NULL;
278         eReadState Finished = eBufferNotEmpty;
279         
280         become_session(IO->CitContext);
281
282         while ((Finished == eBufferNotEmpty) && 
283                ((IO->NextState == eReadMessage)||
284                 (IO->NextState == eReadMore)||
285                 (IO->NextState == eReadFile)||
286                 (IO->NextState == eReadPayload)))
287         {
288                 if (IO->RecvBuf.nBlobBytesWanted != 0) { 
289                                 
290                 }
291                 else { /* Reading lines... */
292 //// lex line reply in callback, or do it ourselves. as nnn-blabla means continue reading in SMTP
293                         if ((IO->NextState == eReadFile) && 
294                             (Finished == eBufferNotEmpty))
295                         {
296                                 Finished = WriteIOBAlreadyRead(&IO->IOB, &Err);
297                                 if (Finished == eReadSuccess)
298                                 {
299                                         IO->NextState = eSendReply;                             
300                                 }
301                         }
302                         else if (IO->LineReader)
303                                 Finished = IO->LineReader(IO);
304                         else 
305                                 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
306                                 
307                         switch (Finished) {
308                         case eMustReadMore: /// read new from socket... 
309                                 break;
310                         case eBufferNotEmpty: /* shouldn't happen... */
311                         case eReadSuccess: /// done for now...
312                                 break;
313                         case eReadFail: /// WHUT?
314                                 ///todo: shut down! 
315                                 break;
316                         }
317                                         
318                 }
319                         
320                 if (Finished != eMustReadMore) {
321                         assert(IO->ReadDone);
322                         ev_io_stop(event_base, &IO->recv_event);
323                         IO->NextState = IO->ReadDone(IO);
324                         Finished = StrBufCheckBuffer(&IO->RecvBuf);
325                 }
326         }
327
328         switch (IO->NextState) {
329         case eSendFile:
330                 ev_io_start(event_base, &IO->send_event);
331                 break;
332         case eSendReply:
333         case eSendMore:
334                 assert(IO->SendDone);
335                 IO->NextState = IO->SendDone(IO);
336                 ev_io_start(event_base, &IO->send_event);
337                 break;
338         case eReadPayload:
339         case eReadMore:
340         case eReadFile:
341                 ev_io_start(event_base, &IO->recv_event);
342                 break;
343         case eTerminateConnection:
344 //////TODOxxxx
345                 break;
346         case eAbort:
347                 ShutDownCLient(IO);
348                 break;
349         case eSendDNSQuery:
350         case eReadDNSReply:
351         case eDBQuery:
352         case eConnect:
353         case eReadMessage:
354                 break;
355         }
356         return Finished;
357 }
358
359
360 static void
361 IO_send_callback(struct ev_loop *loop, ev_io *watcher, int revents)
362 {
363         int rc;
364         AsyncIO *IO = watcher->data;
365         const char *errmsg = NULL;
366
367         become_session(IO->CitContext);
368 #ifdef BIGBAD_IODBG
369         {
370                 int rv = 0;
371                 char fn [SIZ];
372                 FILE *fd;
373                 const char *pch = ChrPtr(IO->SendBuf.Buf);
374                 const char *pchh = IO->SendBuf.ReadWritePointer;
375                 long nbytes;
376                 
377                 if (pchh == NULL)
378                         pchh = pch;
379                 
380                 nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
381                 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
382                          ((CitContext*)(IO->CitContext))->ServiceName,
383                          IO->SendBuf.fd);
384                 
385                 fd = fopen(fn, "a+");
386                 fprintf(fd, "Send: BufSize: %ld BufContent: [",
387                         nbytes);
388                 rv = fwrite(pchh, nbytes, 1, fd);
389                 if (!rv) printf("failed to write debug to %s!\n", fn);
390                 fprintf(fd, "]\n");
391 #endif
392                 switch (IO->NextState) {
393                 case eSendFile:
394                         rc = FileSendChunked(&IO->IOB, &errmsg);
395                         if (rc < 0)
396                                 StrBufPlain(IO->ErrMsg, errmsg, -1);
397                         break;
398                 default:
399                         rc = StrBuf_write_one_chunk_callback(watcher->fd, 0/*TODO*/, &IO->SendBuf);
400                 }
401
402 #ifdef BIGBAD_IODBG
403                 fprintf(fd, "Sent: BufSize: %d bytes.\n", rc);
404                 fclose(fd);
405         }
406 #endif
407         if (rc == 0)
408         {
409                 ev_io_stop(event_base, &IO->send_event);
410                 switch (IO->NextState) {
411                 case eSendMore:
412                         assert(IO->SendDone);
413                         IO->NextState = IO->SendDone(IO);
414
415                         if ((IO->NextState == eTerminateConnection) ||
416                             (IO->NextState == eAbort) )
417                                 ShutDownCLient(IO);
418                         else {
419                                 ev_io_start(event_base, &IO->send_event);
420                         }
421                         break;
422                 case eSendFile:
423                         if (IO->IOB.ChunkSendRemain > 0) {
424                                 ev_io_start(event_base, &IO->recv_event);
425                         } else {
426                                 assert(IO->ReadDone);
427                                 IO->NextState = IO->ReadDone(IO);
428                                 switch(IO->NextState) {
429                                 case eSendDNSQuery:
430                                 case eReadDNSReply:
431                                 case eDBQuery:
432                                 case eConnect:
433                                         break;
434                                 case eSendReply: 
435                                 case eSendMore:
436                                 case eSendFile:
437                                         ev_io_start(event_base, &IO->send_event);
438                                         break;
439                                 case eReadMessage: 
440                                 case eReadMore:
441                                 case eReadPayload:
442                                 case eReadFile:
443                                         break;
444                                 case eTerminateConnection:
445                                 case eAbort:
446                                         break;
447                                 }
448                         }
449                         break;
450                 case eSendReply:
451                     if (StrBufCheckBuffer(&IO->SendBuf) != eReadSuccess) 
452                         break;
453                     IO->NextState = eReadMore;
454                 case eReadMore:
455                 case eReadMessage:
456                 case eReadPayload:
457                 case eReadFile:
458                         if (StrBufCheckBuffer(&IO->RecvBuf) == eBufferNotEmpty) {
459                                 HandleInbound(IO);
460                         }
461                         else {
462                                 ev_io_start(event_base, &IO->recv_event);
463                         }
464
465                         break;
466                 case eDBQuery:
467                         /* we now live in another queue, so we have to unregister. */
468                         ev_cleanup_stop(loop, &IO->abort_by_shutdown);
469                         break;
470                 case eSendDNSQuery:
471                 case eReadDNSReply:
472                 case eConnect:
473                 case eTerminateConnection:
474                 case eAbort:
475                         break;
476                 }
477         }
478         else if (rc < 0) {
479                 assert(IO->Timeout);
480                 IO->Timeout(IO);
481         }
482         /* else : must write more. */
483 }
484 static void
485 set_start_callback(struct ev_loop *loop, AsyncIO *IO, int revents)
486 {
487         
488         switch(IO->NextState) {
489         case eReadMore:
490         case eReadMessage:
491         case eReadFile:
492                 ev_io_start(event_base, &IO->recv_event);
493                 break;
494         case eSendReply:
495         case eSendMore:
496         case eReadPayload:
497         case eSendFile:
498                 become_session(IO->CitContext);
499                 IO_send_callback(loop, &IO->send_event, revents);
500                 break;
501         case eDBQuery:
502         case eSendDNSQuery:
503         case eReadDNSReply:
504         case eConnect:
505         case eTerminateConnection:
506         case eAbort:
507                 /// TODO: WHUT?
508                 break;
509         }
510 }
511
512 static void
513 IO_Timeout_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
514 {
515         AsyncIO *IO = watcher->data;
516
517         ev_timer_stop (event_base, &IO->rw_timeout);
518         become_session(IO->CitContext);
519
520         if (IO->SendBuf.fd != 0)
521         {
522                 ev_io_stop(event_base, &IO->send_event);
523                 ev_io_stop(event_base, &IO->recv_event);
524                 ev_timer_stop (event_base, &IO->rw_timeout);
525                 close(IO->SendBuf.fd);
526                 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
527         }
528
529         assert(IO->Timeout);
530         switch (IO->Timeout(IO))
531         {
532         case eAbort:
533                 ShutDownCLient(IO);
534         default:
535                 break;
536         }
537 }
538
539 static void
540 IO_connfail_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
541 {
542         AsyncIO *IO = watcher->data;
543
544         ev_timer_stop (event_base, &IO->conn_fail);
545
546         if (IO->SendBuf.fd != 0)
547         {
548                 ev_io_stop(loop, &IO->conn_event);
549                 ev_io_stop(event_base, &IO->send_event);
550                 ev_io_stop(event_base, &IO->recv_event);
551                 ev_timer_stop (event_base, &IO->rw_timeout);
552                 close(IO->SendBuf.fd);
553                 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
554         }
555         become_session(IO->CitContext);
556
557         assert(IO->ConnFail);
558         switch (IO->ConnFail(IO))
559         {
560         case eAbort:
561                 ShutDownCLient(IO);
562         default:
563                 break;
564
565         }
566 }
567
568 static void
569 IO_connfailimmediate_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
570 {
571         AsyncIO *IO = watcher->data;
572
573         ev_idle_stop (event_base, &IO->conn_fail_immediate);
574
575         if (IO->SendBuf.fd != 0)
576         {
577                 close(IO->SendBuf.fd);
578                 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
579         }
580         become_session(IO->CitContext);
581
582         assert(IO->ConnFail);
583         switch (IO->ConnFail(IO))
584         {
585         case eAbort:
586                 ShutDownCLient(IO);
587         default:
588                 break;
589
590         }
591 }
592
593 static void
594 IO_connestd_callback(struct ev_loop *loop, ev_io *watcher, int revents)
595 {
596         AsyncIO *IO = watcher->data;
597
598         ev_io_stop(loop, &IO->conn_event);
599         ev_timer_stop (event_base, &IO->conn_fail);
600         set_start_callback(loop, IO, revents);
601 }
602 static void
603 IO_recv_callback(struct ev_loop *loop, ev_io *watcher, int revents)
604 {
605         const char *errmsg;
606         ssize_t nbytes;
607         AsyncIO *IO = watcher->data;
608
609         switch (IO->NextState) {
610         case eReadFile:
611                 nbytes = FileRecvChunked(&IO->IOB, &errmsg);
612                 if (nbytes < 0)
613                         StrBufPlain(IO->ErrMsg, errmsg, -1);
614                 else 
615                 {
616                         if (IO->IOB.ChunkSendRemain == 0)
617                         {
618                                 IO->NextState = eSendReply;
619                         }
620                         else
621                                 return;
622                 }
623                 break;
624         default:
625                 nbytes = StrBuf_read_one_chunk_callback(watcher->fd, 0 /*TODO */, &IO->RecvBuf);
626                 break;
627         }
628
629 #ifdef BIGBAD_IODBG
630         {
631                 int rv = 0;
632                 char fn [SIZ];
633                 FILE *fd;
634                 const char *pch = ChrPtr(IO->RecvBuf.Buf);
635                 const char *pchh = IO->RecvBuf.ReadWritePointer;
636                 long nbytes;
637                 
638                 if (pchh == NULL)
639                         pchh = pch;
640                 
641                 nbytes = StrLength(IO->RecvBuf.Buf) - (pchh - pch);
642                 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
643                          ((CitContext*)(IO->CitContext))->ServiceName, 
644                          IO->SendBuf.fd);
645                 
646                 fd = fopen(fn, "a+");
647                 fprintf(fd, "Read: BufSize: %ld BufContent: [",
648                         nbytes);
649                 rv = fwrite(pchh, nbytes, 1, fd);
650                 if (!rv) printf("failed to write debug to %s!\n", fn);
651                 fprintf(fd, "]\n");
652                 
653                 
654                 fclose(fd);
655         }
656 #endif
657         if (nbytes > 0) {
658                 HandleInbound(IO);
659         } else if (nbytes == 0) {
660                 assert(IO->Timeout);
661
662                 switch (IO->Timeout(IO))
663                 {
664                 case eAbort:
665                         ShutDownCLient(IO);
666                 default:
667                         break;
668                 }
669                 return;
670         } else if (nbytes == -1) {
671 /// TODO: FD is gone. kick it.        sock_buff_invoke_free(sb, errno);
672                 EV_syslog(LOG_DEBUG, 
673                           "EVENT: Socket Invalid! %s \n",
674                           strerror(errno));
675                 ShutDownCLient(IO);
676                 return;
677         }
678 }
679
680 void
681 IO_postdns_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
682 {
683         AsyncIO *IO = watcher->data;
684         EV_syslog(LOG_DEBUG, "event: %s\n", __FUNCTION__);
685         become_session(IO->CitContext);
686         assert(IO->DNS.Fail);
687         assert(IO->DNS.Query->PostDNS);
688         switch (IO->DNS.Query->PostDNS(IO))
689         {
690         case eAbort:
691                 switch (IO->DNS.Fail(IO)) {
692                 case eAbort:
693                         ShutDownCLient(IO);
694                 default:
695                         break;
696                         
697                 }
698         default:
699                 break;
700         }
701 }
702
703
704 eNextState EvConnectSock(AsyncIO *IO, 
705                          void *pData, 
706                          double conn_timeout, 
707                          double first_rw_timeout,
708                          int ReadFirst)
709 {
710         int fdflags; 
711         int rc = -1;
712
713         IO->Data = pData;
714         become_session(IO->CitContext);
715         
716         if (ReadFirst) {
717                 IO->NextState = eReadMessage;
718         }
719         else {
720                 IO->NextState = eSendReply;
721         }
722
723         IO->SendBuf.fd = IO->RecvBuf.fd = 
724                 socket(
725                         (IO->ConnectMe->IPv6)?PF_INET6:PF_INET, 
726                         SOCK_STREAM, 
727                         IPPROTO_TCP);
728
729         if (IO->SendBuf.fd < 0) {
730                 EV_syslog(LOG_ERR, "EVENT: socket() failed: %s\n", strerror(errno));
731                 StrBufPrintf(IO->ErrMsg, "Failed to create socket: %s", strerror(errno));
732                 return eAbort;
733         }
734         fdflags = fcntl(IO->SendBuf.fd, F_GETFL);
735         if (fdflags < 0) {
736                 EV_syslog(LOG_DEBUG, 
737                           "EVENT: unable to get socket flags! %s \n",
738                           strerror(errno));
739                 StrBufPrintf(IO->ErrMsg, "Failed to get socket flags: %s", strerror(errno));
740                 return eAbort;
741         }
742         fdflags = fdflags | O_NONBLOCK;
743         if (fcntl(IO->SendBuf.fd, F_SETFL, fdflags) < 0) {
744                 EV_syslog(LOG_DEBUG, 
745                           "EVENT: unable to set socket nonblocking flags! %s \n",
746                           strerror(errno));
747                 StrBufPrintf(IO->ErrMsg, "Failed to set socket flags: %s", strerror(errno));
748                 close(IO->SendBuf.fd);
749                 IO->SendBuf.fd = IO->RecvBuf.fd = -1;
750                 return eAbort;
751         }
752 /* TODO: maye we could use offsetof() to calc the position of data... 
753  * http://doc.dvgu.ru/devel/ev.html#associating_custom_data_with_a_watcher
754  */
755         ev_io_init(&IO->recv_event, IO_recv_callback, IO->RecvBuf.fd, EV_READ);
756         IO->recv_event.data = IO;
757         ev_io_init(&IO->send_event, IO_send_callback, IO->SendBuf.fd, EV_WRITE);
758         IO->send_event.data = IO;
759
760         ev_timer_init(&IO->conn_fail, IO_connfail_callback, conn_timeout, 0);
761         IO->conn_fail.data = IO;
762         ev_timer_init(&IO->rw_timeout, IO_Timeout_callback, first_rw_timeout, 0);
763         IO->rw_timeout.data = IO;
764
765
766         /*  Bypass it like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
767 ///     ((struct sockaddr_in)IO->ConnectMe->Addr).sin_addr.s_addr = inet_addr("127.0.0.1");
768         if (IO->ConnectMe->IPv6)
769                 rc = connect(IO->SendBuf.fd, &IO->ConnectMe->Addr, sizeof(struct sockaddr_in6));
770         else
771                 rc = connect(IO->SendBuf.fd, (struct sockaddr_in *)&IO->ConnectMe->Addr, sizeof(struct sockaddr_in));
772
773         if (rc >= 0){
774                 EVM_syslog(LOG_DEBUG, "connect() immediate success.\n");
775                 set_start_callback(event_base, IO, 0);
776                 ev_timer_start(event_base, &IO->rw_timeout);
777                 return IO->NextState;
778         }
779         else if (errno == EINPROGRESS) {
780                 EVM_syslog(LOG_DEBUG, "connect() have to wait now.\n");
781
782                 ev_io_init(&IO->conn_event, IO_connestd_callback, IO->SendBuf.fd, EV_READ|EV_WRITE);
783                 IO->conn_event.data = IO;
784
785                 ev_io_start(event_base, &IO->conn_event);
786                 ev_timer_start(event_base, &IO->conn_fail);
787                 return IO->NextState;
788         }
789         else {
790                 ev_idle_init(&IO->conn_fail_immediate,
791                              IO_connfailimmediate_callback);
792                 IO->conn_fail_immediate.data = IO;
793                 ev_idle_start(event_base, &IO->conn_fail_immediate);
794                 
795                 EV_syslog(LOG_ERR, "connect() failed: %s\n", strerror(errno));
796                 StrBufPrintf(IO->ErrMsg, "Failed to connect: %s", strerror(errno));
797                 return IO->NextState;
798         }
799         return IO->NextState;
800 }
801
802 void SetNextTimeout(AsyncIO *IO, double timeout)
803 {
804         IO->rw_timeout.repeat = timeout;
805         ev_timer_again (event_base,  &IO->rw_timeout);
806 }
807
808
809 eNextState ReAttachIO(AsyncIO *IO, 
810                       void *pData, 
811                       int ReadFirst)
812 {
813         IO->Data = pData;
814         become_session(IO->CitContext);
815         ev_cleanup_start(event_base, &IO->abort_by_shutdown);
816         if (ReadFirst) {
817                 IO->NextState = eReadMessage;
818         }
819         else {
820                 IO->NextState = eSendReply;
821         }
822         set_start_callback(event_base, IO, 0);
823
824         return IO->NextState;
825 }