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