2 * Copyright (c) 1998-2012 by the citadel.org team
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.
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.
28 #include <sys/types.h>
31 #if TIME_WITH_SYS_TIME
32 # include <sys/time.h>
36 # include <sys/time.h>
45 #include <sys/socket.h>
46 #include <netinet/in.h>
48 #include <arpa/inet.h>
49 #include <libcitadel.h>
50 #include <curl/curl.h>
51 #include <curl/multi.h>
54 #include "citserver.h"
57 #include "ctdl_module.h"
59 #include "event_client.h"
60 #include "serv_curl.h"
63 int DebugEventLoop = 0;
64 int DebugEventLoopBacktrace = 0;
68 /*****************************************************************************
69 * libevent / curl integration *
70 *****************************************************************************/
73 sta = curl_multi_setopt(mhnd, (CURLMOPT_##s), (v)); \
75 syslog(LOG_ERR, "EVCURL: error setting option " \
76 #s " on curl multi handle: %s\n", \
77 curl_easy_strerror(sta)); \
82 #define DBGLOG(LEVEL) if ((LEVEL != LOG_DEBUG) || (DebugCurl != 0))
84 #define EVCURL_syslog(LEVEL, FORMAT, ...) \
85 DBGLOG (LEVEL) syslog(LEVEL, "EVCURL:IO[%ld]CC[%d] " FORMAT, IO->ID, CCID, __VA_ARGS__)
87 #define EVCURLM_syslog(LEVEL, FORMAT) \
88 DBGLOG (LEVEL) syslog(LEVEL, "EVCURL:IO[%ld]CC[%d] " FORMAT, IO->ID, CCID)
90 #define CURL_syslog(LEVEL, FORMAT, ...) \
91 DBGLOG (LEVEL) syslog(LEVEL, "CURL: " FORMAT, __VA_ARGS__)
93 #define CURLM_syslog(LEVEL, FORMAT) \
94 DBGLOG (LEVEL) syslog(LEVEL, "CURL: " FORMAT)
96 typedef struct _evcurl_global_data {
101 } evcurl_global_data;
104 evcurl_global_data global;
114 CURLM_syslog(LOG_DEBUG,
115 "gotstatus(): about to call curl_multi_info_read\n");
116 while ((msg = curl_multi_info_read(global.mhnd, &nmsg))) {
117 CURL_syslog(LOG_DEBUG,
118 "got curl multi_info message msg=%d\n",
121 if (CURLMSG_DONE == msg->msg) {
123 char *chandle = NULL;
129 chnd = msg->easy_handle;
130 sta = curl_easy_getinfo(chnd,
133 EVCURLM_syslog(LOG_DEBUG, "request complete\n");
135 EVCURL_syslog(LOG_ERR,
136 "error asking curl for private"
137 " cookie of curl handle: %s\n",
138 curl_easy_strerror(sta));
141 IO = (AsyncIO *)chandle;
143 IO->Now = ev_now(event_base);
145 ev_io_stop(event_base, &IO->recv_event);
146 ev_io_stop(event_base, &IO->send_event);
148 sta = msg->data.result;
150 EVCURL_syslog(LOG_ERR,
151 "error description: %s\n",
152 IO->HttpReq.errdesc);
153 EVCURL_syslog(LOG_ERR,
154 "error performing request: %s\n",
155 curl_easy_strerror(sta));
157 sta = curl_easy_getinfo(chnd,
158 CURLINFO_RESPONSE_CODE,
159 &IO->HttpReq.httpcode);
161 EVCURL_syslog(LOG_ERR,
162 "error asking curl for "
163 "response code from request: %s\n",
164 curl_easy_strerror(sta));
165 EVCURL_syslog(LOG_ERR,
166 "http response code was %ld\n",
167 (long)IO->HttpReq.httpcode);
170 curl_slist_free_all(IO->HttpReq.headers);
171 msta = curl_multi_remove_handle(global.mhnd, chnd);
173 EVCURL_syslog(LOG_ERR,
174 "warning problem detaching "
175 "completed handle from curl multi: "
177 curl_multi_strerror(msta));
179 ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
181 IO->HttpReq.attached = 0;
182 switch(IO->SendDone(IO))
185 curl_easy_cleanup(IO->HttpReq.chnd);
186 IO->HttpReq.chnd = NULL;
198 curl_easy_cleanup(IO->HttpReq.chnd);
199 IO->HttpReq.chnd = NULL;
201 case eTerminateConnection:
203 curl_easy_cleanup(IO->HttpReq.chnd);
204 IO->HttpReq.chnd = NULL;
205 FreeStrBuf(&IO->HttpReq.ReplyData);
206 FreeURL(&IO->ConnectMe);
207 RemoveContext(IO->CitContext);
215 stepmulti(void *data, curl_socket_t fd, int which)
217 int running_handles = 0;
220 msta = curl_multi_socket_action(global.mhnd,
225 CURLM_syslog(LOG_DEBUG, "stepmulti(): calling gotstatus()\n");
228 "error in curl processing events"
229 "on multi handle, fd %d: %s\n",
231 curl_multi_strerror(msta));
233 if (global.nrun != running_handles)
234 gotstatus(running_handles);
238 gottime(struct ev_loop *loop, ev_timer *timeev, int events)
240 CURLM_syslog(LOG_DEBUG, "EVCURL: waking up curl for timeout\n");
241 stepmulti(NULL, CURL_SOCKET_TIMEOUT, 0);
245 got_in(struct ev_loop *loop, ev_io *ioev, int events)
247 CURL_syslog(LOG_DEBUG,
248 "EVCURL: waking up curl for io on fd %d\n",
251 stepmulti(ioev->data, ioev->fd, CURL_CSELECT_IN);
255 got_out(struct ev_loop *loop, ev_io *ioev, int events)
257 CURL_syslog(LOG_DEBUG,
258 "waking up curl for io on fd %d\n",
261 stepmulti(ioev->data, ioev->fd, CURL_CSELECT_OUT);
265 gotdata(void *data, size_t size, size_t nmemb, void *cglobal) {
266 AsyncIO *IO = (AsyncIO*) cglobal;
268 if (IO->HttpReq.ReplyData == NULL)
270 IO->HttpReq.ReplyData = NewStrBufPlain(NULL, SIZ);
272 IO->Now = ev_now(event_base);
273 return CurlFillStrBuf_callback(data,
276 IO->HttpReq.ReplyData);
280 gotwatchtime(CURLM *multi, long tblock_ms, void *cglobal) {
281 CURL_syslog(LOG_DEBUG, "EVCURL: gotwatchtime called %ld ms\n", tblock_ms);
282 evcurl_global_data *global = cglobal;
283 ev_timer_stop(EV_DEFAULT, &global->timeev);
284 if (tblock_ms < 0 || 14000 < tblock_ms)
286 ev_timer_set(&global->timeev, 0.5e-3 + 1.0e-3 * tblock_ms, 14.0);
287 ev_timer_start(EV_DEFAULT_UC, &global->timeev);
288 curl_multi_perform(global, &global->nrun);
293 gotwatchsock(CURL *easy,
299 evcurl_global_data *global = cglobal;
300 CURLM *mhnd = global->mhnd;
302 AsyncIO *IO = (AsyncIO*) vIO;
307 sta = curl_easy_getinfo(easy, CURLINFO_PRIVATE, &f);
309 EVCURL_syslog(LOG_ERR,
310 "EVCURL: error asking curl for private "
311 "cookie of curl handle: %s\n",
312 curl_easy_strerror(sta));
316 EVCURL_syslog(LOG_DEBUG,
317 "EVCURL: got socket for URL: %s\n",
318 IO->ConnectMe->PlainUrl);
320 if (IO->SendBuf.fd != 0)
322 ev_io_stop(event_base, &IO->recv_event);
323 ev_io_stop(event_base, &IO->send_event);
326 ev_io_init(&IO->recv_event, &got_in, fd, EV_READ);
327 ev_io_init(&IO->send_event, &got_out, fd, EV_WRITE);
328 curl_multi_assign(mhnd, fd, IO);
331 IO->Now = ev_now(event_base);
337 Action = "CURL_POLL_NONE";
339 case CURL_POLL_REMOVE:
340 Action = "CURL_POLL_REMOVE";
343 Action = "CURL_POLL_IN";
346 Action = "CURL_POLL_OUT";
348 case CURL_POLL_INOUT:
349 Action = "CURL_POLL_INOUT";
354 EVCURL_syslog(LOG_DEBUG,
355 "EVCURL: gotwatchsock called fd=%d action=%s[%d]\n",
356 (int)fd, Action, action);
361 EVCURLM_syslog(LOG_ERR,
363 "to register this sockwatcker\n");
365 case CURL_POLL_REMOVE:
366 EVCURLM_syslog(LOG_ERR,
367 "called last time to unregister "
368 "this sockwatcher\n");
369 ev_io_stop(event_base, &IO->recv_event);
370 ev_io_stop(event_base, &IO->send_event);
373 ev_io_start(event_base, &IO->recv_event);
374 ev_io_stop(event_base, &IO->send_event);
377 ev_io_start(event_base, &IO->send_event);
378 ev_io_stop(event_base, &IO->recv_event);
380 case CURL_POLL_INOUT:
381 ev_io_start(event_base, &IO->send_event);
382 ev_io_start(event_base, &IO->recv_event);
388 void curl_init_connectionpool(void)
392 ev_timer_init(&global.timeev, &gottime, 14.0, 14.0);
393 global.timeev.data = (void *)&global;
395 CURLcode sta = curl_global_init(CURL_GLOBAL_ALL);
400 "error initializing curl library: %s\n",
401 curl_easy_strerror(sta));
405 mhnd = global.mhnd = curl_multi_init();
408 CURLM_syslog(LOG_ERR,
409 "error initializing curl multi handle\n");
413 MOPT(SOCKETFUNCTION, &gotwatchsock);
414 MOPT(SOCKETDATA, (void *)&global);
415 MOPT(TIMERFUNCTION, &gotwatchtime);
416 MOPT(TIMERDATA, (void *)&global);
421 int evcurl_init(AsyncIO *IO)
426 EVCURLM_syslog(LOG_DEBUG, "EVCURL: evcurl_init called ms\n");
427 IO->HttpReq.attached = 0;
428 chnd = IO->HttpReq.chnd = curl_easy_init();
431 EVCURLM_syslog(LOG_ERR, "EVCURL: error initializing curl handle\n");
436 OPT(VERBOSE, (long)1);
441 OPT(FAILONERROR, (long)1);
443 OPT(FOLLOWLOCATION, (long)0);
444 OPT(MAXREDIRS, (long)0);
445 OPT(USERAGENT, CITADEL);
447 OPT(TIMEOUT, (long)1800);
448 OPT(LOW_SPEED_LIMIT, (long)64);
449 OPT(LOW_SPEED_TIME, (long)600);
450 OPT(CONNECTTIMEOUT, (long)600);
451 OPT(PRIVATE, (void *)IO);
453 OPT(FORBID_REUSE, 1);
454 OPT(WRITEFUNCTION, &gotdata);
455 OPT(WRITEDATA, (void *)IO);
456 OPT(ERRORBUFFER, IO->HttpReq.errdesc);
458 if ((!IsEmptyStr(config.c_ip_addr))
459 && (strcmp(config.c_ip_addr, "*"))
460 && (strcmp(config.c_ip_addr, "::"))
461 && (strcmp(config.c_ip_addr, "0.0.0.0"))
464 OPT(INTERFACE, config.c_ip_addr);
467 #ifdef CURLOPT_HTTP_CONTENT_DECODING
468 OPT(HTTP_CONTENT_DECODING, 1);
472 IO->HttpReq.headers = curl_slist_append(IO->HttpReq.headers,
473 "Connection: close");
479 static void IOcurl_abort_shutdown_callback(struct ev_loop *loop,
484 AsyncIO *IO = watcher->data;
485 IO->Now = ev_now(event_base);
486 EVCURL_syslog(LOG_DEBUG, "EVENT Curl: %s\n", __FUNCTION__);
488 curl_slist_free_all(IO->HttpReq.headers);
489 msta = curl_multi_remove_handle(global.mhnd, IO->HttpReq.chnd);
492 EVCURL_syslog(LOG_ERR,
493 "EVCURL: warning problem detaching completed handle "
494 "from curl multi: %s\n",
495 curl_multi_strerror(msta));
498 curl_easy_cleanup(IO->HttpReq.chnd);
499 IO->HttpReq.chnd = NULL;
500 ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
501 ev_io_stop(event_base, &IO->recv_event);
502 ev_io_stop(event_base, &IO->send_event);
503 assert(IO->ShutdownAbort);
504 IO->ShutdownAbort(IO);
507 evcurl_handle_start(AsyncIO *IO)
513 chnd = IO->HttpReq.chnd;
514 EVCURL_syslog(LOG_DEBUG,
515 "EVCURL: Loading URL: %s\n", IO->ConnectMe->PlainUrl);
516 OPT(URL, IO->ConnectMe->PlainUrl);
517 if (StrLength(IO->ConnectMe->CurlCreds))
519 OPT(HTTPAUTH, (long)CURLAUTH_BASIC);
520 OPT(USERPWD, ChrPtr(IO->ConnectMe->CurlCreds));
522 if (StrLength(IO->HttpReq.PostData) > 0)
524 OPT(POSTFIELDS, ChrPtr(IO->HttpReq.PostData));
525 OPT(POSTFIELDSIZE, StrLength(IO->HttpReq.PostData));
528 else if ((IO->HttpReq.PlainPostDataLen != 0) &&
529 (IO->HttpReq.PlainPostData != NULL))
531 OPT(POSTFIELDS, IO->HttpReq.PlainPostData);
532 OPT(POSTFIELDSIZE, IO->HttpReq.PlainPostDataLen);
534 OPT(HTTPHEADER, IO->HttpReq.headers);
536 IO->NextState = eConnect;
537 EVCURLM_syslog(LOG_DEBUG, "EVCURL: attaching to curl multi handle\n");
538 msta = curl_multi_add_handle(global.mhnd, IO->HttpReq.chnd);
541 EVCURL_syslog(LOG_ERR,
542 "EVCURL: error attaching to curl multi handle: %s\n",
543 curl_multi_strerror(msta));
546 IO->HttpReq.attached = 1;
547 ev_async_send (event_base, &WakeupCurl);
548 ev_cleanup_init(&IO->abort_by_shutdown,
549 IOcurl_abort_shutdown_callback);
551 ev_cleanup_start(event_base, &IO->abort_by_shutdown);
555 static void WakeupCurlCallback(EV_P_ ev_async *w, int revents)
557 CURLM_syslog(LOG_DEBUG, "waking up curl multi handle\n");
559 curl_multi_perform(&global, CURL_POLL_NONE);
562 static void evcurl_shutdown (void)
564 curl_global_cleanup();
565 curl_multi_cleanup(global.mhnd);
566 CURLM_syslog(LOG_DEBUG, "exiting\n");
568 /*****************************************************************************
569 * libevent integration *
570 *****************************************************************************/
572 * client event queue plus its methods.
573 * this currently is the main loop (which may change in some future?)
575 int evbase_count = 0;
576 int event_add_pipe[2] = {-1, -1};
577 pthread_mutex_t EventQueueMutex; /* locks the access to the following vars: */
578 HashList *QueueEvents = NULL;
579 HashList *InboundEventQueue = NULL;
580 HashList *InboundEventQueues[2] = { NULL, NULL };
583 ev_async ExitEventLoop;
585 static void QueueEventAddCallback(EV_P_ ev_async *w, int revents)
594 /* get the control command... */
595 pthread_mutex_lock(&EventQueueMutex);
597 if (InboundEventQueues[0] == InboundEventQueue) {
598 InboundEventQueue = InboundEventQueues[1];
599 q = InboundEventQueues[0];
602 InboundEventQueue = InboundEventQueues[0];
603 q = InboundEventQueues[1];
605 pthread_mutex_unlock(&EventQueueMutex);
606 Now = ev_now (event_base);
607 It = GetNewHashPos(q, 0);
608 while (GetNextHashPos(q, It, &len, &Key, &v))
611 if (h->IO->ID == 0) {
612 h->IO->ID = EvIDSource++;
614 if (h->IO->StartIO == 0.0)
615 h->IO->StartIO = Now;
620 DeleteHashContent(&q);
621 syslog(LOG_DEBUG, "EVENT Q Add done.\n");
625 static void EventExitCallback(EV_P_ ev_async *w, int revents)
627 ev_break(event_base, EVBREAK_ALL);
629 syslog(LOG_DEBUG, "EVENT Q exiting.\n");
634 void InitEventQueue(void)
636 struct rlimit LimitSet;
638 pthread_mutex_init(&EventQueueMutex, NULL);
640 if (pipe(event_add_pipe) != 0) {
642 "Unable to create pipe for libev queueing: %s\n",
646 LimitSet.rlim_cur = 1;
647 LimitSet.rlim_max = 1;
648 setrlimit(event_add_pipe[1], &LimitSet);
650 QueueEvents = NewHash(1, Flathash);
651 InboundEventQueues[0] = NewHash(1, Flathash);
652 InboundEventQueues[1] = NewHash(1, Flathash);
653 InboundEventQueue = InboundEventQueues[0];
655 extern void CtdlDestroyEVCleanupHooks(void);
657 extern int EVQShutDown;
659 * this thread operates the select() etc. via libev.
661 void *client_event_thread(void *arg)
663 struct CitContext libev_client_CC;
665 CtdlFillSystemContext(&libev_client_CC, "LibEv Thread");
666 // citthread_setspecific(MyConKey, (void *)&smtp_queue_CC);
667 syslog(LOG_DEBUG, "client_event_thread() initializing\n");
669 event_base = ev_default_loop (EVFLAG_AUTO);
670 ev_async_init(&AddJob, QueueEventAddCallback);
671 ev_async_start(event_base, &AddJob);
672 ev_async_init(&ExitEventLoop, EventExitCallback);
673 ev_async_start(event_base, &ExitEventLoop);
674 ev_async_init(&WakeupCurl, WakeupCurlCallback);
675 ev_async_start(event_base, &WakeupCurl);
677 curl_init_connectionpool();
679 ev_run (event_base, 0);
681 syslog(LOG_DEBUG, "client_event_thread() exiting\n");
683 ///what todo here? CtdlClearSystemContext();
684 ev_loop_destroy (EV_DEFAULT_UC);
685 DeleteHash(&QueueEvents);
686 InboundEventQueue = NULL;
687 DeleteHash(&InboundEventQueues[0]);
688 DeleteHash(&InboundEventQueues[1]);
689 /* citthread_mutex_destroy(&EventQueueMutex); TODO */
691 close(event_add_pipe[0]);
692 close(event_add_pipe[1]);
694 CtdlDestroyEVCleanupHooks();
700 /*----------------------------------------------------------------------------*/
702 * DB-Queue; does async bdb operations.
703 * has its own set of handlers.
707 int evdb_add_pipe[2] = {-1, -1};
708 pthread_mutex_t DBEventQueueMutex; /* locks the access to the following vars: */
709 HashList *DBQueueEvents = NULL;
710 HashList *DBInboundEventQueue = NULL;
711 HashList *DBInboundEventQueues[2] = { NULL, NULL };
714 ev_async DBExitEventLoop;
716 extern void ShutDownDBCLient(AsyncIO *IO);
718 static void DBQueueEventAddCallback(EV_P_ ev_async *w, int revents)
727 /* get the control command... */
728 pthread_mutex_lock(&DBEventQueueMutex);
730 if (DBInboundEventQueues[0] == DBInboundEventQueue) {
731 DBInboundEventQueue = DBInboundEventQueues[1];
732 q = DBInboundEventQueues[0];
735 DBInboundEventQueue = DBInboundEventQueues[0];
736 q = DBInboundEventQueues[1];
738 pthread_mutex_unlock(&DBEventQueueMutex);
740 Now = ev_now (event_db);
741 It = GetNewHashPos(q, 0);
742 while (GetNextHashPos(q, It, &len, &Key, &v))
747 h->IO->ID = EvIDSource++;
748 if (h->IO->StartDB == 0.0)
749 h->IO->StartDB = Now;
751 rc = h->EvAttch(h->IO);
755 ShutDownDBCLient(h->IO);
761 DeleteHashContent(&q);
762 syslog(LOG_DEBUG, "DBEVENT Q Add done.\n");
766 static void DBEventExitCallback(EV_P_ ev_async *w, int revents)
768 syslog(LOG_DEBUG, "DB EVENT Q exiting.\n");
769 ev_break(event_db, EVBREAK_ALL);
774 void DBInitEventQueue(void)
776 struct rlimit LimitSet;
778 pthread_mutex_init(&DBEventQueueMutex, NULL);
780 if (pipe(evdb_add_pipe) != 0) {
781 syslog(LOG_EMERG, "Unable to create pipe for libev queueing: %s\n", strerror(errno));
784 LimitSet.rlim_cur = 1;
785 LimitSet.rlim_max = 1;
786 setrlimit(evdb_add_pipe[1], &LimitSet);
788 DBQueueEvents = NewHash(1, Flathash);
789 DBInboundEventQueues[0] = NewHash(1, Flathash);
790 DBInboundEventQueues[1] = NewHash(1, Flathash);
791 DBInboundEventQueue = DBInboundEventQueues[0];
795 * this thread operates writing to the message database via libev.
797 void *db_event_thread(void *arg)
799 struct CitContext libev_msg_CC;
801 CtdlFillSystemContext(&libev_msg_CC, "LibEv DB IO Thread");
802 // citthread_setspecific(MyConKey, (void *)&smtp_queue_CC);
803 syslog(LOG_DEBUG, "dbevent_thread() initializing\n");
805 event_db = ev_loop_new (EVFLAG_AUTO);
807 ev_async_init(&DBAddJob, DBQueueEventAddCallback);
808 ev_async_start(event_db, &DBAddJob);
809 ev_async_init(&DBExitEventLoop, DBEventExitCallback);
810 ev_async_start(event_db, &DBExitEventLoop);
812 ev_run (event_db, 0);
814 syslog(LOG_DEBUG, "dbevent_thread() exiting\n");
816 //// what to do here? CtdlClearSystemContext();
817 ev_loop_destroy (event_db);
819 DeleteHash(&DBQueueEvents);
820 DBInboundEventQueue = NULL;
821 DeleteHash(&DBInboundEventQueues[0]);
822 DeleteHash(&DBInboundEventQueues[1]);
824 close(evdb_add_pipe[0]);
825 close(evdb_add_pipe[1]);
826 /* citthread_mutex_destroy(&DBEventQueueMutex); TODO */
831 void ShutDownEventQueues(void)
833 syslog(LOG_DEBUG, "EVENT Qs triggering exits.\n");
835 pthread_mutex_lock(&DBEventQueueMutex);
836 ev_async_send (event_db, &DBExitEventLoop);
837 pthread_mutex_unlock(&DBEventQueueMutex);
839 pthread_mutex_lock(&EventQueueMutex);
840 ev_async_send (EV_DEFAULT_ &ExitEventLoop);
841 pthread_mutex_unlock(&EventQueueMutex);
844 void DebugEventloopEnable(void)
848 void DebugEventloopBacktraceEnable(void)
850 DebugEventLoopBacktrace = 1;
853 void DebugCurlEnable(void)
858 CTDL_MODULE_INIT(event_client)
862 CtdlRegisterDebugFlagHook(HKEY("eventloop"), DebugEventloopEnable);
863 CtdlRegisterDebugFlagHook(HKEY("eventloopbacktrace"), DebugEventloopBacktraceEnable);
864 CtdlRegisterDebugFlagHook(HKEY("curl"), DebugCurlEnable);
867 CtdlThreadCreate(client_event_thread);
868 CtdlThreadCreate(db_event_thread);