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