EV: stop all watchers before going into other queues - so we can avoid race conditions.
[citadel.git] / citadel / event_client.c
1 /*
2  * Copyright (c) 1998-2012 by the citadel.org team
3  *
4  * This program is open source software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License, version 3.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  */
12
13 #include "sysdep.h"
14 #include <stdlib.h>
15 #include <unistd.h>
16 #include <stdio.h>
17 #include <termios.h>
18 #include <fcntl.h>
19 #include <signal.h>
20 #include <pwd.h>
21 #include <errno.h>
22 #include <sys/types.h>
23 #include <syslog.h>
24
25 #if TIME_WITH_SYS_TIME
26 # include <sys/time.h>
27 # include <time.h>
28 #else
29 # if HAVE_SYS_TIME_H
30 #  include <sys/time.h>
31 # else
32 #  include <time.h>
33 # endif
34 #endif
35 #include <sys/wait.h>
36 #include <ctype.h>
37 #include <string.h>
38 #include <limits.h>
39 #include <sys/socket.h>
40 #include <netinet/in.h>
41 #include <arpa/inet.h>
42 #include <assert.h>
43 #if HAVE_BACKTRACE
44 #include <execinfo.h>
45 #endif
46
47 #include <libcitadel.h>
48 #include "citadel.h"
49 #include "server.h"
50 #include "citserver.h"
51 #include "support.h"
52 #include "config.h"
53 #include "control.h"
54 #include "user_ops.h"
55 #include "database.h"
56 #include "msgbase.h"
57 #include "internet_addressing.h"
58 #include "genstamp.h"
59 #include "domain.h"
60 #include "clientsocket.h"
61 #include "locate_host.h"
62 #include "citadel_dirs.h"
63
64 #include "event_client.h"
65 #include "ctdl_module.h"
66
67
68 ConstStr IOStates[] = {
69         {HKEY("DB Queue")},
70         {HKEY("DB Q Next")},
71         {HKEY("DB Attach")},
72         {HKEY("DB Next")},
73         {HKEY("DB Stop")},
74         {HKEY("DB Exit")},
75         {HKEY("DB Terminate")},
76         {HKEY("IO Queue")},
77         {HKEY("IO Attach")},
78         {HKEY("IO Connect Socket")},
79         {HKEY("IO Abort")},
80         {HKEY("IO Timeout")},
81         {HKEY("IO ConnFail")},
82         {HKEY("IO ConnFail Now")},
83         {HKEY("IO Conn Now")},
84         {HKEY("IO Conn Wait")},
85         {HKEY("Curl Q")},
86         {HKEY("Curl Start")},
87         {HKEY("Curl Shotdown")},
88         {HKEY("Curl More IO")},
89         {HKEY("Curl Got IO")},
90         {HKEY("Curl Got Data")},
91         {HKEY("Curl Got Status")},
92         {HKEY("C-Ares Start")},
93         {HKEY("C-Ares IO Done")},
94         {HKEY("C-Ares Finished")},
95         {HKEY("C-Ares exit")},
96         {HKEY("Killing")},
97         {HKEY("Exit")}
98 };
99
100 void SetEVState(AsyncIO *IO, eIOState State)
101 {
102
103         CitContext* CCC = IO->CitContext;
104         if (CCC != NULL)
105                 memcpy(CCC->lastcmdname, IOStates[State].Key, IOStates[State].len + 1);
106
107 }
108
109
110 static void IO_Timeout_callback(struct ev_loop *loop, ev_timer *watcher, int revents);
111 static void IO_abort_shutdown_callback(struct ev_loop *loop,
112                                        ev_cleanup *watcher,
113                                        int revents);
114
115
116 /*------------------------------------------------------------------------------
117  *                              Server DB IO
118  *----------------------------------------------------------------------------*/
119 extern int evdb_count;
120 extern pthread_mutex_t DBEventQueueMutex;
121 extern pthread_mutex_t DBEventExitQueueMutex;
122 extern HashList *DBInboundEventQueue;
123 extern struct ev_loop *event_db;
124 extern ev_async DBAddJob;
125 extern ev_async DBExitEventLoop;
126
127 eNextState QueueDBOperation(AsyncIO *IO, IO_CallBack CB)
128 {
129         IOAddHandler *h;
130         int i;
131
132         SetEVState(IO, eDBQ);
133         h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
134         h->IO = IO;
135         h->EvAttch = CB;
136         ev_cleanup_init(&IO->db_abort_by_shutdown,
137                         IO_abort_shutdown_callback);
138         IO->db_abort_by_shutdown.data = IO;
139
140         pthread_mutex_lock(&DBEventQueueMutex);
141         if (DBInboundEventQueue == NULL)
142         {
143                 /* shutting down... */
144                 free(h);
145                 EVM_syslog(LOG_DEBUG, "DBEVENT Q exiting.\n");
146                 pthread_mutex_unlock(&DBEventQueueMutex);
147                 return eAbort;
148         }
149         EVM_syslog(LOG_DEBUG, "DBEVENT Q\n");
150         i = ++evdb_count ;
151         Put(DBInboundEventQueue, IKEY(i), h, NULL);
152         pthread_mutex_unlock(&DBEventQueueMutex);
153
154         pthread_mutex_lock(&DBEventExitQueueMutex);
155         if (event_db == NULL)
156         {
157                 pthread_mutex_unlock(&DBEventExitQueueMutex);
158                 return eAbort;
159         }
160         ev_async_send (event_db, &DBAddJob);
161         pthread_mutex_unlock(&DBEventExitQueueMutex);
162
163         EVM_syslog(LOG_DEBUG, "DBEVENT Q Done.\n");
164         return eDBQuery;
165 }
166
167 void StopDBWatchers(AsyncIO *IO)
168 {
169         SetEVState(IO, eDBStop);
170         ev_cleanup_stop(event_db, &IO->db_abort_by_shutdown);
171         ev_idle_stop(event_db, &IO->db_unwind_stack);
172 }
173
174 void ShutDownDBCLient(AsyncIO *IO)
175 {
176         CitContext *Ctx =IO->CitContext;
177         become_session(Ctx);
178
179         SetEVState(IO, eDBTerm);
180         EVM_syslog(LOG_DEBUG, "DBEVENT Terminating.\n");
181         StopDBWatchers(IO);
182
183         assert(IO->DBTerminate);
184         IO->DBTerminate(IO);
185 }
186
187 void
188 DB_PerformNext(struct ev_loop *loop, ev_idle *watcher, int revents)
189 {
190         AsyncIO *IO = watcher->data;
191
192         SetEVState(IO, eDBNext);
193         IO->Now = ev_now(event_db);
194         EV_syslog(LOG_DEBUG, "%s()", __FUNCTION__);
195         become_session(IO->CitContext);
196
197         ev_idle_stop(event_db, &IO->db_unwind_stack);
198
199         assert(IO->NextDBOperation);
200         switch (IO->NextDBOperation(IO))
201         {
202         case eDBQuery:
203                 break;
204         case eSendDNSQuery:
205         case eReadDNSReply:
206         case eConnect:
207         case eSendReply:
208         case eSendMore:
209         case eSendFile:
210         case eReadMessage:
211         case eReadMore:
212         case eReadPayload:
213         case eReadFile:
214                 ev_cleanup_stop(loop, &IO->db_abort_by_shutdown);
215                 break;
216         case eTerminateConnection:
217         case eAbort:
218                 ev_idle_stop(event_db, &IO->db_unwind_stack);
219                 ev_cleanup_stop(loop, &IO->db_abort_by_shutdown);
220                 ShutDownDBCLient(IO);
221         }
222 }
223
224 eNextState NextDBOperation(AsyncIO *IO, IO_CallBack CB)
225 {
226         SetEVState(IO, eQDBNext);
227         IO->NextDBOperation = CB;
228         ev_idle_init(&IO->db_unwind_stack,
229                      DB_PerformNext);
230         IO->db_unwind_stack.data = IO;
231         ev_idle_start(event_db, &IO->db_unwind_stack);
232         return eDBQuery;
233 }
234
235 /*------------------------------------------------------------------------------
236  *                      Client IO
237  *----------------------------------------------------------------------------*/
238 extern int evbase_count;
239 extern pthread_mutex_t EventQueueMutex;
240 extern pthread_mutex_t EventExitQueueMutex; 
241 extern HashList *InboundEventQueue;
242 extern struct ev_loop *event_base;
243 extern ev_async AddJob;
244 extern ev_async ExitEventLoop;
245
246 static void IO_abort_shutdown_callback(struct ev_loop *loop,
247                                        ev_cleanup *watcher,
248                                        int revents)
249 {
250         AsyncIO *IO = watcher->data;
251
252         SetEVState(IO, eIOAbort);
253         EV_syslog(LOG_DEBUG, "EVENT Q: %s\n", __FUNCTION__);
254         IO->Now = ev_now(event_base);
255         assert(IO->ShutdownAbort);
256         IO->ShutdownAbort(IO);
257 }
258
259
260 eNextState QueueEventContext(AsyncIO *IO, IO_CallBack CB)
261 {
262         IOAddHandler *h;
263         int i;
264
265         SetEVState(IO, eIOQ);
266         h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
267         h->IO = IO;
268         h->EvAttch = CB;
269         ev_cleanup_init(&IO->abort_by_shutdown,
270                         IO_abort_shutdown_callback);
271         IO->abort_by_shutdown.data = IO;
272
273         pthread_mutex_lock(&EventQueueMutex);
274         if (InboundEventQueue == NULL)
275         {
276                 free(h);
277                 /* shutting down... */
278                 EVM_syslog(LOG_DEBUG, "EVENT Q exiting.\n");
279                 pthread_mutex_unlock(&EventQueueMutex);
280                 return eAbort;
281         }
282         EVM_syslog(LOG_DEBUG, "EVENT Q\n");
283         i = ++evbase_count;
284         Put(InboundEventQueue, IKEY(i), h, NULL);
285         pthread_mutex_unlock(&EventQueueMutex);
286
287         pthread_mutex_lock(&EventExitQueueMutex);
288         if (event_base == NULL) {
289                 pthread_mutex_unlock(&EventExitQueueMutex);
290                 return eAbort;
291         }
292         ev_async_send (event_base, &AddJob);
293         pthread_mutex_unlock(&EventExitQueueMutex);
294         EVM_syslog(LOG_DEBUG, "EVENT Q Done.\n");
295         return eSendReply;
296 }
297
298 eNextState EventQueueDBOperation(AsyncIO *IO, IO_CallBack CB)
299 {
300         StopClientWatchers(IO, 0);
301         return QueueDBOperation(IO, CB);
302 }
303 eNextState DBQueueEventContext(AsyncIO *IO, IO_CallBack CB)
304 {
305         StopDBWatchers(IO);
306         return QueueEventContext(IO, CB);
307 }
308
309 extern eNextState evcurl_handle_start(AsyncIO *IO);
310
311 eNextState QueueCurlContext(AsyncIO *IO)
312 {
313         IOAddHandler *h;
314         int i;
315
316         SetEVState(IO, eCurlQ);
317         h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
318         h->IO = IO;
319         h->EvAttch = evcurl_handle_start;
320
321         pthread_mutex_lock(&EventQueueMutex);
322         if (InboundEventQueue == NULL)
323         {
324                 /* shutting down... */
325                 free(h);
326                 EVM_syslog(LOG_DEBUG, "EVENT Q exiting.\n");
327                 pthread_mutex_unlock(&EventQueueMutex);
328                 return eAbort;
329         }
330
331         EVM_syslog(LOG_DEBUG, "EVENT Q\n");
332         i = ++evbase_count;
333         Put(InboundEventQueue, IKEY(i), h, NULL);
334         pthread_mutex_unlock(&EventQueueMutex);
335
336         pthread_mutex_lock(&EventExitQueueMutex);
337         if (event_base == NULL) {
338                 pthread_mutex_unlock(&EventExitQueueMutex);
339                 return eAbort;
340         }
341         ev_async_send (event_base, &AddJob);
342         pthread_mutex_unlock(&EventExitQueueMutex);
343
344         EVM_syslog(LOG_DEBUG, "EVENT Q Done.\n");
345         return eSendReply;
346 }
347
348 eNextState CurlQueueDBOperation(AsyncIO *IO, IO_CallBack CB)
349 {
350         StopCurlWatchers(IO);
351         return QueueDBOperation(IO, CB);
352 }
353
354
355 void DestructCAres(AsyncIO *IO);
356 void FreeAsyncIOContents(AsyncIO *IO)
357 {
358         CitContext *Ctx = IO->CitContext;
359
360         FreeStrBuf(&IO->IOBuf);
361         FreeStrBuf(&IO->SendBuf.Buf);
362         FreeStrBuf(&IO->RecvBuf.Buf);
363
364         DestructCAres(IO);
365
366         FreeURL(&IO->ConnectMe);
367         FreeStrBuf(&IO->HttpReq.ReplyData);
368
369         if (Ctx) {
370                 Ctx->state = CON_IDLE;
371                 Ctx->kill_me = 1;
372                 IO->CitContext = NULL;
373         }
374 }
375
376
377 void StopClientWatchers(AsyncIO *IO, int CloseFD)
378 {
379         ev_timer_stop (event_base, &IO->rw_timeout);
380         ev_timer_stop(event_base, &IO->conn_fail);
381         ev_idle_stop(event_base, &IO->unwind_stack);
382         ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
383
384         ev_io_stop(event_base, &IO->conn_event);
385         ev_io_stop(event_base, &IO->send_event);
386         ev_io_stop(event_base, &IO->recv_event);
387
388         if (CloseFD && (IO->SendBuf.fd > 0)) {
389                 close(IO->SendBuf.fd);
390                 IO->SendBuf.fd = 0;
391                 IO->RecvBuf.fd = 0;
392         }
393 }
394
395 void StopCurlWatchers(AsyncIO *IO)
396 {
397         ev_timer_stop (event_base, &IO->rw_timeout);
398         ev_timer_stop(event_base, &IO->conn_fail);
399         ev_idle_stop(event_base, &IO->unwind_stack);
400         ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
401
402         ev_io_stop(event_base, &IO->conn_event);
403         ev_io_stop(event_base, &IO->send_event);
404         ev_io_stop(event_base, &IO->recv_event);
405
406         if (IO->SendBuf.fd != 0) {
407                 close(IO->SendBuf.fd);
408         }
409         IO->SendBuf.fd = 0;
410         IO->RecvBuf.fd = 0;
411 }
412
413 void ShutDownCLient(AsyncIO *IO)
414 {
415         CitContext *Ctx =IO->CitContext;
416
417         SetEVState(IO, eExit);
418         become_session(Ctx);
419
420         EVM_syslog(LOG_DEBUG, "EVENT Terminating \n");
421
422         StopClientWatchers(IO, 1);
423
424         if (IO->DNS.Channel != NULL) {
425                 ares_destroy(IO->DNS.Channel);
426                 EV_DNS_LOG_STOP(DNS.recv_event);
427                 EV_DNS_LOG_STOP(DNS.send_event);
428                 ev_io_stop(event_base, &IO->DNS.recv_event);
429                 ev_io_stop(event_base, &IO->DNS.send_event);
430                 IO->DNS.Channel = NULL;
431         }
432         assert(IO->Terminate);
433         IO->Terminate(IO);
434 }
435
436 void PostInbound(AsyncIO *IO)
437 {
438         switch (IO->NextState) {
439         case eSendFile:
440                 ev_io_start(event_base, &IO->send_event);
441                 break;
442         case eSendReply:
443         case eSendMore:
444                 assert(IO->SendDone);
445                 IO->NextState = IO->SendDone(IO);
446                 switch (IO->NextState)
447                 {
448                 case eSendFile:
449                 case eSendReply:
450                 case eSendMore:
451                 case eReadMessage:
452                 case eReadPayload:
453                 case eReadMore:
454                 case eReadFile:
455                         ev_io_start(event_base, &IO->send_event);
456                         break;
457                 case eDBQuery:
458                         StopClientWatchers(IO, 0);
459                 default:
460                         break;
461                 }
462                 break;
463         case eReadPayload:
464         case eReadMore:
465         case eReadFile:
466                 ev_io_start(event_base, &IO->recv_event);
467                 break;
468         case eTerminateConnection:
469                 ShutDownCLient(IO);
470                 break;
471         case eAbort:
472                 ShutDownCLient(IO);
473                 break;
474         case eSendDNSQuery:
475         case eReadDNSReply:
476         case eDBQuery:
477         case eConnect:
478         case eReadMessage:
479                 break;
480         }
481 }
482 eReadState HandleInbound(AsyncIO *IO)
483 {
484         const char *Err = NULL;
485         eReadState Finished = eBufferNotEmpty;
486
487         become_session(IO->CitContext);
488
489         while ((Finished == eBufferNotEmpty) &&
490                ((IO->NextState == eReadMessage)||
491                 (IO->NextState == eReadMore)||
492                 (IO->NextState == eReadFile)||
493                 (IO->NextState == eReadPayload)))
494         {
495                 /* Reading lines...
496                  * lex line reply in callback,
497                  * or do it ourselves.
498                  * i.e. as nnn-blabla means continue reading in SMTP
499                  */
500                 if ((IO->NextState == eReadFile) &&
501                     (Finished == eBufferNotEmpty))
502                 {
503                         Finished = WriteIOBAlreadyRead(&IO->IOB, &Err);
504                         if (Finished == eReadSuccess)
505                         {
506                                 IO->NextState = eSendReply;
507                         }
508                 }
509                 else if (IO->LineReader)
510                         Finished = IO->LineReader(IO);
511                 else
512                         Finished = StrBufChunkSipLine(IO->IOBuf,
513                                                       &IO->RecvBuf);
514
515                 switch (Finished) {
516                 case eMustReadMore: /// read new from socket...
517                         break;
518                 case eBufferNotEmpty: /* shouldn't happen... */
519                 case eReadSuccess: /// done for now...
520                         break;
521                 case eReadFail: /// WHUT?
522                                 ///todo: shut down!
523                         break;
524                 }
525
526                 if (Finished != eMustReadMore) {
527                         assert(IO->ReadDone);
528                         ev_io_stop(event_base, &IO->recv_event);
529                         IO->NextState = IO->ReadDone(IO);
530                         Finished = StrBufCheckBuffer(&IO->RecvBuf);
531                 }
532         }
533
534         PostInbound(IO);
535
536         return Finished;
537 }
538
539
540 static void
541 IO_send_callback(struct ev_loop *loop, ev_io *watcher, int revents)
542 {
543         int rc;
544         AsyncIO *IO = watcher->data;
545         const char *errmsg = NULL;
546
547         IO->Now = ev_now(event_base);
548         become_session(IO->CitContext);
549 #ifdef BIGBAD_IODBG
550         {
551                 int rv = 0;
552                 char fn [SIZ];
553                 FILE *fd;
554                 const char *pch = ChrPtr(IO->SendBuf.Buf);
555                 const char *pchh = IO->SendBuf.ReadWritePointer;
556                 long nbytes;
557
558                 if (pchh == NULL)
559                         pchh = pch;
560
561                 nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
562                 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
563                          ((CitContext*)(IO->CitContext))->ServiceName,
564                          IO->SendBuf.fd);
565
566                 fd = fopen(fn, "a+");
567                 fprintf(fd, "Send: BufSize: %ld BufContent: [",
568                         nbytes);
569                 rv = fwrite(pchh, nbytes, 1, fd);
570                 if (!rv) printf("failed to write debug to %s!\n", fn);
571                 fprintf(fd, "]\n");
572 #endif
573                 switch (IO->NextState) {
574                 case eSendFile:
575                         rc = FileSendChunked(&IO->IOB, &errmsg);
576                         if (rc < 0)
577                                 StrBufPlain(IO->ErrMsg, errmsg, -1);
578                         break;
579                 default:
580                         rc = StrBuf_write_one_chunk_callback(IO->SendBuf.fd,
581                                                              0,
582                                                              &IO->SendBuf);
583                 }
584
585 #ifdef BIGBAD_IODBG
586                 fprintf(fd, "Sent: BufSize: %d bytes.\n", rc);
587                 fclose(fd);
588         }
589 #endif
590         if (rc == 0)
591         {
592                 ev_io_stop(event_base, &IO->send_event);
593                 switch (IO->NextState) {
594                 case eSendMore:
595                         assert(IO->SendDone);
596                         IO->NextState = IO->SendDone(IO);
597
598                         if ((IO->NextState == eTerminateConnection) ||
599                             (IO->NextState == eAbort) )
600                                 ShutDownCLient(IO);
601                         else {
602                                 ev_io_start(event_base, &IO->send_event);
603                         }
604                         break;
605                 case eSendFile:
606                         if (IO->IOB.ChunkSendRemain > 0) {
607                                 ev_io_start(event_base, &IO->recv_event);
608                                 SetNextTimeout(IO, 100.0);
609
610                         } else {
611                                 assert(IO->ReadDone);
612                                 IO->NextState = IO->ReadDone(IO);
613                                 switch(IO->NextState) {
614                                 case eSendDNSQuery:
615                                 case eReadDNSReply:
616                                 case eDBQuery:
617                                 case eConnect:
618                                         break;
619                                 case eSendReply:
620                                 case eSendMore:
621                                 case eSendFile:
622                                         ev_io_start(event_base,
623                                                     &IO->send_event);
624                                         break;
625                                 case eReadMessage:
626                                 case eReadMore:
627                                 case eReadPayload:
628                                 case eReadFile:
629                                         break;
630                                 case eTerminateConnection:
631                                 case eAbort:
632                                         break;
633                                 }
634                         }
635                         break;
636                 case eSendReply:
637                     if (StrBufCheckBuffer(&IO->SendBuf) != eReadSuccess)
638                         break;
639                     IO->NextState = eReadMore;
640                 case eReadMore:
641                 case eReadMessage:
642                 case eReadPayload:
643                 case eReadFile:
644                         if (StrBufCheckBuffer(&IO->RecvBuf) == eBufferNotEmpty)
645                         {
646                                 HandleInbound(IO);
647                         }
648                         else {
649                                 ev_io_start(event_base, &IO->recv_event);
650                         }
651
652                         break;
653                 case eDBQuery:
654                         /*
655                          * we now live in another queue,
656                          * so we have to unregister.
657                          */
658                         ev_cleanup_stop(loop, &IO->abort_by_shutdown);
659                         break;
660                 case eSendDNSQuery:
661                 case eReadDNSReply:
662                 case eConnect:
663                 case eTerminateConnection:
664                 case eAbort:
665                         break;
666                 }
667         }
668         else if (rc < 0) {
669                 if (errno != EAGAIN) {
670                         StopClientWatchers(IO, 1);
671                         EV_syslog(LOG_DEBUG,
672                                   "IO_send_callback(): Socket Invalid! [%d] [%s] [%d]\n",
673                                   errno, strerror(errno), IO->SendBuf.fd);
674                         StrBufPrintf(IO->ErrMsg,
675                                      "Socket Invalid! [%s]",
676                                      strerror(errno));
677                         SetNextTimeout(IO, 0.01);
678                 }
679         }
680         /* else : must write more. */
681 }
682 static void
683 set_start_callback(struct ev_loop *loop, AsyncIO *IO, int revents)
684 {
685         ev_timer_stop(event_base, &IO->conn_fail);
686         ev_timer_start(event_base, &IO->rw_timeout);
687
688         switch(IO->NextState) {
689         case eReadMore:
690         case eReadMessage:
691         case eReadFile:
692                 StrBufAppendBufPlain(IO->ErrMsg, HKEY("[while waiting for greeting]"), 0);
693                 ev_io_start(event_base, &IO->recv_event);
694                 break;
695         case eSendReply:
696         case eSendMore:
697         case eReadPayload:
698         case eSendFile:
699                 become_session(IO->CitContext);
700                 IO_send_callback(loop, &IO->send_event, revents);
701                 break;
702         case eDBQuery:
703         case eSendDNSQuery:
704         case eReadDNSReply:
705         case eConnect:
706         case eTerminateConnection:
707         case eAbort:
708                 /// TODO: WHUT?
709                 break;
710         }
711 }
712
713 static void
714 IO_Timeout_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
715 {
716         AsyncIO *IO = watcher->data;
717
718         SetEVState(IO, eIOTimeout);
719         IO->Now = ev_now(event_base);
720         ev_timer_stop (event_base, &IO->rw_timeout);
721         become_session(IO->CitContext);
722
723         if (IO->SendBuf.fd != 0)
724         {
725                 ev_io_stop(event_base, &IO->send_event);
726                 ev_io_stop(event_base, &IO->recv_event);
727                 ev_timer_stop (event_base, &IO->rw_timeout);
728                 close(IO->SendBuf.fd);
729                 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
730         }
731
732         assert(IO->Timeout);
733         switch (IO->Timeout(IO))
734         {
735         case eAbort:
736                 ShutDownCLient(IO);
737         default:
738                 break;
739         }
740 }
741
742 static void
743 IO_connfail_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
744 {
745         AsyncIO *IO = watcher->data;
746
747         SetEVState(IO, eIOConnfail);
748         IO->Now = ev_now(event_base);
749         ev_timer_stop (event_base, &IO->conn_fail);
750
751         if (IO->SendBuf.fd != 0)
752         {
753                 ev_io_stop(loop, &IO->conn_event);
754                 ev_io_stop(event_base, &IO->send_event);
755                 ev_io_stop(event_base, &IO->recv_event);
756                 ev_timer_stop (event_base, &IO->rw_timeout);
757                 close(IO->SendBuf.fd);
758                 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
759         }
760         become_session(IO->CitContext);
761
762         assert(IO->ConnFail);
763         switch (IO->ConnFail(IO))
764         {
765         case eAbort:
766                 ShutDownCLient(IO);
767         default:
768                 break;
769
770         }
771 }
772
773 static void
774 IO_connfailimmediate_callback(struct ev_loop *loop,
775                               ev_idle *watcher,
776                               int revents)
777 {
778         AsyncIO *IO = watcher->data;
779
780         SetEVState(IO, eIOConnfailNow);
781         IO->Now = ev_now(event_base);
782         ev_idle_stop (event_base, &IO->conn_fail_immediate);
783
784         if (IO->SendBuf.fd != 0)
785         {
786                 close(IO->SendBuf.fd);
787                 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
788         }
789         become_session(IO->CitContext);
790
791         assert(IO->ConnFail);
792         switch (IO->ConnFail(IO))
793         {
794         case eAbort:
795                 ShutDownCLient(IO);
796         default:
797                 break;
798
799         }
800 }
801
802 static void
803 IO_connestd_callback(struct ev_loop *loop, ev_io *watcher, int revents)
804 {
805         AsyncIO *IO = watcher->data;
806         int             so_err = 0;
807         socklen_t       lon = sizeof(so_err);
808         int             err;
809
810         SetEVState(IO, eIOConnNow);
811         IO->Now = ev_now(event_base);
812         EVM_syslog(LOG_DEBUG, "connect() succeeded.\n");
813
814         ev_io_stop(loop, &IO->conn_event);
815         ev_timer_stop(event_base, &IO->conn_fail);
816
817         err = getsockopt(IO->SendBuf.fd,
818                          SOL_SOCKET,
819                          SO_ERROR,
820                          (void*)&so_err,
821                          &lon);
822
823         if ((err == 0) && (so_err != 0))
824         {
825                 EV_syslog(LOG_DEBUG, "connect() failed [%d][%s]\n",
826                           so_err,
827                           strerror(so_err));
828                 IO_connfail_callback(loop, &IO->conn_fail, revents);
829
830         }
831         else
832         {
833                 EVM_syslog(LOG_DEBUG, "connect() succeeded\n");
834                 set_start_callback(loop, IO, revents);
835         }
836 }
837
838 static void
839 IO_recv_callback(struct ev_loop *loop, ev_io *watcher, int revents)
840 {
841         const char *errmsg;
842         ssize_t nbytes;
843         AsyncIO *IO = watcher->data;
844
845         IO->Now = ev_now(event_base);
846         switch (IO->NextState) {
847         case eReadFile:
848                 nbytes = FileRecvChunked(&IO->IOB, &errmsg);
849                 if (nbytes < 0)
850                         StrBufPlain(IO->ErrMsg, errmsg, -1);
851                 else
852                 {
853                         if (IO->IOB.ChunkSendRemain == 0)
854                         {
855                                 IO->NextState = eSendReply;
856                                 assert(IO->ReadDone);
857                                 ev_io_stop(event_base, &IO->recv_event);
858                                 PostInbound(IO);
859                                 return;
860                         }
861                         else
862                                 return;
863                 }
864                 break;
865         default:
866                 nbytes = StrBuf_read_one_chunk_callback(IO->RecvBuf.fd,
867                                                         0,
868                                                         &IO->RecvBuf);
869                 break;
870         }
871
872 #ifdef BIGBAD_IODBG
873         {
874                 long nbytes;
875                 int rv = 0;
876                 char fn [SIZ];
877                 FILE *fd;
878                 const char *pch = ChrPtr(IO->RecvBuf.Buf);
879                 const char *pchh = IO->RecvBuf.ReadWritePointer;
880
881                 if (pchh == NULL)
882                         pchh = pch;
883
884                 nbytes = StrLength(IO->RecvBuf.Buf) - (pchh - pch);
885                 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
886                          ((CitContext*)(IO->CitContext))->ServiceName,
887                          IO->SendBuf.fd);
888
889                 fd = fopen(fn, "a+");
890                 fprintf(fd, "Read: BufSize: %ld BufContent: [",
891                         nbytes);
892                 rv = fwrite(pchh, nbytes, 1, fd);
893                 if (!rv) printf("failed to write debug to %s!\n", fn);
894                 fprintf(fd, "]\n");
895                 fclose(fd);
896         }
897 #endif
898         if (nbytes > 0) {
899                 HandleInbound(IO);
900         } else if (nbytes == 0) {
901                 StopClientWatchers(IO, 1);
902                 SetNextTimeout(IO, 0.01);
903                 return;
904         } else if (nbytes == -1) {
905                 if (errno != EAGAIN) {
906                         // FD is gone. kick it. 
907                         StopClientWatchers(IO, 1);
908                         EV_syslog(LOG_DEBUG,
909                                   "IO_recv_callback(): Socket Invalid! [%d] [%s] [%d]\n",
910                                   errno, strerror(errno), IO->SendBuf.fd);
911                         StrBufPrintf(IO->ErrMsg,
912                                      "Socket Invalid! [%s]",
913                                      strerror(errno));
914                         SetNextTimeout(IO, 0.01);
915                 }
916                 return;
917         }
918 }
919
920 void
921 IO_postdns_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
922 {
923         AsyncIO *IO = watcher->data;
924
925         SetEVState(IO, eCaresFinished);
926         IO->Now = ev_now(event_base);
927         EV_syslog(LOG_DEBUG, "event: %s\n", __FUNCTION__);
928         become_session(IO->CitContext);
929         assert(IO->DNS.Query->PostDNS);
930         switch (IO->DNS.Query->PostDNS(IO))
931         {
932         case eAbort:
933                 assert(IO->DNS.Fail);
934                 switch (IO->DNS.Fail(IO)) {
935                 case eAbort:
936 ////                    StopClientWatchers(IO);
937                         ShutDownCLient(IO);
938                 default:
939                         break;
940                 }
941         default:
942                 break;
943         }
944 }
945
946
947 eNextState EvConnectSock(AsyncIO *IO,
948                          double conn_timeout,
949                          double first_rw_timeout,
950                          int ReadFirst)
951 {
952         struct sockaddr_in egress_sin;
953         int fdflags;
954         int rc = -1;
955
956         SetEVState(IO, eIOConnectSock);
957         become_session(IO->CitContext);
958
959         if (ReadFirst) {
960                 IO->NextState = eReadMessage;
961         }
962         else {
963                 IO->NextState = eSendReply;
964         }
965
966         IO->SendBuf.fd = IO->RecvBuf.fd =
967                 socket(
968                         (IO->ConnectMe->IPv6)?PF_INET6:PF_INET,
969                         SOCK_STREAM,
970                         IPPROTO_TCP);
971
972         if (IO->SendBuf.fd < 0) {
973                 EV_syslog(LOG_ERR,
974                           "EVENT: socket() failed: %s\n",
975                           strerror(errno));
976
977                 StrBufPrintf(IO->ErrMsg,
978                              "Failed to create socket: %s",
979                              strerror(errno));
980                 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
981                 return eAbort;
982         }
983         fdflags = fcntl(IO->SendBuf.fd, F_GETFL);
984         if (fdflags < 0) {
985                 EV_syslog(LOG_ERR,
986                           "EVENT: unable to get socket %d flags! %s \n",
987                           IO->SendBuf.fd,
988                           strerror(errno));
989                 StrBufPrintf(IO->ErrMsg,
990                              "Failed to get socket %d flags: %s",
991                              IO->SendBuf.fd,
992                              strerror(errno));
993                 close(IO->SendBuf.fd);
994                 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
995                 return eAbort;
996         }
997         fdflags = fdflags | O_NONBLOCK;
998         if (fcntl(IO->SendBuf.fd, F_SETFL, fdflags) < 0) {
999                 EV_syslog(
1000                         LOG_ERR,
1001                         "EVENT: unable to set socket %d nonblocking flags! %s \n",
1002                         IO->SendBuf.fd,
1003                         strerror(errno));
1004                 StrBufPrintf(IO->ErrMsg,
1005                              "Failed to set socket flags: %s",
1006                              strerror(errno));
1007                 close(IO->SendBuf.fd);
1008                 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
1009                 return eAbort;
1010         }
1011 /* TODO: maye we could use offsetof() to calc the position of data...
1012  * http://doc.dvgu.ru/devel/ev.html#associating_custom_data_with_a_watcher
1013  */
1014         ev_io_init(&IO->recv_event, IO_recv_callback, IO->RecvBuf.fd, EV_READ);
1015         IO->recv_event.data = IO;
1016         ev_io_init(&IO->send_event, IO_send_callback, IO->SendBuf.fd, EV_WRITE);
1017         IO->send_event.data = IO;
1018
1019         ev_timer_init(&IO->conn_fail, IO_connfail_callback, conn_timeout, 0);
1020         IO->conn_fail.data = IO;
1021         ev_timer_init(&IO->rw_timeout, IO_Timeout_callback, first_rw_timeout,0);
1022         IO->rw_timeout.data = IO;
1023
1024
1025
1026
1027         /* for debugging you may bypass it like this:
1028          * IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1029          * ((struct sockaddr_in)IO->ConnectMe->Addr).sin_addr.s_addr =
1030          *   inet_addr("127.0.0.1");
1031          */
1032         if (IO->ConnectMe->IPv6) {
1033                 rc = connect(IO->SendBuf.fd,
1034                              &IO->ConnectMe->Addr,
1035                              sizeof(struct sockaddr_in6));
1036         }
1037         else {
1038                 /* If citserver is bound to a specific IP address on the host, make
1039                  * sure we use that address for outbound connections.
1040                  */
1041         
1042                 memset(&egress_sin, 0, sizeof(egress_sin));
1043                 egress_sin.sin_family = AF_INET;
1044                 if (!IsEmptyStr(config.c_ip_addr)) {
1045                         egress_sin.sin_addr.s_addr = inet_addr(config.c_ip_addr);
1046                         if (egress_sin.sin_addr.s_addr == !INADDR_ANY) {
1047                                 egress_sin.sin_addr.s_addr = INADDR_ANY;
1048                         }
1049
1050                         /* If this bind fails, no problem; we can still use INADDR_ANY */
1051                         bind(IO->SendBuf.fd, (struct sockaddr *)&egress_sin, sizeof(egress_sin));
1052                 }
1053                 rc = connect(IO->SendBuf.fd,
1054                              (struct sockaddr_in *)&IO->ConnectMe->Addr,
1055                              sizeof(struct sockaddr_in));
1056         }
1057
1058         if (rc >= 0){
1059                 SetEVState(IO, eIOConnNow);
1060                 EV_syslog(LOG_DEBUG, "connect() = %d immediate success.\n", IO->SendBuf.fd);
1061                 set_start_callback(event_base, IO, 0);
1062                 return IO->NextState;
1063         }
1064         else if (errno == EINPROGRESS) {
1065                 SetEVState(IO, eIOConnWait);
1066                 EV_syslog(LOG_DEBUG, "connect() = %d have to wait now.\n", IO->SendBuf.fd);
1067
1068                 ev_io_init(&IO->conn_event,
1069                            IO_connestd_callback,
1070                            IO->SendBuf.fd,
1071                            EV_READ|EV_WRITE);
1072
1073                 IO->conn_event.data = IO;
1074
1075                 ev_io_start(event_base, &IO->conn_event);
1076                 ev_timer_start(event_base, &IO->conn_fail);
1077                 return IO->NextState;
1078         }
1079         else {
1080                 SetEVState(IO, eIOConnfail);
1081                 ev_idle_init(&IO->conn_fail_immediate,
1082                              IO_connfailimmediate_callback);
1083                 IO->conn_fail_immediate.data = IO;
1084                 ev_idle_start(event_base, &IO->conn_fail_immediate);
1085
1086                 EV_syslog(LOG_ERR,
1087                           "connect() = %d failed: %s\n",
1088                           IO->SendBuf.fd,
1089                           strerror(errno));
1090
1091                 StrBufPrintf(IO->ErrMsg,
1092                              "Failed to connect: %s",
1093                              strerror(errno));
1094                 return IO->NextState;
1095         }
1096         return IO->NextState;
1097 }
1098
1099 void SetNextTimeout(AsyncIO *IO, double timeout)
1100 {
1101         IO->rw_timeout.repeat = timeout;
1102         ev_timer_again (event_base,  &IO->rw_timeout);
1103 }
1104
1105
1106 eNextState ReAttachIO(AsyncIO *IO,
1107                       void *pData,
1108                       int ReadFirst)
1109 {
1110         SetEVState(IO, eIOAttach);
1111         IO->Data = pData;
1112         become_session(IO->CitContext);
1113         ev_cleanup_start(event_base, &IO->abort_by_shutdown);
1114         if (ReadFirst) {
1115                 IO->NextState = eReadMessage;
1116         }
1117         else {
1118                 IO->NextState = eSendReply;
1119         }
1120         set_start_callback(event_base, IO, 0);
1121
1122         return IO->NextState;
1123 }
1124
1125 void InitIOStruct(AsyncIO *IO,
1126                   void *Data,
1127                   eNextState NextState,
1128                   IO_LineReaderCallback LineReader,
1129                   IO_CallBack DNS_Fail,
1130                   IO_CallBack SendDone,
1131                   IO_CallBack ReadDone,
1132                   IO_CallBack Terminate,
1133                   IO_CallBack DBTerminate,
1134                   IO_CallBack ConnFail,
1135                   IO_CallBack Timeout,
1136                   IO_CallBack ShutdownAbort)
1137 {
1138         IO->Data          = Data;
1139
1140         IO->CitContext    = CloneContext(CC);
1141         IO->CitContext->session_specific_data = Data;
1142         IO->CitContext->IO = IO;
1143
1144         IO->NextState     = NextState;
1145
1146         IO->SendDone      = SendDone;
1147         IO->ReadDone      = ReadDone;
1148         IO->Terminate     = Terminate;
1149         IO->DBTerminate   = DBTerminate;
1150         IO->LineReader    = LineReader;
1151         IO->ConnFail      = ConnFail;
1152         IO->Timeout       = Timeout;
1153         IO->ShutdownAbort = ShutdownAbort;
1154
1155         IO->DNS.Fail      = DNS_Fail;
1156
1157         IO->SendBuf.Buf   = NewStrBufPlain(NULL, 1024);
1158         IO->RecvBuf.Buf   = NewStrBufPlain(NULL, 1024);
1159         IO->IOBuf         = NewStrBuf();
1160         EV_syslog(LOG_DEBUG,
1161                   "EVENT: Session lives at %p IO at %p \n",
1162                   Data, IO);
1163
1164 }
1165
1166 extern int evcurl_init(AsyncIO *IO);
1167
1168 int InitcURLIOStruct(AsyncIO *IO,
1169                      void *Data,
1170                      const char* Desc,
1171                      IO_CallBack SendDone,
1172                      IO_CallBack Terminate,
1173                      IO_CallBack DBTerminate,
1174                      IO_CallBack ShutdownAbort)
1175 {
1176         IO->Data          = Data;
1177
1178         IO->CitContext    = CloneContext(CC);
1179         IO->CitContext->session_specific_data = Data;
1180         IO->CitContext->IO = IO;
1181
1182         IO->SendDone      = SendDone;
1183         IO->Terminate     = Terminate;
1184         IO->DBTerminate   = DBTerminate;
1185         IO->ShutdownAbort = ShutdownAbort;
1186
1187         strcpy(IO->HttpReq.errdesc, Desc);
1188
1189
1190         return  evcurl_init(IO);
1191
1192 }
1193
1194
1195 typedef struct KillOtherSessionContext {
1196         AsyncIO IO;
1197         AsyncIO *OtherOne;
1198 }KillOtherSessionContext;
1199
1200 eNextState KillTerminate(AsyncIO *IO)
1201 {
1202         long id;
1203         KillOtherSessionContext *Ctx = (KillOtherSessionContext*)IO->Data;
1204         EV_syslog(LOG_DEBUG, "%s Exit\n", __FUNCTION__);
1205         id = IO->ID;
1206         FreeAsyncIOContents(IO);
1207         memset(Ctx, 0, sizeof(KillOtherSessionContext));
1208         IO->ID = id; /* just for the case we want to analyze it in a coredump */
1209         free(Ctx);
1210         return eAbort;
1211
1212 }
1213
1214 eNextState KillShutdown(AsyncIO *IO)
1215 {
1216         return eTerminateConnection;
1217 }
1218
1219 eNextState KillOtherContextNow(AsyncIO *IO)
1220 {
1221         KillOtherSessionContext *Ctx = IO->Data;
1222
1223         SetEVState(IO, eKill);
1224
1225         if (Ctx->OtherOne->ShutdownAbort != NULL)
1226                 Ctx->OtherOne->ShutdownAbort(Ctx->OtherOne);
1227         return eTerminateConnection;
1228 }
1229
1230 void KillAsyncIOContext(AsyncIO *IO)
1231 {
1232         KillOtherSessionContext *Ctx;
1233
1234         Ctx = (KillOtherSessionContext*) malloc(sizeof(KillOtherSessionContext));
1235         memset(Ctx, 0, sizeof(KillOtherSessionContext));
1236         
1237         InitIOStruct(&Ctx->IO,
1238                      Ctx,
1239                      eReadMessage,
1240                      NULL,
1241                      NULL,
1242                      NULL,
1243                      NULL,
1244                      KillTerminate,
1245                      NULL,
1246                      NULL,
1247                      NULL,
1248                      KillShutdown);
1249
1250         Ctx->OtherOne = IO;
1251
1252         switch(IO->NextState) {
1253         case eSendDNSQuery:
1254         case eReadDNSReply:
1255
1256         case eConnect:
1257         case eSendReply:
1258         case eSendMore:
1259         case eSendFile:
1260
1261         case eReadMessage:
1262         case eReadMore:
1263         case eReadPayload:
1264         case eReadFile:
1265                 QueueEventContext(&Ctx->IO, KillOtherContextNow);
1266                 break;
1267         case eDBQuery:
1268                 QueueDBOperation(&Ctx->IO, KillOtherContextNow);
1269                 break;
1270         case eTerminateConnection:
1271         case eAbort:
1272                 /*hm, its already dying, dunno which Queue its in... */
1273                 free(Ctx);
1274         }
1275         
1276 }
1277
1278 extern int DebugEventLoopBacktrace;
1279 void EV_backtrace(AsyncIO *IO)
1280 {
1281 #ifdef HAVE_BACKTRACE
1282         void *stack_frames[50];
1283         size_t size, i;
1284         char **strings;
1285
1286         if ((IO == NULL) || (DebugEventLoopBacktrace == 0))
1287                 return;
1288         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
1289         strings = backtrace_symbols(stack_frames, size);
1290         for (i = 0; i < size; i++) {
1291                 if (strings != NULL) {
1292                         EV_syslog(LOG_ALERT, " BT %s\n", strings[i]);
1293                 }
1294                 else {
1295                         EV_syslog(LOG_ALERT, " BT %p\n", stack_frames[i]);
1296                 }
1297         }
1298         free(strings);
1299 #endif
1300 }
1301
1302
1303 ev_tstamp ctdl_ev_now (void)
1304 {
1305         return ev_now(event_base);
1306 }