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 *****************************************************************************/
71 #define DBGLOG(LEVEL) if ((LEVEL != LOG_DEBUG) || (DebugCurl != 0))
73 #define EVCURL_syslog(LEVEL, FORMAT, ...) \
74 DBGLOG (LEVEL) syslog(LEVEL, "EVCURL:IO[%ld]CC[%d] " FORMAT, \
75 IO->ID, CCID, __VA_ARGS__)
77 #define EVCURLM_syslog(LEVEL, FORMAT) \
78 DBGLOG (LEVEL) syslog(LEVEL, "EVCURL:IO[%ld]CC[%d] " FORMAT, \
81 #define CURL_syslog(LEVEL, FORMAT, ...) \
82 DBGLOG (LEVEL) syslog(LEVEL, "CURL: " FORMAT, __VA_ARGS__)
84 #define CURLM_syslog(LEVEL, FORMAT) \
85 DBGLOG (LEVEL) syslog(LEVEL, "CURL: " FORMAT)
89 sta = curl_multi_setopt(mhnd, (CURLMOPT_##s), (v)); \
91 EVQ_syslog(LOG_ERR, "error setting option " \
92 #s " on curl multi handle: %s\n", \
93 curl_easy_strerror(sta)); \
99 typedef struct _evcurl_global_data {
104 } evcurl_global_data;
107 evcurl_global_data global;
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",
124 if (CURLMSG_DONE == msg->msg) {
126 char *chandle = NULL;
132 chnd = msg->easy_handle;
133 sta = curl_easy_getinfo(chnd,
137 EVCURL_syslog(LOG_ERR,
138 "error asking curl for private"
139 " cookie of curl handle: %s\n",
140 curl_easy_strerror(sta));
143 IO = (AsyncIO *)chandle;
145 EVCURLM_syslog(LOG_DEBUG, "request complete\n");
147 IO->Now = ev_now(event_base);
149 ev_io_stop(event_base, &IO->recv_event);
150 ev_io_stop(event_base, &IO->send_event);
152 sta = msg->data.result;
154 EVCURL_syslog(LOG_ERR,
155 "error description: %s\n",
156 IO->HttpReq.errdesc);
157 EVCURL_syslog(LOG_ERR,
158 "error performing request: %s\n",
159 curl_easy_strerror(sta));
161 sta = curl_easy_getinfo(chnd,
162 CURLINFO_RESPONSE_CODE,
163 &IO->HttpReq.httpcode);
165 EVCURL_syslog(LOG_ERR,
166 "error asking curl for "
167 "response code from request: %s\n",
168 curl_easy_strerror(sta));
169 EVCURL_syslog(LOG_ERR,
170 "http response code was %ld\n",
171 (long)IO->HttpReq.httpcode);
174 curl_slist_free_all(IO->HttpReq.headers);
175 msta = curl_multi_remove_handle(global.mhnd, chnd);
177 EVCURL_syslog(LOG_ERR,
178 "warning problem detaching "
179 "completed handle from curl multi: "
181 curl_multi_strerror(msta));
183 ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
185 IO->HttpReq.attached = 0;
186 switch(IO->SendDone(IO))
189 curl_easy_cleanup(IO->HttpReq.chnd);
190 IO->HttpReq.chnd = NULL;
202 curl_easy_cleanup(IO->HttpReq.chnd);
203 IO->HttpReq.chnd = NULL;
205 case eTerminateConnection:
207 curl_easy_cleanup(IO->HttpReq.chnd);
208 IO->HttpReq.chnd = NULL;
209 FreeStrBuf(&IO->HttpReq.ReplyData);
210 FreeURL(&IO->ConnectMe);
211 RemoveContext(IO->CitContext);
219 stepmulti(void *data, curl_socket_t fd, int which)
221 int running_handles = 0;
224 msta = curl_multi_socket_action(global.mhnd,
229 CURLM_syslog(LOG_DEBUG, "stepmulti(): calling gotstatus()\n");
232 "error in curl processing events"
233 "on multi handle, fd %d: %s\n",
235 curl_multi_strerror(msta));
237 if (global.nrun != running_handles)
238 gotstatus(running_handles);
242 gottime(struct ev_loop *loop, ev_timer *timeev, int events)
244 CURLM_syslog(LOG_DEBUG, "EVCURL: waking up curl for timeout\n");
245 stepmulti(NULL, CURL_SOCKET_TIMEOUT, 0);
249 got_in(struct ev_loop *loop, ev_io *ioev, int events)
251 CURL_syslog(LOG_DEBUG,
252 "EVCURL: waking up curl for io on fd %d\n",
255 stepmulti(ioev->data, ioev->fd, CURL_CSELECT_IN);
259 got_out(struct ev_loop *loop, ev_io *ioev, int events)
261 CURL_syslog(LOG_DEBUG,
262 "waking up curl for io on fd %d\n",
265 stepmulti(ioev->data, ioev->fd, CURL_CSELECT_OUT);
269 gotdata(void *data, size_t size, size_t nmemb, void *cglobal) {
270 AsyncIO *IO = (AsyncIO*) cglobal;
272 if (IO->HttpReq.ReplyData == NULL)
274 IO->HttpReq.ReplyData = NewStrBufPlain(NULL, SIZ);
276 IO->Now = ev_now(event_base);
277 return CurlFillStrBuf_callback(data,
280 IO->HttpReq.ReplyData);
284 gotwatchtime(CURLM *multi, long tblock_ms, void *cglobal) {
285 CURL_syslog(LOG_DEBUG, "EVCURL: gotwatchtime called %ld ms\n", tblock_ms);
286 evcurl_global_data *global = cglobal;
287 ev_timer_stop(EV_DEFAULT, &global->timeev);
288 if (tblock_ms < 0 || 14000 < tblock_ms)
290 ev_timer_set(&global->timeev, 0.5e-3 + 1.0e-3 * tblock_ms, 14.0);
291 ev_timer_start(EV_DEFAULT_UC, &global->timeev);
292 curl_multi_perform(global, &global->nrun);
297 gotwatchsock(CURL *easy,
303 evcurl_global_data *global = cglobal;
304 CURLM *mhnd = global->mhnd;
306 AsyncIO *IO = (AsyncIO*) vIO;
311 sta = curl_easy_getinfo(easy, CURLINFO_PRIVATE, &f);
313 EVCURL_syslog(LOG_ERR,
314 "EVCURL: error asking curl for private "
315 "cookie of curl handle: %s\n",
316 curl_easy_strerror(sta));
320 EVCURL_syslog(LOG_DEBUG,
321 "EVCURL: got socket for URL: %s\n",
322 IO->ConnectMe->PlainUrl);
324 if (IO->SendBuf.fd != 0)
326 ev_io_stop(event_base, &IO->recv_event);
327 ev_io_stop(event_base, &IO->send_event);
330 ev_io_init(&IO->recv_event, &got_in, fd, EV_READ);
331 ev_io_init(&IO->send_event, &got_out, fd, EV_WRITE);
332 curl_multi_assign(mhnd, fd, IO);
335 IO->Now = ev_now(event_base);
341 Action = "CURL_POLL_NONE";
343 case CURL_POLL_REMOVE:
344 Action = "CURL_POLL_REMOVE";
347 Action = "CURL_POLL_IN";
350 Action = "CURL_POLL_OUT";
352 case CURL_POLL_INOUT:
353 Action = "CURL_POLL_INOUT";
358 EVCURL_syslog(LOG_DEBUG,
359 "EVCURL: gotwatchsock called fd=%d action=%s[%d]\n",
360 (int)fd, Action, action);
365 EVCURLM_syslog(LOG_DEBUG,
367 "to register this sockwatcker\n");
369 case CURL_POLL_REMOVE:
370 EVCURLM_syslog(LOG_DEBUG,
371 "called last time to unregister "
372 "this sockwatcher\n");
373 ev_io_stop(event_base, &IO->recv_event);
374 ev_io_stop(event_base, &IO->send_event);
377 ev_io_start(event_base, &IO->recv_event);
378 ev_io_stop(event_base, &IO->send_event);
381 ev_io_start(event_base, &IO->send_event);
382 ev_io_stop(event_base, &IO->recv_event);
384 case CURL_POLL_INOUT:
385 ev_io_start(event_base, &IO->send_event);
386 ev_io_start(event_base, &IO->recv_event);
392 void curl_init_connectionpool(void)
396 ev_timer_init(&global.timeev, &gottime, 14.0, 14.0);
397 global.timeev.data = (void *)&global;
399 CURLcode sta = curl_global_init(CURL_GLOBAL_ALL);
404 "error initializing curl library: %s\n",
405 curl_easy_strerror(sta));
409 mhnd = global.mhnd = curl_multi_init();
412 CURLM_syslog(LOG_ERR,
413 "error initializing curl multi handle\n");
417 MOPT(SOCKETFUNCTION, &gotwatchsock);
418 MOPT(SOCKETDATA, (void *)&global);
419 MOPT(TIMERFUNCTION, &gotwatchtime);
420 MOPT(TIMERDATA, (void *)&global);
425 int evcurl_init(AsyncIO *IO)
430 EVCURLM_syslog(LOG_DEBUG, "EVCURL: evcurl_init called ms\n");
431 IO->HttpReq.attached = 0;
432 chnd = IO->HttpReq.chnd = curl_easy_init();
435 EVCURLM_syslog(LOG_ERR, "EVCURL: error initializing curl handle\n");
440 OPT(VERBOSE, (long)1);
445 OPT(FAILONERROR, (long)1);
447 OPT(FOLLOWLOCATION, (long)0);
448 OPT(MAXREDIRS, (long)0);
449 OPT(USERAGENT, CITADEL);
451 OPT(TIMEOUT, (long)1800);
452 OPT(LOW_SPEED_LIMIT, (long)64);
453 OPT(LOW_SPEED_TIME, (long)600);
454 OPT(CONNECTTIMEOUT, (long)600);
455 OPT(PRIVATE, (void *)IO);
457 OPT(FORBID_REUSE, 1);
458 OPT(WRITEFUNCTION, &gotdata);
459 OPT(WRITEDATA, (void *)IO);
460 OPT(ERRORBUFFER, IO->HttpReq.errdesc);
462 if ((!IsEmptyStr(config.c_ip_addr))
463 && (strcmp(config.c_ip_addr, "*"))
464 && (strcmp(config.c_ip_addr, "::"))
465 && (strcmp(config.c_ip_addr, "0.0.0.0"))
468 OPT(INTERFACE, config.c_ip_addr);
471 #ifdef CURLOPT_HTTP_CONTENT_DECODING
472 OPT(HTTP_CONTENT_DECODING, 1);
476 IO->HttpReq.headers = curl_slist_append(IO->HttpReq.headers,
477 "Connection: close");
483 static void IOcurl_abort_shutdown_callback(struct ev_loop *loop,
488 AsyncIO *IO = watcher->data;
489 IO->Now = ev_now(event_base);
490 EVCURL_syslog(LOG_DEBUG, "EVENT Curl: %s\n", __FUNCTION__);
492 curl_slist_free_all(IO->HttpReq.headers);
493 msta = curl_multi_remove_handle(global.mhnd, IO->HttpReq.chnd);
496 EVCURL_syslog(LOG_ERR,
497 "EVCURL: warning problem detaching completed handle "
498 "from curl multi: %s\n",
499 curl_multi_strerror(msta));
502 curl_easy_cleanup(IO->HttpReq.chnd);
503 IO->HttpReq.chnd = NULL;
504 ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
505 ev_io_stop(event_base, &IO->recv_event);
506 ev_io_stop(event_base, &IO->send_event);
507 assert(IO->ShutdownAbort);
508 IO->ShutdownAbort(IO);
511 evcurl_handle_start(AsyncIO *IO)
517 chnd = IO->HttpReq.chnd;
518 EVCURL_syslog(LOG_DEBUG,
519 "EVCURL: Loading URL: %s\n", IO->ConnectMe->PlainUrl);
520 OPT(URL, IO->ConnectMe->PlainUrl);
521 if (StrLength(IO->ConnectMe->CurlCreds))
523 OPT(HTTPAUTH, (long)CURLAUTH_BASIC);
524 OPT(USERPWD, ChrPtr(IO->ConnectMe->CurlCreds));
526 if (StrLength(IO->HttpReq.PostData) > 0)
528 OPT(POSTFIELDS, ChrPtr(IO->HttpReq.PostData));
529 OPT(POSTFIELDSIZE, StrLength(IO->HttpReq.PostData));
532 else if ((IO->HttpReq.PlainPostDataLen != 0) &&
533 (IO->HttpReq.PlainPostData != NULL))
535 OPT(POSTFIELDS, IO->HttpReq.PlainPostData);
536 OPT(POSTFIELDSIZE, IO->HttpReq.PlainPostDataLen);
538 OPT(HTTPHEADER, IO->HttpReq.headers);
540 IO->NextState = eConnect;
541 EVCURLM_syslog(LOG_DEBUG, "EVCURL: attaching to curl multi handle\n");
542 msta = curl_multi_add_handle(global.mhnd, IO->HttpReq.chnd);
545 EVCURL_syslog(LOG_ERR,
546 "EVCURL: error attaching to curl multi handle: %s\n",
547 curl_multi_strerror(msta));
550 IO->HttpReq.attached = 1;
551 ev_async_send (event_base, &WakeupCurl);
552 ev_cleanup_init(&IO->abort_by_shutdown,
553 IOcurl_abort_shutdown_callback);
555 ev_cleanup_start(event_base, &IO->abort_by_shutdown);
559 static void WakeupCurlCallback(EV_P_ ev_async *w, int revents)
561 CURLM_syslog(LOG_DEBUG, "waking up curl multi handle\n");
563 curl_multi_perform(&global, CURL_POLL_NONE);
566 static void evcurl_shutdown (void)
568 curl_global_cleanup();
569 curl_multi_cleanup(global.mhnd);
570 CURLM_syslog(LOG_DEBUG, "exiting\n");
572 /*****************************************************************************
573 * libevent integration *
574 *****************************************************************************/
576 * client event queue plus its methods.
577 * this currently is the main loop (which may change in some future?)
579 int evbase_count = 0;
580 int event_add_pipe[2] = {-1, -1};
581 pthread_mutex_t EventQueueMutex; /* locks the access to the following vars: */
582 HashList *QueueEvents = NULL;
583 HashList *InboundEventQueue = NULL;
584 HashList *InboundEventQueues[2] = { NULL, NULL };
587 ev_async ExitEventLoop;
589 static void QueueEventAddCallback(EV_P_ ev_async *w, int revents)
598 /* get the control command... */
599 pthread_mutex_lock(&EventQueueMutex);
601 if (InboundEventQueues[0] == InboundEventQueue) {
602 InboundEventQueue = InboundEventQueues[1];
603 q = InboundEventQueues[0];
606 InboundEventQueue = InboundEventQueues[0];
607 q = InboundEventQueues[1];
609 pthread_mutex_unlock(&EventQueueMutex);
610 Now = ev_now (event_base);
611 It = GetNewHashPos(q, 0);
612 while (GetNextHashPos(q, It, &len, &Key, &v))
615 if (h->IO->ID == 0) {
616 h->IO->ID = EvIDSource++;
618 if (h->IO->StartIO == 0.0)
619 h->IO->StartIO = Now;
624 DeleteHashContent(&q);
625 EVQM_syslog(LOG_DEBUG, "EVENT Q Add done.\n");
629 static void EventExitCallback(EV_P_ ev_async *w, int revents)
631 ev_break(event_base, EVBREAK_ALL);
633 EVQM_syslog(LOG_DEBUG, "EVENT Q exiting.\n");
638 void InitEventQueue(void)
640 struct rlimit LimitSet;
642 pthread_mutex_init(&EventQueueMutex, NULL);
644 if (pipe(event_add_pipe) != 0) {
646 "Unable to create pipe for libev queueing: %s\n",
650 LimitSet.rlim_cur = 1;
651 LimitSet.rlim_max = 1;
652 setrlimit(event_add_pipe[1], &LimitSet);
654 QueueEvents = NewHash(1, Flathash);
655 InboundEventQueues[0] = NewHash(1, Flathash);
656 InboundEventQueues[1] = NewHash(1, Flathash);
657 InboundEventQueue = InboundEventQueues[0];
659 extern void CtdlDestroyEVCleanupHooks(void);
661 extern int EVQShutDown;
663 * this thread operates the select() etc. via libev.
665 void *client_event_thread(void *arg)
667 struct CitContext libev_client_CC;
669 CtdlFillSystemContext(&libev_client_CC, "LibEv Thread");
670 // citthread_setspecific(MyConKey, (void *)&smtp_queue_CC);
671 EVQM_syslog(LOG_DEBUG, "client_event_thread() initializing\n");
673 event_base = ev_default_loop (EVFLAG_AUTO);
674 ev_async_init(&AddJob, QueueEventAddCallback);
675 ev_async_start(event_base, &AddJob);
676 ev_async_init(&ExitEventLoop, EventExitCallback);
677 ev_async_start(event_base, &ExitEventLoop);
678 ev_async_init(&WakeupCurl, WakeupCurlCallback);
679 ev_async_start(event_base, &WakeupCurl);
681 curl_init_connectionpool();
683 ev_run (event_base, 0);
685 EVQM_syslog(LOG_DEBUG, "client_event_thread() exiting\n");
687 ///what todo here? CtdlClearSystemContext();
688 ev_loop_destroy (EV_DEFAULT_UC);
689 DeleteHash(&QueueEvents);
690 InboundEventQueue = NULL;
691 DeleteHash(&InboundEventQueues[0]);
692 DeleteHash(&InboundEventQueues[1]);
693 /* citthread_mutex_destroy(&EventQueueMutex); TODO */
695 close(event_add_pipe[0]);
696 close(event_add_pipe[1]);
698 CtdlDestroyEVCleanupHooks();
704 /*----------------------------------------------------------------------------*/
706 * DB-Queue; does async bdb operations.
707 * has its own set of handlers.
711 int evdb_add_pipe[2] = {-1, -1};
712 pthread_mutex_t DBEventQueueMutex; /* locks the access to the following vars: */
713 HashList *DBQueueEvents = NULL;
714 HashList *DBInboundEventQueue = NULL;
715 HashList *DBInboundEventQueues[2] = { NULL, NULL };
718 ev_async DBExitEventLoop;
720 extern void ShutDownDBCLient(AsyncIO *IO);
722 static void DBQueueEventAddCallback(EV_P_ ev_async *w, int revents)
731 /* get the control command... */
732 pthread_mutex_lock(&DBEventQueueMutex);
734 if (DBInboundEventQueues[0] == DBInboundEventQueue) {
735 DBInboundEventQueue = DBInboundEventQueues[1];
736 q = DBInboundEventQueues[0];
739 DBInboundEventQueue = DBInboundEventQueues[0];
740 q = DBInboundEventQueues[1];
742 pthread_mutex_unlock(&DBEventQueueMutex);
744 Now = ev_now (event_db);
745 It = GetNewHashPos(q, 0);
746 while (GetNextHashPos(q, It, &len, &Key, &v))
751 h->IO->ID = EvIDSource++;
752 if (h->IO->StartDB == 0.0)
753 h->IO->StartDB = Now;
755 rc = h->EvAttch(h->IO);
759 ShutDownDBCLient(h->IO);
765 DeleteHashContent(&q);
766 EVQM_syslog(LOG_DEBUG, "DBEVENT Q Add done.\n");
770 static void DBEventExitCallback(EV_P_ ev_async *w, int revents)
772 EVQM_syslog(LOG_DEBUG, "DB EVENT Q exiting.\n");
773 ev_break(event_db, EVBREAK_ALL);
778 void DBInitEventQueue(void)
780 struct rlimit LimitSet;
782 pthread_mutex_init(&DBEventQueueMutex, NULL);
784 if (pipe(evdb_add_pipe) != 0) {
785 EVQ_syslog(LOG_EMERG, "Unable to create pipe for libev queueing: %s\n", strerror(errno));
788 LimitSet.rlim_cur = 1;
789 LimitSet.rlim_max = 1;
790 setrlimit(evdb_add_pipe[1], &LimitSet);
792 DBQueueEvents = NewHash(1, Flathash);
793 DBInboundEventQueues[0] = NewHash(1, Flathash);
794 DBInboundEventQueues[1] = NewHash(1, Flathash);
795 DBInboundEventQueue = DBInboundEventQueues[0];
799 * this thread operates writing to the message database via libev.
801 void *db_event_thread(void *arg)
803 struct CitContext libev_msg_CC;
805 CtdlFillSystemContext(&libev_msg_CC, "LibEv DB IO Thread");
806 // citthread_setspecific(MyConKey, (void *)&smtp_queue_CC);
807 EVQM_syslog(LOG_DEBUG, "dbevent_thread() initializing\n");
809 event_db = ev_loop_new (EVFLAG_AUTO);
811 ev_async_init(&DBAddJob, DBQueueEventAddCallback);
812 ev_async_start(event_db, &DBAddJob);
813 ev_async_init(&DBExitEventLoop, DBEventExitCallback);
814 ev_async_start(event_db, &DBExitEventLoop);
816 ev_run (event_db, 0);
818 EVQM_syslog(LOG_DEBUG, "dbevent_thread() exiting\n");
820 //// what to do here? CtdlClearSystemContext();
821 ev_loop_destroy (event_db);
823 DeleteHash(&DBQueueEvents);
824 DBInboundEventQueue = NULL;
825 DeleteHash(&DBInboundEventQueues[0]);
826 DeleteHash(&DBInboundEventQueues[1]);
828 close(evdb_add_pipe[0]);
829 close(evdb_add_pipe[1]);
830 /* citthread_mutex_destroy(&DBEventQueueMutex); TODO */
835 void ShutDownEventQueues(void)
837 EVQM_syslog(LOG_DEBUG, "EVENT Qs triggering exits.\n");
839 pthread_mutex_lock(&DBEventQueueMutex);
840 ev_async_send (event_db, &DBExitEventLoop);
841 pthread_mutex_unlock(&DBEventQueueMutex);
843 pthread_mutex_lock(&EventQueueMutex);
844 ev_async_send (EV_DEFAULT_ &ExitEventLoop);
845 pthread_mutex_unlock(&EventQueueMutex);
848 void DebugEventloopEnable(const int n)
852 void DebugEventloopBacktraceEnable(const int n)
854 DebugEventLoopBacktrace = n;
857 void DebugCurlEnable(const int n)
862 CTDL_MODULE_INIT(event_client)
866 CtdlRegisterDebugFlagHook(HKEY("eventloop"), DebugEventloopEnable, &DebugEventLoop);
867 CtdlRegisterDebugFlagHook(HKEY("eventloopbacktrace"), DebugEventloopBacktraceEnable, &DebugEventLoopBacktrace);
868 CtdlRegisterDebugFlagHook(HKEY("curl"), DebugCurlEnable, &DebugCurl);
871 CtdlThreadCreate(client_event_thread);
872 CtdlThreadCreate(db_event_thread);