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,
138 "error asking curl for private"
139 " cookie of curl handle: %s\n",
140 curl_easy_strerror(sta));
143 IO = (AsyncIO *)chandle;
145 EVCURL_syslog(LOG_ERR,
146 "Error, invalid IO context %p\n",
150 SetEVState(IO, eCurlGotStatus);
152 EVCURLM_syslog(LOG_DEBUG, "request complete\n");
154 IO->Now = ev_now(event_base);
156 ev_io_stop(event_base, &IO->recv_event);
157 ev_io_stop(event_base, &IO->send_event);
159 sta = msg->data.result;
161 EVCURL_syslog(LOG_ERR,
162 "error description: %s\n",
163 IO->HttpReq.errdesc);
164 IO->HttpReq.CurlError = curl_easy_strerror(sta);
165 EVCURL_syslog(LOG_ERR,
166 "error performing request: %s\n",
167 IO->HttpReq.CurlError);
168 if (sta == CURLE_OPERATION_TIMEDOUT)
174 sta = curl_easy_getinfo(chnd,
175 CURLINFO_RESPONSE_CODE,
176 &IO->HttpReq.httpcode);
178 EVCURL_syslog(LOG_ERR,
179 "error asking curl for "
180 "response code from request: %s\n",
181 curl_easy_strerror(sta));
182 EVCURL_syslog(LOG_DEBUG,
183 "http response code was %ld\n",
184 (long)IO->HttpReq.httpcode);
187 curl_slist_free_all(IO->HttpReq.headers);
188 msta = curl_multi_remove_handle(global.mhnd, chnd);
190 EVCURL_syslog(LOG_ERR,
191 "warning problem detaching "
192 "completed handle from curl multi: "
194 curl_multi_strerror(msta));
196 ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
198 IO->HttpReq.attached = 0;
199 switch(IO->SendDone(IO))
213 case eTerminateConnection:
215 curl_easy_cleanup(IO->HttpReq.chnd);
216 IO->HttpReq.chnd = NULL;
217 FreeStrBuf(&IO->HttpReq.ReplyData);
218 FreeURL(&IO->ConnectMe);
219 RemoveContext(IO->CitContext);
227 stepmulti(void *data, curl_socket_t fd, int which)
229 int running_handles = 0;
232 msta = curl_multi_socket_action(global.mhnd,
237 CURLM_syslog(LOG_DEBUG, "stepmulti(): calling gotstatus()\n");
240 "error in curl processing events"
241 "on multi handle, fd %d: %s\n",
243 curl_multi_strerror(msta));
245 if (global.nrun != running_handles)
246 gotstatus(running_handles);
250 gottime(struct ev_loop *loop, ev_timer *timeev, int events)
252 CURLM_syslog(LOG_DEBUG, "EVCURL: waking up curl for timeout\n");
253 stepmulti(NULL, CURL_SOCKET_TIMEOUT, 0);
257 got_in(struct ev_loop *loop, ev_io *ioev, int events)
259 CURL_syslog(LOG_DEBUG,
260 "EVCURL: waking up curl for io on fd %d\n",
263 stepmulti(ioev->data, ioev->fd, CURL_CSELECT_IN);
267 got_out(struct ev_loop *loop, ev_io *ioev, int events)
269 CURL_syslog(LOG_DEBUG,
270 "waking up curl for io on fd %d\n",
273 stepmulti(ioev->data, ioev->fd, CURL_CSELECT_OUT);
277 gotdata(void *data, size_t size, size_t nmemb, void *cglobal)
279 AsyncIO *IO = (AsyncIO*) cglobal;
281 SetEVState(IO, eCurlGotData);
282 if (IO->HttpReq.ReplyData == NULL)
284 IO->HttpReq.ReplyData = NewStrBufPlain(NULL, SIZ);
286 IO->Now = ev_now(event_base);
287 return CurlFillStrBuf_callback(data,
290 IO->HttpReq.ReplyData);
294 gotwatchtime(CURLM *multi, long tblock_ms, void *cglobal) {
295 CURL_syslog(LOG_DEBUG, "EVCURL: gotwatchtime called %ld ms\n", tblock_ms);
296 evcurl_global_data *global = cglobal;
297 ev_timer_stop(EV_DEFAULT, &global->timeev);
298 if (tblock_ms < 0 || 14000 < tblock_ms)
300 ev_timer_set(&global->timeev, 0.5e-3 + 1.0e-3 * tblock_ms, 14.0);
301 ev_timer_start(EV_DEFAULT_UC, &global->timeev);
302 curl_multi_perform(global, &global->nrun);
307 gotwatchsock(CURL *easy,
313 evcurl_global_data *global = cglobal;
314 CURLM *mhnd = global->mhnd;
316 AsyncIO *IO = (AsyncIO*) vIO;
321 sta = curl_easy_getinfo(easy, CURLINFO_PRIVATE, &f);
324 "EVCURL: error asking curl for private "
325 "cookie of curl handle: %s\n",
326 curl_easy_strerror(sta));
330 SetEVState(IO, eCurlNewIO);
331 EVCURL_syslog(LOG_DEBUG,
332 "EVCURL: got socket for URL: %s\n",
333 IO->ConnectMe->PlainUrl);
335 if (IO->SendBuf.fd != 0)
337 ev_io_stop(event_base, &IO->recv_event);
338 ev_io_stop(event_base, &IO->send_event);
341 ev_io_init(&IO->recv_event, &got_in, fd, EV_READ);
342 ev_io_init(&IO->send_event, &got_out, fd, EV_WRITE);
343 curl_multi_assign(mhnd, fd, IO);
346 SetEVState(IO, eCurlGotIO);
347 IO->Now = ev_now(event_base);
353 Action = "CURL_POLL_NONE";
355 case CURL_POLL_REMOVE:
356 Action = "CURL_POLL_REMOVE";
359 Action = "CURL_POLL_IN";
362 Action = "CURL_POLL_OUT";
364 case CURL_POLL_INOUT:
365 Action = "CURL_POLL_INOUT";
370 EVCURL_syslog(LOG_DEBUG,
371 "EVCURL: gotwatchsock called fd=%d action=%s[%d]\n",
372 (int)fd, Action, action);
377 EVCURLM_syslog(LOG_DEBUG,
379 "to register this sockwatcker\n");
381 case CURL_POLL_REMOVE:
382 EVCURLM_syslog(LOG_DEBUG,
383 "called last time to unregister "
384 "this sockwatcher\n");
385 ev_io_stop(event_base, &IO->recv_event);
386 ev_io_stop(event_base, &IO->send_event);
389 ev_io_start(event_base, &IO->recv_event);
390 ev_io_stop(event_base, &IO->send_event);
393 ev_io_start(event_base, &IO->send_event);
394 ev_io_stop(event_base, &IO->recv_event);
396 case CURL_POLL_INOUT:
397 ev_io_start(event_base, &IO->send_event);
398 ev_io_start(event_base, &IO->recv_event);
404 void curl_init_connectionpool(void)
408 ev_timer_init(&global.timeev, &gottime, 14.0, 14.0);
409 global.timeev.data = (void *)&global;
411 CURLcode sta = curl_global_init(CURL_GLOBAL_ALL);
416 "error initializing curl library: %s\n",
417 curl_easy_strerror(sta));
421 mhnd = global.mhnd = curl_multi_init();
424 CURLM_syslog(LOG_ERR,
425 "error initializing curl multi handle\n");
429 MOPT(SOCKETFUNCTION, &gotwatchsock);
430 MOPT(SOCKETDATA, (void *)&global);
431 MOPT(TIMERFUNCTION, &gotwatchtime);
432 MOPT(TIMERDATA, (void *)&global);
437 int evcurl_init(AsyncIO *IO)
442 EVCURLM_syslog(LOG_DEBUG, "EVCURL: evcurl_init called ms\n");
443 IO->HttpReq.attached = 0;
444 chnd = IO->HttpReq.chnd = curl_easy_init();
447 EVCURLM_syslog(LOG_ERR, "EVCURL: error initializing curl handle\n");
452 OPT(VERBOSE, (long)1);
457 OPT(FAILONERROR, (long)1);
459 OPT(FOLLOWLOCATION, (long)0);
460 OPT(MAXREDIRS, (long)0);
461 OPT(USERAGENT, CITADEL);
463 OPT(TIMEOUT, (long)1800);
464 OPT(LOW_SPEED_LIMIT, (long)64);
465 OPT(LOW_SPEED_TIME, (long)600);
466 OPT(CONNECTTIMEOUT, (long)600);
467 OPT(PRIVATE, (void *)IO);
469 OPT(FORBID_REUSE, 1);
470 OPT(WRITEFUNCTION, &gotdata);
471 OPT(WRITEDATA, (void *)IO);
472 OPT(ERRORBUFFER, IO->HttpReq.errdesc);
474 if ((!IsEmptyStr(config.c_ip_addr))
475 && (strcmp(config.c_ip_addr, "*"))
476 && (strcmp(config.c_ip_addr, "::"))
477 && (strcmp(config.c_ip_addr, "0.0.0.0"))
480 OPT(INTERFACE, config.c_ip_addr);
483 #ifdef CURLOPT_HTTP_CONTENT_DECODING
484 OPT(HTTP_CONTENT_DECODING, 1);
488 IO->HttpReq.headers = curl_slist_append(IO->HttpReq.headers,
489 "Connection: close");
495 static void IOcurl_abort_shutdown_callback(struct ev_loop *loop,
500 AsyncIO *IO = watcher->data;
505 SetEVState(IO, eCurlShutdown);
506 IO->Now = ev_now(event_base);
507 EVCURL_syslog(LOG_DEBUG, "EVENT Curl: %s\n", __FUNCTION__);
509 curl_slist_free_all(IO->HttpReq.headers);
510 msta = curl_multi_remove_handle(global.mhnd, IO->HttpReq.chnd);
513 EVCURL_syslog(LOG_ERR,
514 "EVCURL: warning problem detaching completed handle "
515 "from curl multi: %s\n",
516 curl_multi_strerror(msta));
519 curl_easy_cleanup(IO->HttpReq.chnd);
520 IO->HttpReq.chnd = NULL;
521 ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
522 ev_io_stop(event_base, &IO->recv_event);
523 ev_io_stop(event_base, &IO->send_event);
524 assert(IO->ShutdownAbort);
525 IO->ShutdownAbort(IO);
528 evcurl_handle_start(AsyncIO *IO)
534 SetEVState(IO, eCurlStart);
535 chnd = IO->HttpReq.chnd;
536 EVCURL_syslog(LOG_DEBUG,
537 "EVCURL: Loading URL: %s\n", IO->ConnectMe->PlainUrl);
538 OPT(URL, IO->ConnectMe->PlainUrl);
539 if (StrLength(IO->ConnectMe->CurlCreds))
541 OPT(HTTPAUTH, (long)CURLAUTH_BASIC);
542 OPT(USERPWD, ChrPtr(IO->ConnectMe->CurlCreds));
544 if (StrLength(IO->HttpReq.PostData) > 0)
546 OPT(POSTFIELDS, ChrPtr(IO->HttpReq.PostData));
547 OPT(POSTFIELDSIZE, StrLength(IO->HttpReq.PostData));
550 else if ((IO->HttpReq.PlainPostDataLen != 0) &&
551 (IO->HttpReq.PlainPostData != NULL))
553 OPT(POSTFIELDS, IO->HttpReq.PlainPostData);
554 OPT(POSTFIELDSIZE, IO->HttpReq.PlainPostDataLen);
556 OPT(HTTPHEADER, IO->HttpReq.headers);
558 IO->NextState = eConnect;
559 EVCURLM_syslog(LOG_DEBUG, "EVCURL: attaching to curl multi handle\n");
560 msta = curl_multi_add_handle(global.mhnd, IO->HttpReq.chnd);
563 EVCURL_syslog(LOG_ERR,
564 "EVCURL: error attaching to curl multi handle: %s\n",
565 curl_multi_strerror(msta));
568 IO->HttpReq.attached = 1;
569 ev_async_send (event_base, &WakeupCurl);
571 ev_cleanup_init(&IO->abort_by_shutdown,
572 IOcurl_abort_shutdown_callback);
574 ev_cleanup_start(event_base, &IO->abort_by_shutdown);
579 static void WakeupCurlCallback(EV_P_ ev_async *w, int revents)
581 CURLM_syslog(LOG_DEBUG, "waking up curl multi handle\n");
583 curl_multi_perform(&global, CURL_POLL_NONE);
586 static void evcurl_shutdown (void)
588 curl_global_cleanup();
589 curl_multi_cleanup(global.mhnd);
590 CURLM_syslog(LOG_DEBUG, "exiting\n");
592 /*****************************************************************************
593 * libevent integration *
594 *****************************************************************************/
596 * client event queue plus its methods.
597 * this currently is the main loop (which may change in some future?)
599 int evbase_count = 0;
600 pthread_mutex_t EventQueueMutex; /* locks the access to the following vars: */
601 pthread_mutex_t EventExitQueueMutex; /* locks the access to the event queue pointer on exit. */
602 HashList *QueueEvents = NULL;
603 HashList *InboundEventQueue = NULL;
604 HashList *InboundEventQueues[2] = { NULL, NULL };
605 extern void ShutDownCLient(AsyncIO *IO);
608 ev_async ExitEventLoop;
610 static void QueueEventAddCallback(EV_P_ ev_async *w, int revents)
620 /* get the control command... */
621 pthread_mutex_lock(&EventQueueMutex);
623 if (InboundEventQueues[0] == InboundEventQueue) {
624 InboundEventQueue = InboundEventQueues[1];
625 q = InboundEventQueues[0];
628 InboundEventQueue = InboundEventQueues[0];
629 q = InboundEventQueues[1];
631 pthread_mutex_unlock(&EventQueueMutex);
632 Now = ev_now (event_base);
633 It = GetNewHashPos(q, 0);
634 while (GetNextHashPos(q, It, &len, &Key, &v))
637 if (h->IO->ID == 0) {
638 h->IO->ID = EvIDSource++;
640 if (h->IO->StartIO == 0.0)
641 h->IO->StartIO = Now;
643 SetEVState(h->IO, eIOAttach);
645 Ctx = h->IO->CitContext;
649 switch (h->EvAttch(h->IO))
663 case eTerminateConnection:
665 ShutDownCLient(h->IO);
670 DeleteHashContent(&q);
671 EVQM_syslog(LOG_DEBUG, "EVENT Q Add done.\n");
675 static void EventExitCallback(EV_P_ ev_async *w, int revents)
677 ev_break(event_base, EVBREAK_ALL);
679 EVQM_syslog(LOG_DEBUG, "EVENT Q exiting.\n");
684 void InitEventQueue(void)
686 pthread_mutex_init(&EventQueueMutex, NULL);
687 pthread_mutex_init(&EventExitQueueMutex, NULL);
689 QueueEvents = NewHash(1, Flathash);
690 InboundEventQueues[0] = NewHash(1, Flathash);
691 InboundEventQueues[1] = NewHash(1, Flathash);
692 InboundEventQueue = InboundEventQueues[0];
694 extern void CtdlDestroyEVCleanupHooks(void);
696 extern int EVQShutDown;
698 * this thread operates the select() etc. via libev.
700 void *client_event_thread(void *arg)
702 struct CitContext libev_client_CC;
704 CtdlFillSystemContext(&libev_client_CC, "LibEv Thread");
705 // citthread_setspecific(MyConKey, (void *)&smtp_queue_CC);
706 EVQM_syslog(LOG_DEBUG, "client_event_thread() initializing\n");
708 event_base = ev_default_loop (EVFLAG_AUTO);
709 ev_async_init(&AddJob, QueueEventAddCallback);
710 ev_async_start(event_base, &AddJob);
711 ev_async_init(&ExitEventLoop, EventExitCallback);
712 ev_async_start(event_base, &ExitEventLoop);
713 ev_async_init(&WakeupCurl, WakeupCurlCallback);
714 ev_async_start(event_base, &WakeupCurl);
716 curl_init_connectionpool();
718 ev_run (event_base, 0);
720 EVQM_syslog(LOG_DEBUG, "client_event_thread() exiting\n");
722 ///what todo here? CtdlClearSystemContext();
723 pthread_mutex_lock(&EventExitQueueMutex);
724 ev_loop_destroy (EV_DEFAULT_UC);
726 DeleteHash(&QueueEvents);
727 InboundEventQueue = NULL;
728 DeleteHash(&InboundEventQueues[0]);
729 DeleteHash(&InboundEventQueues[1]);
730 /* citthread_mutex_destroy(&EventQueueMutex); TODO */
733 CtdlDestroyEVCleanupHooks();
735 pthread_mutex_unlock(&EventExitQueueMutex);
740 /*----------------------------------------------------------------------------*/
742 * DB-Queue; does async bdb operations.
743 * has its own set of handlers.
747 pthread_mutex_t DBEventQueueMutex; /* locks the access to the following vars: */
748 pthread_mutex_t DBEventExitQueueMutex; /* locks the access to the db-event queue pointer on exit. */
749 HashList *DBQueueEvents = NULL;
750 HashList *DBInboundEventQueue = NULL;
751 HashList *DBInboundEventQueues[2] = { NULL, NULL };
754 ev_async DBExitEventLoop;
756 extern void ShutDownDBCLient(AsyncIO *IO);
758 static void DBQueueEventAddCallback(EV_P_ ev_async *w, int revents)
768 /* get the control command... */
769 pthread_mutex_lock(&DBEventQueueMutex);
771 if (DBInboundEventQueues[0] == DBInboundEventQueue) {
772 DBInboundEventQueue = DBInboundEventQueues[1];
773 q = DBInboundEventQueues[0];
776 DBInboundEventQueue = DBInboundEventQueues[0];
777 q = DBInboundEventQueues[1];
779 pthread_mutex_unlock(&DBEventQueueMutex);
781 Now = ev_now (event_db);
782 It = GetNewHashPos(q, 0);
783 while (GetNextHashPos(q, It, &len, &Key, &v))
788 h->IO->ID = EvIDSource++;
789 if (h->IO->StartDB == 0.0)
790 h->IO->StartDB = Now;
793 SetEVState(h->IO, eDBAttach);
794 Ctx = h->IO->CitContext;
796 ev_cleanup_start(event_db, &h->IO->db_abort_by_shutdown);
797 rc = h->EvAttch(h->IO);
801 ShutDownDBCLient(h->IO);
807 DeleteHashContent(&q);
808 EVQM_syslog(LOG_DEBUG, "DBEVENT Q Add done.\n");
812 static void DBEventExitCallback(EV_P_ ev_async *w, int revents)
814 EVQM_syslog(LOG_DEBUG, "DB EVENT Q exiting.\n");
815 ev_break(event_db, EVBREAK_ALL);
820 void DBInitEventQueue(void)
822 pthread_mutex_init(&DBEventQueueMutex, NULL);
823 pthread_mutex_init(&DBEventExitQueueMutex, NULL);
825 DBQueueEvents = NewHash(1, Flathash);
826 DBInboundEventQueues[0] = NewHash(1, Flathash);
827 DBInboundEventQueues[1] = NewHash(1, Flathash);
828 DBInboundEventQueue = DBInboundEventQueues[0];
832 * this thread operates writing to the message database via libev.
834 void *db_event_thread(void *arg)
837 struct CitContext libev_msg_CC;
839 CtdlFillSystemContext(&libev_msg_CC, "LibEv DB IO Thread");
841 EVQM_syslog(LOG_DEBUG, "dbevent_thread() initializing\n");
843 tmp = event_db = ev_loop_new (EVFLAG_AUTO);
845 ev_async_init(&DBAddJob, DBQueueEventAddCallback);
846 ev_async_start(event_db, &DBAddJob);
847 ev_async_init(&DBExitEventLoop, DBEventExitCallback);
848 ev_async_start(event_db, &DBExitEventLoop);
850 ev_run (event_db, 0);
852 pthread_mutex_lock(&DBEventExitQueueMutex);
855 EVQM_syslog(LOG_INFO, "dbevent_thread() exiting\n");
857 DeleteHash(&DBQueueEvents);
858 DBInboundEventQueue = NULL;
859 DeleteHash(&DBInboundEventQueues[0]);
860 DeleteHash(&DBInboundEventQueues[1]);
862 /* citthread_mutex_destroy(&DBEventQueueMutex); TODO */
864 ev_loop_destroy (tmp);
865 pthread_mutex_unlock(&DBEventExitQueueMutex);
869 void ShutDownEventQueues(void)
871 EVQM_syslog(LOG_DEBUG, "EVENT Qs triggering exits.\n");
873 pthread_mutex_lock(&DBEventQueueMutex);
874 ev_async_send (event_db, &DBExitEventLoop);
875 pthread_mutex_unlock(&DBEventQueueMutex);
877 pthread_mutex_lock(&EventQueueMutex);
878 ev_async_send (EV_DEFAULT_ &ExitEventLoop);
879 pthread_mutex_unlock(&EventQueueMutex);
882 void DebugEventloopEnable(const int n)
886 void DebugEventloopBacktraceEnable(const int n)
888 DebugEventLoopBacktrace = n;
891 void DebugCurlEnable(const int n)
896 CTDL_MODULE_INIT(event_client)
900 CtdlRegisterDebugFlagHook(HKEY("eventloop"), DebugEventloopEnable, &DebugEventLoop);
901 CtdlRegisterDebugFlagHook(HKEY("eventloopbacktrace"), DebugEventloopBacktraceEnable, &DebugEventLoopBacktrace);
902 CtdlRegisterDebugFlagHook(HKEY("curl"), DebugCurlEnable, &DebugCurl);
905 CtdlThreadCreate(client_event_thread);
906 CtdlThreadCreate(db_event_thread);