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