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