79b0eeb303d15dbba8bb2e6c17572574b8f9d308
[citadel.git] / citadel / modules / eventclient / serv_eventclient.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  *  
8  *
9  *  This program is distributed in the hope that it will be useful,
10  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *  GNU General Public License for more details.
13  *
14  *  
15  *  
16  *  
17  */
18
19 #include "sysdep.h"
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include <stdio.h>
23 #include <termios.h>
24 #include <fcntl.h>
25 #include <signal.h>
26 #include <pwd.h>
27 #include <errno.h>
28 #include <sys/types.h>
29 #include <syslog.h>
30
31 #if TIME_WITH_SYS_TIME
32 # include <sys/time.h>
33 # include <time.h>
34 #else
35 # if HAVE_SYS_TIME_H
36 #  include <sys/time.h>
37 # else
38 #  include <time.h>
39 # endif
40 #endif
41 #include <sys/wait.h>
42 #include <ctype.h>
43 #include <string.h>
44 #include <limits.h>
45 #include <sys/socket.h>
46 #include <netinet/in.h>
47 #include <assert.h>
48 #include <arpa/inet.h>
49 #include <libcitadel.h>
50 #include <curl/curl.h>
51 #include <curl/multi.h>
52 #include "citadel.h"
53 #include "server.h"
54 #include "citserver.h"
55 #include "support.h"
56
57 #include "ctdl_module.h"
58
59 #include "event_client.h"
60 #include "serv_curl.h"
61
62 ev_loop *event_base;
63 int DebugEventLoop = 0;
64 int DebugEventLoopBacktrace = 0;
65 int DebugCurl = 0;
66
67 long EvIDSource = 1;
68 /*****************************************************************************
69  *                   libevent / curl integration                             *
70  *****************************************************************************/
71 #define DBGLOG(LEVEL) if ((LEVEL != LOG_DEBUG) || (DebugCurl != 0))
72
73 #define EVCURL_syslog(LEVEL, FORMAT, ...)                               \
74         DBGLOG (LEVEL) syslog(LEVEL, "EVCURL:IO[%ld]CC[%d] " FORMAT,    \
75                               IO->ID, CCID, __VA_ARGS__)
76
77 #define EVCURLM_syslog(LEVEL, FORMAT)                                   \
78         DBGLOG (LEVEL) syslog(LEVEL, "EVCURL:IO[%ld]CC[%d] " FORMAT,    \
79                               IO->ID, CCID)
80
81 #define CURL_syslog(LEVEL, FORMAT, ...)                                 \
82         DBGLOG (LEVEL) syslog(LEVEL, "CURL: " FORMAT, __VA_ARGS__)
83
84 #define CURLM_syslog(LEVEL, FORMAT)                     \
85         DBGLOG (LEVEL) syslog(LEVEL, "CURL: " FORMAT)
86
87 #define MOPT(s, v)                                                      \
88         do {                                                            \
89                 sta = curl_multi_setopt(mhnd, (CURLMOPT_##s), (v));     \
90                 if (sta) {                                              \
91                         EVQ_syslog(LOG_ERR, "error setting option "     \
92                                #s " on curl multi handle: %s\n",        \
93                                curl_easy_strerror(sta));                \
94                         exit (1);                                       \
95                 }                                                       \
96         } while (0)
97
98
99 typedef struct _evcurl_global_data {
100         int magic;
101         CURLM *mhnd;
102         ev_timer timeev;
103         int nrun;
104 } evcurl_global_data;
105
106 ev_async WakeupCurl;
107 evcurl_global_data global;
108
109 static void
110 gotstatus(int nnrun)
111 {
112         CURLMsg *msg;
113         int nmsg;
114
115         global.nrun = nnrun;
116
117         CURLM_syslog(LOG_DEBUG,
118                      "gotstatus(): about to call curl_multi_info_read\n");
119         while ((msg = curl_multi_info_read(global.mhnd, &nmsg))) {
120                 CURL_syslog(LOG_DEBUG,
121                             "got curl multi_info message msg=%d\n",
122                             msg->msg);
123
124                 if (CURLMSG_DONE == msg->msg) {
125                         CURL *chnd;
126                         char *chandle = NULL;
127                         CURLcode sta;
128                         CURLMcode msta;
129                         AsyncIO*IO;
130
131                         chandle = NULL;;
132                         chnd = msg->easy_handle;
133                         sta = curl_easy_getinfo(chnd,
134                                                 CURLINFO_PRIVATE,
135                                                 &chandle);
136                         if (sta) {
137                                 syslog(LOG_ERR,
138                                        "error asking curl for private"
139                                        " cookie of curl handle: %s\n",
140                                        curl_easy_strerror(sta));
141                                 continue;
142                         }
143                         IO = (AsyncIO *)chandle;
144                         if (IO->ID == 0) {
145                                 EVCURL_syslog(LOG_ERR,
146                                               "Error, invalid IO context %p\n",
147                                               IO);
148                                 continue;
149                         }
150                         SetEVState(IO, eCurlGotStatus);
151
152                         EVCURLM_syslog(LOG_DEBUG, "request complete\n");
153
154                         IO->Now = ev_now(event_base);
155
156                         ev_io_stop(event_base, &IO->recv_event);
157                         ev_io_stop(event_base, &IO->send_event);
158
159                         sta = msg->data.result;
160                         if (sta) {
161                                 EVCURL_syslog(LOG_ERR,
162                                               "error description: %s\n",
163                                               IO->HttpReq.errdesc);
164                                 IO->HttpReq.CurlError = curl_easy_strerror(sta);
165                                 EVCURL_syslog(LOG_ERR,
166                                               "error performing request: %s\n",
167                                               IO->HttpReq.CurlError);
168                                 if (sta == CURLE_OPERATION_TIMEDOUT)
169                                 {
170                                         IO->SendBuf.fd = 0;
171                                         IO->RecvBuf.fd = 0;
172                                 }
173                         }
174                         sta = curl_easy_getinfo(chnd,
175                                                 CURLINFO_RESPONSE_CODE,
176                                                 &IO->HttpReq.httpcode);
177                         if (sta)
178                                 EVCURL_syslog(LOG_ERR,
179                                               "error asking curl for "
180                                               "response code from request: %s\n",
181                                               curl_easy_strerror(sta));
182                         EVCURL_syslog(LOG_DEBUG,
183                                       "http response code was %ld\n",
184                                       (long)IO->HttpReq.httpcode);
185
186
187                         curl_slist_free_all(IO->HttpReq.headers);
188                         msta = curl_multi_remove_handle(global.mhnd, chnd);
189                         if (msta)
190                                 EVCURL_syslog(LOG_ERR,
191                                               "warning problem detaching "
192                                               "completed handle from curl multi: "
193                                               "%s\n",
194                                               curl_multi_strerror(msta));
195
196                         ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
197
198                         IO->HttpReq.attached = 0;
199                         switch(IO->SendDone(IO))
200                         {
201                         case eDBQuery:
202                         case eSendDNSQuery:
203                         case eReadDNSReply:
204                         case eConnect:
205                         case eSendReply:
206                         case eSendMore:
207                         case eSendFile:
208                         case eReadMessage:
209                         case eReadMore:
210                         case eReadPayload:
211                         case eReadFile:
212                                 break;
213                         case eTerminateConnection:
214                         case eAbort:
215                                 curl_easy_cleanup(IO->HttpReq.chnd);
216                                 IO->HttpReq.chnd = NULL;
217                                 FreeStrBuf(&IO->HttpReq.ReplyData);
218                                 FreeURL(&IO->ConnectMe);
219                                 RemoveContext(IO->CitContext);
220                                 IO->Terminate(IO);
221                         }
222                 }
223         }
224 }
225
226 static void
227 stepmulti(void *data, curl_socket_t fd, int which)
228 {
229         int running_handles = 0;
230         CURLMcode msta;
231
232         msta = curl_multi_socket_action(global.mhnd,
233                                         fd,
234                                         which,
235                                         &running_handles);
236
237         CURLM_syslog(LOG_DEBUG, "stepmulti(): calling gotstatus()\n");
238         if (msta)
239                 CURL_syslog(LOG_ERR,
240                             "error in curl processing events"
241                             "on multi handle, fd %d: %s\n",
242                             (int)fd,
243                             curl_multi_strerror(msta));
244
245         if (global.nrun != running_handles)
246                 gotstatus(running_handles);
247 }
248
249 static void
250 gottime(struct ev_loop *loop, ev_timer *timeev, int events)
251 {
252         CURLM_syslog(LOG_DEBUG, "EVCURL: waking up curl for timeout\n");
253         stepmulti(NULL, CURL_SOCKET_TIMEOUT, 0);
254 }
255
256 static void
257 got_in(struct ev_loop *loop, ev_io *ioev, int events)
258 {
259         CURL_syslog(LOG_DEBUG,
260                     "EVCURL: waking up curl for io on fd %d\n",
261                     (int)ioev->fd);
262
263         stepmulti(ioev->data, ioev->fd, CURL_CSELECT_IN);
264 }
265
266 static void
267 got_out(struct ev_loop *loop, ev_io *ioev, int events)
268 {
269         CURL_syslog(LOG_DEBUG,
270                     "waking up curl for io on fd %d\n",
271                     (int)ioev->fd);
272
273         stepmulti(ioev->data, ioev->fd, CURL_CSELECT_OUT);
274 }
275
276 static size_t
277 gotdata(void *data, size_t size, size_t nmemb, void *cglobal)
278 {
279         AsyncIO *IO = (AsyncIO*) cglobal;
280
281         SetEVState(IO, eCurlGotData);
282         if (IO->HttpReq.ReplyData == NULL)
283         {
284                 IO->HttpReq.ReplyData = NewStrBufPlain(NULL, SIZ);
285         }
286         IO->Now = ev_now(event_base);
287         return CurlFillStrBuf_callback(data,
288                                        size,
289                                        nmemb,
290                                        IO->HttpReq.ReplyData);
291 }
292
293 static int
294 gotwatchtime(CURLM *multi, long tblock_ms, void *cglobal) {
295         CURL_syslog(LOG_DEBUG, "EVCURL: gotwatchtime called %ld ms\n", tblock_ms);
296         evcurl_global_data *global = cglobal;
297         ev_timer_stop(EV_DEFAULT, &global->timeev);
298         if (tblock_ms < 0 || 14000 < tblock_ms)
299                 tblock_ms = 14000;
300         ev_timer_set(&global->timeev, 0.5e-3 + 1.0e-3 * tblock_ms, 14.0);
301         ev_timer_start(EV_DEFAULT_UC, &global->timeev);
302         curl_multi_perform(global, &global->nrun);
303         return 0;
304 }
305
306 static int
307 gotwatchsock(CURL *easy,
308              curl_socket_t fd,
309              int action,
310              void *cglobal,
311              void *vIO)
312 {
313         evcurl_global_data *global = cglobal;
314         CURLM *mhnd = global->mhnd;
315         char *f;
316         AsyncIO *IO = (AsyncIO*) vIO;
317         CURLcode sta;
318         const char *Action;
319
320         if (IO == NULL) {
321                 sta = curl_easy_getinfo(easy, CURLINFO_PRIVATE, &f);
322                 if (sta) {
323                         CURL_syslog(LOG_ERR,
324                                     "EVCURL: error asking curl for private "
325                                     "cookie of curl handle: %s\n",
326                                     curl_easy_strerror(sta));
327                         return -1;
328                 }
329                 IO = (AsyncIO *) f;
330                 SetEVState(IO, eCurlNewIO);
331                 EVCURL_syslog(LOG_DEBUG,
332                               "EVCURL: got socket for URL: %s\n",
333                               IO->ConnectMe->PlainUrl);
334
335                 if (IO->SendBuf.fd != 0)
336                 {
337                         ev_io_stop(event_base, &IO->recv_event);
338                         ev_io_stop(event_base, &IO->send_event);
339                 }
340                 IO->SendBuf.fd = fd;
341                 ev_io_init(&IO->recv_event, &got_in, fd, EV_READ);
342                 ev_io_init(&IO->send_event, &got_out, fd, EV_WRITE);
343                 curl_multi_assign(mhnd, fd, IO);
344         }
345
346         SetEVState(IO, eCurlGotIO);
347         IO->Now = ev_now(event_base);
348
349         Action = "";
350         switch (action)
351         {
352         case CURL_POLL_NONE:
353                 Action = "CURL_POLL_NONE";
354                 break;
355         case CURL_POLL_REMOVE:
356                 Action = "CURL_POLL_REMOVE";
357                 break;
358         case CURL_POLL_IN:
359                 Action = "CURL_POLL_IN";
360                 break;
361         case CURL_POLL_OUT:
362                 Action = "CURL_POLL_OUT";
363                 break;
364         case CURL_POLL_INOUT:
365                 Action = "CURL_POLL_INOUT";
366                 break;
367         }
368
369
370         EVCURL_syslog(LOG_DEBUG,
371                       "EVCURL: gotwatchsock called fd=%d action=%s[%d]\n",
372                       (int)fd, Action, action);
373
374         switch (action)
375         {
376         case CURL_POLL_NONE:
377                 EVCURLM_syslog(LOG_DEBUG,
378                                "called first time "
379                                "to register this sockwatcker\n");
380                 break;
381         case CURL_POLL_REMOVE:
382                 EVCURLM_syslog(LOG_DEBUG,
383                                "called last time to unregister "
384                                "this sockwatcher\n");
385                 ev_io_stop(event_base, &IO->recv_event);
386                 ev_io_stop(event_base, &IO->send_event);
387                 break;
388         case CURL_POLL_IN:
389                 ev_io_start(event_base, &IO->recv_event);
390                 ev_io_stop(event_base, &IO->send_event);
391                 break;
392         case CURL_POLL_OUT:
393                 ev_io_start(event_base, &IO->send_event);
394                 ev_io_stop(event_base, &IO->recv_event);
395                 break;
396         case CURL_POLL_INOUT:
397                 ev_io_start(event_base, &IO->send_event);
398                 ev_io_start(event_base, &IO->recv_event);
399                 break;
400         }
401         return 0;
402 }
403
404 void curl_init_connectionpool(void)
405 {
406         CURLM *mhnd ;
407
408         ev_timer_init(&global.timeev, &gottime, 14.0, 14.0);
409         global.timeev.data = (void *)&global;
410         global.nrun = -1;
411         CURLcode sta = curl_global_init(CURL_GLOBAL_ALL);
412
413         if (sta)
414         {
415                 CURL_syslog(LOG_ERR,
416                             "error initializing curl library: %s\n",
417                             curl_easy_strerror(sta));
418
419                 exit(1);
420         }
421         mhnd = global.mhnd = curl_multi_init();
422         if (!mhnd)
423         {
424                 CURLM_syslog(LOG_ERR,
425                              "error initializing curl multi handle\n");
426                 exit(3);
427         }
428
429         MOPT(SOCKETFUNCTION, &gotwatchsock);
430         MOPT(SOCKETDATA, (void *)&global);
431         MOPT(TIMERFUNCTION, &gotwatchtime);
432         MOPT(TIMERDATA, (void *)&global);
433
434         return;
435 }
436
437 int evcurl_init(AsyncIO *IO)
438 {
439         CURLcode sta;
440         CURL *chnd;
441
442         EVCURLM_syslog(LOG_DEBUG, "EVCURL: evcurl_init called ms\n");
443         IO->HttpReq.attached = 0;
444         chnd = IO->HttpReq.chnd = curl_easy_init();
445         if (!chnd)
446         {
447                 EVCURLM_syslog(LOG_ERR, "EVCURL: error initializing curl handle\n");
448                 return 0;
449         }
450
451 #if DEBUG
452         OPT(VERBOSE, (long)1);
453 #endif
454         OPT(NOPROGRESS, 1L);
455
456         OPT(NOSIGNAL, 1L);
457         OPT(FAILONERROR, (long)1);
458         OPT(ENCODING, "");
459         OPT(FOLLOWLOCATION, (long)0);
460         OPT(MAXREDIRS, (long)0);
461         OPT(USERAGENT, CITADEL);
462
463         OPT(TIMEOUT, (long)1800);
464         OPT(LOW_SPEED_LIMIT, (long)64);
465         OPT(LOW_SPEED_TIME, (long)600);
466         OPT(CONNECTTIMEOUT, (long)600);
467         OPT(PRIVATE, (void *)IO);
468
469         OPT(FORBID_REUSE, 1);
470         OPT(WRITEFUNCTION, &gotdata);
471         OPT(WRITEDATA, (void *)IO);
472         OPT(ERRORBUFFER, IO->HttpReq.errdesc);
473
474         if ((!IsEmptyStr(config.c_ip_addr))
475                 && (strcmp(config.c_ip_addr, "*"))
476                 && (strcmp(config.c_ip_addr, "::"))
477                 && (strcmp(config.c_ip_addr, "0.0.0.0"))
478                 )
479         {
480                 OPT(INTERFACE, config.c_ip_addr);
481         }
482
483 #ifdef CURLOPT_HTTP_CONTENT_DECODING
484         OPT(HTTP_CONTENT_DECODING, 1);
485         OPT(ENCODING, "");
486 #endif
487
488         IO->HttpReq.headers = curl_slist_append(IO->HttpReq.headers,
489                                                 "Connection: close");
490
491         return 1;
492 }
493
494
495 static void IOcurl_abort_shutdown_callback(struct ev_loop *loop,
496                                            ev_cleanup *watcher,
497                                            int revents)
498 {
499         CURLMcode msta;
500         AsyncIO *IO = watcher->data;
501
502         if (IO == NULL)
503                 return;
504
505         SetEVState(IO, eCurlShutdown);
506         IO->Now = ev_now(event_base);
507         EVCURL_syslog(LOG_DEBUG, "EVENT Curl: %s\n", __FUNCTION__);
508
509         curl_slist_free_all(IO->HttpReq.headers);
510         msta = curl_multi_remove_handle(global.mhnd, IO->HttpReq.chnd);
511         if (msta)
512         {
513                 EVCURL_syslog(LOG_ERR,
514                               "EVCURL: warning problem detaching completed handle "
515                               "from curl multi: %s\n",
516                               curl_multi_strerror(msta));
517         }
518
519         curl_easy_cleanup(IO->HttpReq.chnd);
520         IO->HttpReq.chnd = NULL;
521         ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
522         ev_io_stop(event_base, &IO->recv_event);
523         ev_io_stop(event_base, &IO->send_event);
524         assert(IO->ShutdownAbort);
525         IO->ShutdownAbort(IO);
526 }
527 eNextState
528 evcurl_handle_start(AsyncIO *IO)
529 {
530         CURLMcode msta;
531         CURLcode sta;
532         CURL *chnd;
533
534         SetEVState(IO, eCurlStart);
535         chnd = IO->HttpReq.chnd;
536         EVCURL_syslog(LOG_DEBUG,
537                   "EVCURL: Loading URL: %s\n", IO->ConnectMe->PlainUrl);
538         OPT(URL, IO->ConnectMe->PlainUrl);
539         if (StrLength(IO->ConnectMe->CurlCreds))
540         {
541                 OPT(HTTPAUTH, (long)CURLAUTH_BASIC);
542                 OPT(USERPWD, ChrPtr(IO->ConnectMe->CurlCreds));
543         }
544         if (StrLength(IO->HttpReq.PostData) > 0)
545         {
546                 OPT(POSTFIELDS, ChrPtr(IO->HttpReq.PostData));
547                 OPT(POSTFIELDSIZE, StrLength(IO->HttpReq.PostData));
548
549         }
550         else if ((IO->HttpReq.PlainPostDataLen != 0) &&
551                  (IO->HttpReq.PlainPostData != NULL))
552         {
553                 OPT(POSTFIELDS, IO->HttpReq.PlainPostData);
554                 OPT(POSTFIELDSIZE, IO->HttpReq.PlainPostDataLen);
555         }
556         OPT(HTTPHEADER, IO->HttpReq.headers);
557
558         IO->NextState = eConnect;
559         EVCURLM_syslog(LOG_DEBUG, "EVCURL: attaching to curl multi handle\n");
560         msta = curl_multi_add_handle(global.mhnd, IO->HttpReq.chnd);
561         if (msta)
562         {
563                 EVCURL_syslog(LOG_ERR,
564                           "EVCURL: error attaching to curl multi handle: %s\n",
565                           curl_multi_strerror(msta));
566         }
567
568         IO->HttpReq.attached = 1;
569         ev_async_send (event_base, &WakeupCurl);
570
571         ev_cleanup_init(&IO->abort_by_shutdown,
572                         IOcurl_abort_shutdown_callback);
573
574         ev_cleanup_start(event_base, &IO->abort_by_shutdown);
575
576         return eReadMessage;
577 }
578
579 static void WakeupCurlCallback(EV_P_ ev_async *w, int revents)
580 {
581         CURLM_syslog(LOG_DEBUG, "waking up curl multi handle\n");
582
583         curl_multi_perform(&global, CURL_POLL_NONE);
584 }
585
586 static void evcurl_shutdown (void)
587 {
588         curl_global_cleanup();
589         curl_multi_cleanup(global.mhnd);
590         CURLM_syslog(LOG_DEBUG, "exiting\n");
591 }
592 /*****************************************************************************
593  *                       libevent integration                                *
594  *****************************************************************************/
595 /*
596  * client event queue plus its methods.
597  * this currently is the main loop (which may change in some future?)
598  */
599 int evbase_count = 0;
600 pthread_mutex_t EventQueueMutex; /* locks the access to the following vars: */
601 pthread_mutex_t EventExitQueueMutex; /* locks the access to the event queue pointer on exit. */
602 HashList *QueueEvents = NULL;
603 HashList *InboundEventQueue = NULL;
604 HashList *InboundEventQueues[2] = { NULL, NULL };
605 extern void ShutDownCLient(AsyncIO *IO);
606
607 ev_async AddJob;
608 ev_async ExitEventLoop;
609
610 static void QueueEventAddCallback(EV_P_ ev_async *w, int revents)
611 {
612         CitContext *Ctx;
613         ev_tstamp Now;
614         HashList *q;
615         void *v;
616         HashPos*It;
617         long len;
618         const char *Key;
619
620         /* get the control command... */
621         pthread_mutex_lock(&EventQueueMutex);
622
623         if (InboundEventQueues[0] == InboundEventQueue) {
624                 InboundEventQueue = InboundEventQueues[1];
625                 q = InboundEventQueues[0];
626         }
627         else {
628                 InboundEventQueue = InboundEventQueues[0];
629                 q = InboundEventQueues[1];
630         }
631         pthread_mutex_unlock(&EventQueueMutex);
632         Now = ev_now (event_base);
633         It = GetNewHashPos(q, 0);
634         while (GetNextHashPos(q, It, &len, &Key, &v))
635         {
636                 IOAddHandler *h = v;
637                 if (h->IO->ID == 0) {
638                         h->IO->ID = EvIDSource++;
639                 }
640                 if (h->IO->StartIO == 0.0)
641                         h->IO->StartIO = Now;
642
643                 SetEVState(h->IO, eIOAttach);
644
645                 Ctx = h->IO->CitContext;
646                 become_session(Ctx);
647
648                 h->IO->Now = Now;
649                 switch (h->EvAttch(h->IO))
650                 {
651                 case eReadMore:
652                 case eReadMessage:
653                 case eReadFile:
654                 case eSendReply:
655                 case eSendMore:
656                 case eReadPayload:
657                 case eSendFile:
658                 case eDBQuery:
659                 case eSendDNSQuery:
660                 case eReadDNSReply:
661                 case eConnect:
662                         break;
663                 case eTerminateConnection:
664                 case eAbort:
665                         ShutDownCLient(h->IO);
666                 break;
667                 }
668         }
669         DeleteHashPos(&It);
670         DeleteHashContent(&q);
671         EVQM_syslog(LOG_DEBUG, "EVENT Q Add done.\n");
672 }
673
674
675 static void EventExitCallback(EV_P_ ev_async *w, int revents)
676 {
677         ev_break(event_base, EVBREAK_ALL);
678
679         EVQM_syslog(LOG_DEBUG, "EVENT Q exiting.\n");
680 }
681
682
683
684 void InitEventQueue(void)
685 {
686         pthread_mutex_init(&EventQueueMutex, NULL);
687         pthread_mutex_init(&EventExitQueueMutex, NULL);
688
689         QueueEvents = NewHash(1, Flathash);
690         InboundEventQueues[0] = NewHash(1, Flathash);
691         InboundEventQueues[1] = NewHash(1, Flathash);
692         InboundEventQueue = InboundEventQueues[0];
693 }
694 extern void CtdlDestroyEVCleanupHooks(void);
695
696 extern int EVQShutDown;
697 /*
698  * this thread operates the select() etc. via libev.
699  */
700 void *client_event_thread(void *arg) 
701 {
702         struct CitContext libev_client_CC;
703
704         CtdlFillSystemContext(&libev_client_CC, "LibEv Thread");
705 //      citthread_setspecific(MyConKey, (void *)&smtp_queue_CC);
706         EVQM_syslog(LOG_DEBUG, "client_event_thread() initializing\n");
707
708         event_base = ev_default_loop (EVFLAG_AUTO);
709         ev_async_init(&AddJob, QueueEventAddCallback);
710         ev_async_start(event_base, &AddJob);
711         ev_async_init(&ExitEventLoop, EventExitCallback);
712         ev_async_start(event_base, &ExitEventLoop);
713         ev_async_init(&WakeupCurl, WakeupCurlCallback);
714         ev_async_start(event_base, &WakeupCurl);
715
716         curl_init_connectionpool();
717
718         ev_run (event_base, 0);
719
720         EVQM_syslog(LOG_DEBUG, "client_event_thread() exiting\n");
721
722 ///what todo here?      CtdlClearSystemContext();
723         pthread_mutex_lock(&EventExitQueueMutex);
724         ev_loop_destroy (EV_DEFAULT_UC);
725         event_base = NULL;
726         DeleteHash(&QueueEvents);
727         InboundEventQueue = NULL;
728         DeleteHash(&InboundEventQueues[0]);
729         DeleteHash(&InboundEventQueues[1]);
730 /*      citthread_mutex_destroy(&EventQueueMutex); TODO */
731         evcurl_shutdown();
732
733         CtdlDestroyEVCleanupHooks();
734
735         pthread_mutex_unlock(&EventExitQueueMutex);
736         EVQShutDown = 1;
737         return(NULL);
738 }
739
740 /*----------------------------------------------------------------------------*/
741 /*
742  * DB-Queue; does async bdb operations.
743  * has its own set of handlers.
744  */
745 ev_loop *event_db;
746 int evdb_count = 0;
747 pthread_mutex_t DBEventQueueMutex; /* locks the access to the following vars: */
748 pthread_mutex_t DBEventExitQueueMutex; /* locks the access to the db-event queue pointer on exit. */
749 HashList *DBQueueEvents = NULL;
750 HashList *DBInboundEventQueue = NULL;
751 HashList *DBInboundEventQueues[2] = { NULL, NULL };
752
753 ev_async DBAddJob;
754 ev_async DBExitEventLoop;
755
756 extern void ShutDownDBCLient(AsyncIO *IO);
757
758 static void DBQueueEventAddCallback(EV_P_ ev_async *w, int revents)
759 {
760         CitContext *Ctx;
761         ev_tstamp Now;
762         HashList *q;
763         void *v;
764         HashPos *It;
765         long len;
766         const char *Key;
767
768         /* get the control command... */
769         pthread_mutex_lock(&DBEventQueueMutex);
770
771         if (DBInboundEventQueues[0] == DBInboundEventQueue) {
772                 DBInboundEventQueue = DBInboundEventQueues[1];
773                 q = DBInboundEventQueues[0];
774         }
775         else {
776                 DBInboundEventQueue = DBInboundEventQueues[0];
777                 q = DBInboundEventQueues[1];
778         }
779         pthread_mutex_unlock(&DBEventQueueMutex);
780
781         Now = ev_now (event_db);
782         It = GetNewHashPos(q, 0);
783         while (GetNextHashPos(q, It, &len, &Key, &v))
784         {
785                 IOAddHandler *h = v;
786                 eNextState rc;
787                 if (h->IO->ID == 0)
788                         h->IO->ID = EvIDSource++;
789                 if (h->IO->StartDB == 0.0)
790                         h->IO->StartDB = Now;
791                 h->IO->Now = Now;
792
793                 SetEVState(h->IO, eDBAttach);
794                 Ctx = h->IO->CitContext;
795                 become_session(Ctx);
796                 ev_cleanup_start(event_db, &h->IO->db_abort_by_shutdown);
797                 rc = h->EvAttch(h->IO);
798                 switch (rc)
799                 {
800                 case eAbort:
801                         ShutDownDBCLient(h->IO);
802                 default:
803                         break;
804                 }
805         }
806         DeleteHashPos(&It);
807         DeleteHashContent(&q);
808         EVQM_syslog(LOG_DEBUG, "DBEVENT Q Add done.\n");
809 }
810
811
812 static void DBEventExitCallback(EV_P_ ev_async *w, int revents)
813 {
814         EVQM_syslog(LOG_DEBUG, "DB EVENT Q exiting.\n");
815         ev_break(event_db, EVBREAK_ALL);
816 }
817
818
819
820 void DBInitEventQueue(void)
821 {
822         pthread_mutex_init(&DBEventQueueMutex, NULL);
823         pthread_mutex_init(&DBEventExitQueueMutex, NULL);
824
825         DBQueueEvents = NewHash(1, Flathash);
826         DBInboundEventQueues[0] = NewHash(1, Flathash);
827         DBInboundEventQueues[1] = NewHash(1, Flathash);
828         DBInboundEventQueue = DBInboundEventQueues[0];
829 }
830
831 /*
832  * this thread operates writing to the message database via libev.
833  */
834 void *db_event_thread(void *arg)
835 {
836         ev_loop *tmp;
837         struct CitContext libev_msg_CC;
838
839         CtdlFillSystemContext(&libev_msg_CC, "LibEv DB IO Thread");
840
841         EVQM_syslog(LOG_DEBUG, "dbevent_thread() initializing\n");
842
843         tmp = event_db = ev_loop_new (EVFLAG_AUTO);
844
845         ev_async_init(&DBAddJob, DBQueueEventAddCallback);
846         ev_async_start(event_db, &DBAddJob);
847         ev_async_init(&DBExitEventLoop, DBEventExitCallback);
848         ev_async_start(event_db, &DBExitEventLoop);
849
850         ev_run (event_db, 0);
851
852         pthread_mutex_lock(&DBEventExitQueueMutex);
853
854         event_db = NULL;
855         EVQM_syslog(LOG_INFO, "dbevent_thread() exiting\n");
856
857         DeleteHash(&DBQueueEvents);
858         DBInboundEventQueue = NULL;
859         DeleteHash(&DBInboundEventQueues[0]);
860         DeleteHash(&DBInboundEventQueues[1]);
861
862 /*      citthread_mutex_destroy(&DBEventQueueMutex); TODO */
863
864         ev_loop_destroy (tmp);
865         pthread_mutex_unlock(&DBEventExitQueueMutex);
866         return(NULL);
867 }
868
869 void ShutDownEventQueues(void)
870 {
871         EVQM_syslog(LOG_DEBUG, "EVENT Qs triggering exits.\n");
872
873         pthread_mutex_lock(&DBEventQueueMutex);
874         ev_async_send (event_db, &DBExitEventLoop);
875         pthread_mutex_unlock(&DBEventQueueMutex);
876
877         pthread_mutex_lock(&EventQueueMutex);
878         ev_async_send (EV_DEFAULT_ &ExitEventLoop);
879         pthread_mutex_unlock(&EventQueueMutex);
880 }
881
882 void DebugEventloopEnable(const int n)
883 {
884         DebugEventLoop = n;
885 }
886 void DebugEventloopBacktraceEnable(const int n)
887 {
888         DebugEventLoopBacktrace = n;
889 }
890
891 void DebugCurlEnable(const int n)
892 {
893         DebugCurl = n;
894 }
895
896 CTDL_MODULE_INIT(event_client)
897 {
898         if (!threading)
899         {
900                 CtdlRegisterDebugFlagHook(HKEY("eventloop"), DebugEventloopEnable, &DebugEventLoop);
901                 CtdlRegisterDebugFlagHook(HKEY("eventloopbacktrace"), DebugEventloopBacktraceEnable, &DebugEventLoopBacktrace);
902                 CtdlRegisterDebugFlagHook(HKEY("curl"), DebugCurlEnable, &DebugCurl);
903                 InitEventQueue();
904                 DBInitEventQueue();
905                 CtdlThreadCreate(client_event_thread);
906                 CtdlThreadCreate(db_event_thread);
907         }
908         return "event";
909 }