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