2 * Copyright (c) 1998-2015 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.
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
22 #include <sys/types.h>
25 #if TIME_WITH_SYS_TIME
26 # include <sys/time.h>
30 # include <sys/time.h>
39 #include <sys/socket.h>
40 #include <netinet/in.h>
42 #include <arpa/inet.h>
43 #include <libcitadel.h>
44 #include <curl/curl.h>
45 #include <curl/multi.h>
48 #include "citserver.h"
50 #include "ctdl_module.h"
52 #include "event_client.h"
53 #include "serv_curl.h"
56 int DebugEventLoop = 0;
57 int DebugEventLoopBacktrace = 0;
59 pthread_key_t evConKey;
62 /*****************************************************************************
63 * libevent / curl integration *
64 *****************************************************************************/
68 sta = curl_multi_setopt(mhnd, (CURLMOPT_##s), (v)); \
70 syslog(LOG_ERR, "error setting option " \
71 #s " on curl multi handle: %s\n", \
72 curl_easy_strerror(sta)); \
78 typedef struct _evcurl_global_data {
86 evcurl_global_data global;
88 eNextState QueueAnDBOperation(AsyncIO *IO);
99 "gotstatus(): about to call curl_multi_info_read\n");
100 while ((msg = curl_multi_info_read(global.mhnd, &nmsg))) {
102 "got curl multi_info message msg=%d\n",
105 if (CURLMSG_DONE == msg->msg) {
107 void *chandle = NULL;
113 chnd = msg->easy_handle;
114 sta = curl_easy_getinfo(chnd,
119 "error asking curl for private"
120 " cookie of curl handle: %s\n",
121 curl_easy_strerror(sta));
124 IO = (AsyncIO *)chandle;
127 "Error, invalid IO context %p\n",
131 SetEVState(IO, eCurlGotStatus);
133 syslog(LOG_DEBUG, "request complete\n");
135 IO->CitContext->lastcmd = IO->Now = ev_now(event_base);
137 ev_io_stop(event_base, &IO->recv_event);
138 ev_io_stop(event_base, &IO->send_event);
140 sta = msg->data.result;
143 "error description: %s\n",
144 IO->HttpReq.errdesc);
145 IO->HttpReq.CurlError = curl_easy_strerror(sta);
147 "error performing request: %s\n",
148 IO->HttpReq.CurlError);
149 if (sta == CURLE_OPERATION_TIMEDOUT)
155 sta = curl_easy_getinfo(chnd,
156 CURLINFO_RESPONSE_CODE,
157 &IO->HttpReq.httpcode);
160 "error asking curl for "
161 "response code from request: %s\n",
162 curl_easy_strerror(sta));
164 "http response code was %ld\n",
165 (long)IO->HttpReq.httpcode);
168 curl_slist_free_all(IO->HttpReq.headers);
169 IO->HttpReq.headers = NULL;
170 msta = curl_multi_remove_handle(global.mhnd, chnd);
173 "warning problem detaching "
174 "completed handle from curl multi: "
176 curl_multi_strerror(msta));
178 ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
180 IO->HttpReq.attached = 0;
181 switch(IO->SendDone(IO))
184 FreeURL(&IO->ConnectMe);
185 QueueAnDBOperation(IO);
198 case eTerminateConnection:
200 curl_easy_cleanup(IO->HttpReq.chnd);
201 IO->HttpReq.chnd = NULL;
202 FreeStrBuf(&IO->HttpReq.ReplyData);
203 FreeURL(&IO->ConnectMe);
204 RemoveContext(IO->CitContext);
212 stepmulti(void *data, curl_socket_t fd, int which)
214 int running_handles = 0;
217 msta = curl_multi_socket_action(global.mhnd,
222 syslog(LOG_DEBUG, "stepmulti(): calling gotstatus()\n");
225 "error in curl processing events"
226 "on multi handle, fd %d: %s\n",
228 curl_multi_strerror(msta));
230 if (global.nrun != running_handles)
231 gotstatus(running_handles);
235 gottime(struct ev_loop *loop, ev_timer *timeev, int events)
237 syslog(LOG_DEBUG, "EVCURL: waking up curl for timeout\n");
238 stepmulti(NULL, CURL_SOCKET_TIMEOUT, 0);
242 got_in(struct ev_loop *loop, ev_io *ioev, int events)
245 "EVCURL: waking up curl for io on fd %d\n",
248 stepmulti(ioev->data, ioev->fd, CURL_CSELECT_IN);
252 got_out(struct ev_loop *loop, ev_io *ioev, int events)
255 "waking up curl for io on fd %d\n",
258 stepmulti(ioev->data, ioev->fd, CURL_CSELECT_OUT);
262 gotdata(void *data, size_t size, size_t nmemb, void *cglobal)
264 AsyncIO *IO = (AsyncIO*) cglobal;
266 SetEVState(IO, eCurlGotData);
267 if (IO->HttpReq.ReplyData == NULL)
269 IO->HttpReq.ReplyData = NewStrBufPlain(NULL, SIZ);
271 IO->CitContext->lastcmd = IO->Now = ev_now(event_base);
272 return CurlFillStrBuf_callback(data,
275 IO->HttpReq.ReplyData);
279 gotwatchtime(CURLM *multi, long tblock_ms, void *cglobal) {
280 syslog(LOG_DEBUG, "EVCURL: gotwatchtime called %ld ms\n", tblock_ms);
281 evcurl_global_data *global = cglobal;
282 ev_timer_stop(EV_DEFAULT, &global->timeev);
283 if (tblock_ms < 0 || 14000 < tblock_ms)
285 ev_timer_set(&global->timeev, 0.5e-3 + 1.0e-3 * tblock_ms, 14.0);
286 ev_timer_start(EV_DEFAULT_UC, &global->timeev);
287 curl_multi_perform(global, &global->nrun);
292 gotwatchsock(CURL *easy,
298 evcurl_global_data *global = cglobal;
299 CURLM *mhnd = global->mhnd;
301 AsyncIO *IO = (AsyncIO*) vIO;
306 sta = curl_easy_getinfo(easy, CURLINFO_PRIVATE, &f);
309 "EVCURL: error asking curl for private "
310 "cookie of curl handle: %s\n",
311 curl_easy_strerror(sta));
315 SetEVState(IO, eCurlNewIO);
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 SetEVState(IO, eCurlGotIO);
332 IO->CitContext->lastcmd = IO->Now = ev_now(event_base);
338 Action = "CURL_POLL_NONE";
340 case CURL_POLL_REMOVE:
341 Action = "CURL_POLL_REMOVE";
344 Action = "CURL_POLL_IN";
347 Action = "CURL_POLL_OUT";
349 case CURL_POLL_INOUT:
350 Action = "CURL_POLL_INOUT";
356 "EVCURL: gotwatchsock called fd=%d action=%s[%d]\n",
357 (int)fd, Action, action);
364 "to register this sockwatcker\n");
366 case CURL_POLL_REMOVE:
368 "called last time to unregister "
369 "this sockwatcher\n");
370 ev_io_stop(event_base, &IO->recv_event);
371 ev_io_stop(event_base, &IO->send_event);
374 ev_io_start(event_base, &IO->recv_event);
375 ev_io_stop(event_base, &IO->send_event);
378 ev_io_start(event_base, &IO->send_event);
379 ev_io_stop(event_base, &IO->recv_event);
381 case CURL_POLL_INOUT:
382 ev_io_start(event_base, &IO->send_event);
383 ev_io_start(event_base, &IO->recv_event);
389 void curl_init_connectionpool(void)
393 ev_timer_init(&global.timeev, &gottime, 14.0, 14.0);
394 global.timeev.data = (void *)&global;
396 CURLcode sta = curl_global_init(CURL_GLOBAL_ALL);
401 "error initializing curl library: %s\n",
402 curl_easy_strerror(sta));
406 mhnd = global.mhnd = curl_multi_init();
410 "error initializing curl multi handle\n");
414 MOPT(SOCKETFUNCTION, &gotwatchsock);
415 MOPT(SOCKETDATA, (void *)&global);
416 MOPT(TIMERFUNCTION, &gotwatchtime);
417 MOPT(TIMERDATA, (void *)&global);
422 int evcurl_init(AsyncIO *IO)
427 syslog(LOG_DEBUG, "EVCURL: evcurl_init called ms\n");
428 IO->HttpReq.attached = 0;
429 chnd = IO->HttpReq.chnd = curl_easy_init();
432 syslog(LOG_ERR, "EVCURL: error initializing curl handle\n");
437 OPT(VERBOSE, (long)1);
442 OPT(FAILONERROR, (long)1);
444 OPT(FOLLOWLOCATION, (long)0);
445 OPT(MAXREDIRS, (long)0);
446 OPT(USERAGENT, CITADEL);
448 OPT(TIMEOUT, (long)1800);
449 OPT(LOW_SPEED_LIMIT, (long)64);
450 OPT(LOW_SPEED_TIME, (long)600);
451 OPT(CONNECTTIMEOUT, (long)600);
452 OPT(PRIVATE, (void *)IO);
454 OPT(FORBID_REUSE, 1);
455 OPT(WRITEFUNCTION, &gotdata);
456 OPT(WRITEDATA, (void *)IO);
457 OPT(ERRORBUFFER, IO->HttpReq.errdesc);
459 if ((!IsEmptyStr(CtdlGetConfigStr("c_ip_addr")))
460 && (strcmp(CtdlGetConfigStr("c_ip_addr"), "*"))
461 && (strcmp(CtdlGetConfigStr("c_ip_addr"), "::"))
462 && (strcmp(CtdlGetConfigStr("c_ip_addr"), "0.0.0.0"))
465 OPT(INTERFACE, CtdlGetConfigStr("c_ip_addr"));
468 #ifdef CURLOPT_HTTP_CONTENT_DECODING
469 OPT(HTTP_CONTENT_DECODING, 1);
473 IO->HttpReq.headers = curl_slist_append(IO->HttpReq.headers,
474 "Connection: close");
480 static void IOcurl_abort_shutdown_callback(struct ev_loop *loop,
485 AsyncIO *IO = watcher->data;
490 SetEVState(IO, eCurlShutdown);
491 IO->CitContext->lastcmd = IO->Now = ev_now(event_base);
492 syslog(LOG_DEBUG, "EVENT Curl: %s\n", __FUNCTION__);
494 curl_slist_free_all(IO->HttpReq.headers);
495 IO->HttpReq.headers = NULL;
496 msta = curl_multi_remove_handle(global.mhnd, IO->HttpReq.chnd);
500 "EVCURL: warning problem detaching completed handle "
501 "from curl multi: %s\n",
502 curl_multi_strerror(msta));
505 curl_easy_cleanup(IO->HttpReq.chnd);
506 IO->HttpReq.chnd = NULL;
507 ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
508 ev_io_stop(event_base, &IO->recv_event);
509 ev_io_stop(event_base, &IO->send_event);
510 assert(IO->ShutdownAbort);
511 IO->ShutdownAbort(IO);
515 evcurl_handle_start(AsyncIO *IO)
521 SetEVState(IO, eCurlStart);
522 chnd = IO->HttpReq.chnd;
524 "EVCURL: Loading URL: %s\n", IO->ConnectMe->PlainUrl);
525 OPT(URL, IO->ConnectMe->PlainUrl);
526 if (StrLength(IO->ConnectMe->CurlCreds))
528 OPT(HTTPAUTH, (long)CURLAUTH_BASIC);
529 OPT(USERPWD, ChrPtr(IO->ConnectMe->CurlCreds));
531 if (StrLength(IO->HttpReq.PostData) > 0)
533 OPT(POSTFIELDS, ChrPtr(IO->HttpReq.PostData));
534 OPT(POSTFIELDSIZE, StrLength(IO->HttpReq.PostData));
537 else if ((IO->HttpReq.PlainPostDataLen != 0) &&
538 (IO->HttpReq.PlainPostData != NULL))
540 OPT(POSTFIELDS, IO->HttpReq.PlainPostData);
541 OPT(POSTFIELDSIZE, IO->HttpReq.PlainPostDataLen);
543 OPT(HTTPHEADER, IO->HttpReq.headers);
545 IO->NextState = eConnect;
546 syslog(LOG_DEBUG, "EVCURL: attaching to curl multi handle\n");
547 msta = curl_multi_add_handle(global.mhnd, IO->HttpReq.chnd);
551 "EVCURL: error attaching to curl multi handle: %s\n",
552 curl_multi_strerror(msta));
555 IO->HttpReq.attached = 1;
556 ev_async_send (event_base, &WakeupCurl);
558 ev_cleanup_init(&IO->abort_by_shutdown,
559 IOcurl_abort_shutdown_callback);
561 ev_cleanup_start(event_base, &IO->abort_by_shutdown);
566 static void WakeupCurlCallback(EV_P_ ev_async *w, int revents)
568 syslog(LOG_DEBUG, "waking up curl multi handle\n");
570 curl_multi_perform(&global, CURL_POLL_NONE);
573 static void evcurl_shutdown (void)
575 curl_global_cleanup();
576 curl_multi_cleanup(global.mhnd);
577 syslog(LOG_DEBUG, "exiting\n");
579 /*****************************************************************************
580 * libevent integration *
581 *****************************************************************************/
583 * client event queue plus its methods.
584 * this currently is the main loop (which may change in some future?)
586 int evbase_count = 0;
587 pthread_mutex_t EventQueueMutex; /* locks the access to the following vars: */
588 pthread_mutex_t EventExitQueueMutex; /* locks the access to the event queue pointer on exit. */
589 HashList *QueueEvents = NULL;
590 HashList *InboundEventQueue = NULL;
591 HashList *InboundEventQueues[2] = { NULL, NULL };
592 extern void ShutDownCLient(AsyncIO *IO);
595 ev_async ExitEventLoop;
597 static void QueueEventAddCallback(EV_P_ ev_async *w, int revents)
609 /* get the control command... */
610 pthread_mutex_lock(&EventQueueMutex);
612 if (InboundEventQueues[0] == InboundEventQueue) {
613 InboundEventQueue = InboundEventQueues[1];
614 q = InboundEventQueues[0];
617 InboundEventQueue = InboundEventQueues[0];
618 q = InboundEventQueues[1];
620 pthread_mutex_unlock(&EventQueueMutex);
621 Now = ev_now (event_base);
622 It = GetNewHashPos(q, 0);
623 while (GetNextHashPos(q, It, &len, &Key, &v))
627 if (h->IO->ID == 0) {
628 h->IO->ID = EvIDSource++;
631 if (h->IO->StartIO == 0.0)
632 h->IO->StartIO = Now;
634 SetEVState(h->IO, eIOAttach);
636 Ctx = h->IO->CitContext;
639 h->IO->CitContext->lastcmd = h->IO->Now = Now;
640 switch (h->EvAttch(h->IO))
654 case eTerminateConnection:
656 ShutDownCLient(h->IO);
661 DeleteHashContent(&q);
662 syslog(LOG_DEBUG, "%s CC[%ld] EVENT Q Add %ld done.", IOSTR, IOID, count);
666 static void EventExitCallback(EV_P_ ev_async *w, int revents)
668 ev_break(event_base, EVBREAK_ALL);
670 syslog(LOG_DEBUG, "EVENT Q exiting.\n");
675 void InitEventQueue(void)
677 pthread_mutex_init(&EventQueueMutex, NULL);
678 pthread_mutex_init(&EventExitQueueMutex, NULL);
680 QueueEvents = NewHash(1, Flathash);
681 InboundEventQueues[0] = NewHash(1, Flathash);
682 InboundEventQueues[1] = NewHash(1, Flathash);
683 InboundEventQueue = InboundEventQueues[0];
685 extern void CtdlDestroyEVCleanupHooks(void);
687 extern int EVQShutDown;
688 const char *IOLog = "IO";
690 * this thread operates the select() etc. via libev.
692 void *client_event_thread(void *arg)
694 struct CitContext libev_client_CC;
696 CtdlFillSystemContext(&libev_client_CC, "LibEv Thread");
698 pthread_setspecific(evConKey, IOLog);
700 syslog(LOG_DEBUG, "client_event_thread() initializing\n");
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);
710 curl_init_connectionpool();
712 ev_run (event_base, 0);
714 syslog(LOG_DEBUG, "client_event_thread() exiting\n");
716 ///what todo here? CtdlClearSystemContext();
717 pthread_mutex_lock(&EventExitQueueMutex);
718 ev_loop_destroy (EV_DEFAULT_UC);
720 DeleteHash(&QueueEvents);
721 InboundEventQueue = NULL;
722 DeleteHash(&InboundEventQueues[0]);
723 DeleteHash(&InboundEventQueues[1]);
724 /* citthread_mutex_destroy(&EventQueueMutex); TODO */
727 CtdlDestroyEVCleanupHooks();
729 pthread_mutex_unlock(&EventExitQueueMutex);
734 /*----------------------------------------------------------------------------*/
736 * DB-Queue; does async bdb operations.
737 * has its own set of handlers.
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 };
748 ev_async DBExitEventLoop;
750 extern void ShutDownDBCLient(AsyncIO *IO);
752 static void DBQueueEventAddCallback(EV_P_ ev_async *w, int revents)
764 /* get the control command... */
765 pthread_mutex_lock(&DBEventQueueMutex);
767 if (DBInboundEventQueues[0] == DBInboundEventQueue) {
768 DBInboundEventQueue = DBInboundEventQueues[1];
769 q = DBInboundEventQueues[0];
772 DBInboundEventQueue = DBInboundEventQueues[0];
773 q = DBInboundEventQueues[1];
775 pthread_mutex_unlock(&DBEventQueueMutex);
777 Now = ev_now (event_db);
778 It = GetNewHashPos(q, 0);
779 while (GetNextHashPos(q, It, &len, &Key, &v))
785 h->IO->ID = EvIDSource++;
787 if (h->IO->StartDB == 0.0)
788 h->IO->StartDB = Now;
789 h->IO->CitContext->lastcmd = h->IO->Now = Now;
791 SetEVState(h->IO, eDBAttach);
792 Ctx = h->IO->CitContext;
794 ev_cleanup_start(event_db, &h->IO->db_abort_by_shutdown);
795 rc = h->EvAttch(h->IO);
799 ShutDownDBCLient(h->IO);
805 DeleteHashContent(&q);
806 syslog(LOG_DEBUG, "%s CC[%ld] DBEVENT Q Add %ld done.", IOSTR, IOID, count);
810 static void DBEventExitCallback(EV_P_ ev_async *w, int revents)
812 syslog(LOG_DEBUG, "DB EVENT Q exiting.\n");
813 ev_break(event_db, EVBREAK_ALL);
818 void DBInitEventQueue(void)
820 pthread_mutex_init(&DBEventQueueMutex, NULL);
821 pthread_mutex_init(&DBEventExitQueueMutex, NULL);
823 DBQueueEvents = NewHash(1, Flathash);
824 DBInboundEventQueues[0] = NewHash(1, Flathash);
825 DBInboundEventQueues[1] = NewHash(1, Flathash);
826 DBInboundEventQueue = DBInboundEventQueues[0];
829 const char *DBLog = "BD";
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 pthread_setspecific(evConKey, DBLog);
841 CtdlFillSystemContext(&libev_msg_CC, "LibEv DB IO Thread");
843 syslog(LOG_DEBUG, "dbevent_thread() initializing\n");
845 tmp = event_db = ev_loop_new (EVFLAG_AUTO);
847 ev_async_init(&DBAddJob, DBQueueEventAddCallback);
848 ev_async_start(event_db, &DBAddJob);
849 ev_async_init(&DBExitEventLoop, DBEventExitCallback);
850 ev_async_start(event_db, &DBExitEventLoop);
852 ev_run (event_db, 0);
854 pthread_mutex_lock(&DBEventExitQueueMutex);
857 syslog(LOG_INFO, "dbevent_thread() exiting\n");
859 DeleteHash(&DBQueueEvents);
860 DBInboundEventQueue = NULL;
861 DeleteHash(&DBInboundEventQueues[0]);
862 DeleteHash(&DBInboundEventQueues[1]);
864 /* citthread_mutex_destroy(&DBEventQueueMutex); TODO */
866 ev_loop_destroy (tmp);
867 pthread_mutex_unlock(&DBEventExitQueueMutex);
871 void ShutDownEventQueues(void)
873 syslog(LOG_DEBUG, "EVENT Qs triggering exits.\n");
875 pthread_mutex_lock(&DBEventQueueMutex);
876 ev_async_send (event_db, &DBExitEventLoop);
877 pthread_mutex_unlock(&DBEventQueueMutex);
879 pthread_mutex_lock(&EventQueueMutex);
880 ev_async_send (EV_DEFAULT_ &ExitEventLoop);
881 pthread_mutex_unlock(&EventQueueMutex);
884 void DebugEventloopEnable(const int n)
888 void DebugEventloopBacktraceEnable(const int n)
890 DebugEventLoopBacktrace = n;
893 void DebugCurlEnable(const int n)
898 const char *WLog = "WX";
899 CTDL_MODULE_INIT(event_client)
903 if (pthread_key_create(&evConKey, NULL) != 0) {
904 syslog(LOG_CRIT, "Can't create TSD key: %s", strerror(errno));
906 pthread_setspecific(evConKey, WLog);
908 CtdlRegisterDebugFlagHook(HKEY("eventloop"), DebugEventloopEnable, &DebugEventLoop);
909 CtdlRegisterDebugFlagHook(HKEY("eventloopbacktrace"), DebugEventloopBacktraceEnable, &DebugEventLoopBacktrace);
910 CtdlRegisterDebugFlagHook(HKEY("curl"), DebugCurlEnable, &DebugCurl);
913 CtdlThreadCreate(client_event_thread);
914 CtdlThreadCreate(db_event_thread);