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