2 * Copyright (c) 1998-2009 by the citadel.org team
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 3 of the License, or
7 * (at your option) any later version.
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.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
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>
47 #include <arpa/inet.h>
48 #include <libcitadel.h>
49 #include <curl/curl.h>
50 #include <curl/multi.h>
53 #include "citserver.h"
56 #include "ctdl_module.h"
58 #ifdef EXPERIMENTAL_SMTP_EVENT_CLIENT
60 #include "event_client.h"
61 #include "serv_curl.h"
65 /*****************************************************************************
66 * libevent / curl integration *
67 *****************************************************************************/
70 sta = curl_multi_setopt(mhnd, (CURLMOPT_##s), (v)); \
72 CtdlLogPrintf(CTDL_ERR, "EVCURL: error setting option " #s " on curl multi handle: %s\n", curl_easy_strerror(sta)); \
77 typedef struct _evcurl_global_data {
84 typedef struct _sockwatcher_data
86 evcurl_global_data *global;
91 evcurl_global_data global;
94 gotstatus(evcurl_global_data *global, int nnrun)
100 if (EVCURL_GLOBAL_MAGIC != global.magic)
102 CtdlLogPrintf(CTDL_ERR, "internal error: gotstatus on wrong struct");
106 global->nrun = nnrun;
109 CtdlLogPrintf(CTDL_DEBUG, "CURLEV: gotstatus(): about to call curl_multi_info_read\n");
110 while ((msg = curl_multi_info_read(mhnd, &nmsg))) {
111 CtdlLogPrintf(CTDL_ERR, "EVCURL: got curl multi_info message msg=%d\n", msg->msg);
112 if (CURLMSG_DONE == msg->msg) {
120 chnd = msg->easy_handle;
121 sta = curl_easy_getinfo(chnd, CURLINFO_PRIVATE, &chandle);
122 CtdlLogPrintf(CTDL_ERR, "EVCURL: request complete\n");
124 CtdlLogPrintf(CTDL_ERR, "EVCURL: error asking curl for private cookie of curl handle: %s\n", curl_easy_strerror(sta));
125 IO = (AsyncIO *)chandle;
127 sta = msg->data.result;
129 CtdlLogPrintf(CTDL_ERR, "EVCURL: error description: %s\n", IO->HttpReq.errdesc);
130 CtdlLogPrintf(CTDL_ERR, "EVCURL: error performing request: %s\n", curl_easy_strerror(sta));
132 sta = curl_easy_getinfo(chnd, CURLINFO_RESPONSE_CODE, &IO->HttpReq.httpcode);
134 CtdlLogPrintf(CTDL_ERR, "EVCURL: error asking curl for response code from request: %s\n", curl_easy_strerror(sta));
135 CtdlLogPrintf(CTDL_ERR, "EVCURL: http response code was %ld\n", (long)IO->HttpReq.httpcode);
136 msta = curl_multi_remove_handle(mhnd, chnd);
138 CtdlLogPrintf(CTDL_ERR, "EVCURL: warning problem detaching completed handle from curl multi: %s\n", curl_multi_strerror(msta));
140 IO->HttpReq.attached = 0;
142 curl_easy_cleanup(IO->HttpReq.chnd);
143 curl_slist_free_all(IO->HttpReq.headers);
144 FreeStrBuf(&IO->HttpReq.ReplyData);
145 FreeURL(&IO->ConnectMe);
146 RemoveContext(IO->CitContext);
153 stepmulti(evcurl_global_data *global, curl_socket_t fd) {
157 if (global == NULL) {
158 CtdlLogPrintf(CTDL_DEBUG, "EVCURL: stepmulti(NULL): wtf?\n");
161 msta = curl_multi_socket_action(global->mhnd, fd, 0, &nnrun);
162 CtdlLogPrintf(CTDL_DEBUG, "EVCURL: stepmulti(): calling gotstatus()\n");
164 CtdlLogPrintf(CTDL_ERR, "EVCURL: error in curl processing events on multi handle, fd %d: %s\n", (int)fd, curl_multi_strerror(msta));
165 if (global->nrun != nnrun)
166 gotstatus(global, nnrun);
170 gottime(struct ev_loop *loop, ev_timer *timeev, int events) {
171 CtdlLogPrintf(CTDL_DEBUG, "EVCURL: waking up curl for timeout\n");
172 evcurl_global_data *global = (void *)timeev->data;
173 stepmulti(global, CURL_SOCKET_TIMEOUT);
177 gotio(struct ev_loop *loop, ev_io *ioev, int events) {
178 CtdlLogPrintf(CTDL_DEBUG, "EVCURL: waking up curl for io on fd %d\n", (int)ioev->fd);
179 sockwatcher_data *sockwatcher = (void *)ioev->data;
180 stepmulti(sockwatcher->global, ioev->fd);
184 gotdata(void *data, size_t size, size_t nmemb, void *cglobal) {
185 AsyncIO *IO = (AsyncIO*) cglobal;
186 //evcurl_request_data *D = (evcurl_request_data*) data;
187 CtdlLogPrintf(CTDL_DEBUG, "EVCURL: gotdata(): calling CurlFillStrBuf_callback()\n");
189 if (IO->HttpReq.ReplyData == NULL)
191 IO->HttpReq.ReplyData = NewStrBufPlain(NULL, SIZ);
193 return CurlFillStrBuf_callback(data, size, nmemb, IO->HttpReq.ReplyData);
197 gotwatchtime(CURLM *multi, long tblock_ms, void *cglobal) {
198 CtdlLogPrintf(CTDL_DEBUG, "EVCURL: gotwatchtime called %ld ms\n", tblock_ms);
199 evcurl_global_data *global = cglobal;
200 ev_timer_stop(EV_DEFAULT, &global->timeev);
201 if (tblock_ms < 0 || 14000 < tblock_ms)
203 ev_timer_set(&global->timeev, 0.5e-3 + 1.0e-3 * tblock_ms, 14.0);
204 ev_timer_start(EV_DEFAULT_UC, &global->timeev);
205 curl_multi_perform(global, CURL_POLL_NONE);
210 gotwatchsock(CURL *easy, curl_socket_t fd, int action, void *cglobal, void *csockwatcher) {
211 evcurl_global_data *global = cglobal;
212 CURLM *mhnd = global->mhnd;
213 sockwatcher_data *sockwatcher = csockwatcher;
215 CtdlLogPrintf(CTDL_DEBUG,"EVCURL: gotwatchsock called fd=%d action=%d\n", (int)fd, action);
218 CtdlLogPrintf(CTDL_ERR,"EVCURL: called first time to register this sockwatcker\n");
219 sockwatcher = malloc(sizeof(sockwatcher_data));
220 sockwatcher->global = global;
221 ev_init(&sockwatcher->ioev, &gotio);
222 sockwatcher->ioev.data = (void *)sockwatcher;
223 curl_multi_assign(mhnd, fd, sockwatcher);
225 if (CURL_POLL_REMOVE == action) {
226 CtdlLogPrintf(CTDL_ERR,"EVCURL: called last time to unregister this sockwatcher\n");
227 ev_io_stop(event_base, &sockwatcher->ioev);
230 int events = (action & CURL_POLL_IN ? EV_READ : 0) | (action & CURL_POLL_OUT ? EV_WRITE : 0);
231 ev_io_stop(EV_DEFAULT, &sockwatcher->ioev);
233 ev_io_set(&sockwatcher->ioev, fd, events);
234 ev_io_start(EV_DEFAULT, &sockwatcher->ioev);
240 void curl_init_connectionpool(void)
244 ev_timer_init(&global.timeev, &gottime, 14.0, 14.0);
245 global.timeev.data = (void *)&global;
247 CURLcode sta = curl_global_init(CURL_GLOBAL_ALL);
251 CtdlLogPrintf(CTDL_ERR,"EVCURL: error initializing curl library: %s\n", curl_easy_strerror(sta));
254 mhnd = global.mhnd = curl_multi_init();
257 CtdlLogPrintf(CTDL_ERR,"EVCURL: error initializing curl multi handle\n");
261 MOPT(SOCKETFUNCTION, &gotwatchsock);
262 MOPT(SOCKETDATA, (void *)&global);
263 MOPT(TIMERFUNCTION, &gotwatchtime);
264 MOPT(TIMERDATA, (void *)&global);
272 int evcurl_init(AsyncIO *IO,
275 IO_CallBack CallBack)
280 CtdlLogPrintf(CTDL_DEBUG,"EVCURL: evcurl_init called ms\n");
281 IO->HttpReq.attached = 0;
282 IO->SendDone = CallBack;
283 chnd = IO->HttpReq.chnd = curl_easy_init();
286 CtdlLogPrintf(CTDL_ERR, "EVCURL: error initializing curl handle\n");
290 strcpy(IO->HttpReq.errdesc, Desc);
292 OPT(VERBOSE, (long)1);
293 /* unset in production */
294 OPT(NOPROGRESS, (long)1);
295 OPT(NOSIGNAL, (long)1);
296 OPT(FAILONERROR, (long)1);
298 OPT(FOLLOWLOCATION, (long)1);
299 OPT(MAXREDIRS, (long)7);
300 OPT(USERAGENT, CITADEL);
302 OPT(TIMEOUT, (long)1800);
303 OPT(LOW_SPEED_LIMIT, (long)64);
304 OPT(LOW_SPEED_TIME, (long)600);
305 OPT(CONNECTTIMEOUT, (long)600);
306 OPT(PRIVATE, (void *)IO);
309 OPT(WRITEFUNCTION, &gotdata);
310 OPT(WRITEDATA, (void *)IO);
311 OPT(ERRORBUFFER, IO->HttpReq.errdesc);
314 (!IsEmptyStr(config.c_ip_addr))
315 && (strcmp(config.c_ip_addr, "*"))
316 && (strcmp(config.c_ip_addr, "::"))
317 && (strcmp(config.c_ip_addr, "0.0.0.0"))
319 OPT(INTERFACE, config.c_ip_addr);
321 /* point to a structure that points back to the perl structure and stuff */
322 CtdlLogPrintf(CTDL_DEBUG, "EVCURL: Loading URL: %s\n", IO->ConnectMe->PlainUrl);
323 OPT(URL, IO->ConnectMe->PlainUrl);
324 if (StrLength(IO->ConnectMe->CurlCreds))
326 OPT(HTTPAUTH, (long)CURLAUTH_BASIC);
327 OPT(USERPWD, ChrPtr(IO->ConnectMe->CurlCreds));
329 #ifdef CURLOPT_HTTP_CONTENT_DECODING
330 OPT(HTTP_CONTENT_DECODING, 1);
333 if (StrLength(IO->HttpReq.PostData) > 0)
335 OPT(POSTFIELDS, ChrPtr(IO->HttpReq.PostData));
336 OPT(POSTFIELDSIZE, StrLength(IO->HttpReq.PostData));
339 else if ((IO->HttpReq.PlainPostDataLen != 0) && (IO->HttpReq.PlainPostData != NULL))
341 OPT(POSTFIELDS, IO->HttpReq.PlainPostData);
342 OPT(POSTFIELDSIZE, IO->HttpReq.PlainPostDataLen);
345 if (IO->HttpReq.headers != NULL)
346 OPT(HTTPHEADER, IO->HttpReq.headers);
352 evcurl_handle_start(AsyncIO *IO)
356 CtdlLogPrintf(CTDL_DEBUG, "EVCURL: attaching to curl multi handle\n");
357 msta = curl_multi_add_handle(global.mhnd, IO->HttpReq.chnd);
359 CtdlLogPrintf(CTDL_ERR, "EVCURL: error attaching to curl multi handle: %s\n", curl_multi_strerror(msta));
360 IO->HttpReq.attached = 1;
361 ev_async_send (event_base, &WakeupCurl);
364 static void WakeupCurlCallback(EV_P_ ev_async *w, int revents)
366 CtdlLogPrintf(CTDL_DEBUG, "EVCURL: waking up curl multi handle\n");
368 curl_multi_perform(&global, CURL_POLL_NONE);
371 static void evcurl_shutdown (void)
373 curl_multi_cleanup(global.mhnd);
375 /*****************************************************************************
376 * libevent integration *
377 *****************************************************************************/
379 * client event queue plus its methods.
380 * this currently is the main loop (which may change in some future?)
382 int evbase_count = 0;
383 int event_add_pipe[2] = {-1, -1};
384 citthread_mutex_t EventQueueMutex; /* locks the access to the following vars: */
385 HashList *QueueEvents = NULL;
386 HashList *InboundEventQueue = NULL;
387 HashList *InboundEventQueues[2] = { NULL, NULL };
390 ev_async ExitEventLoop;
392 static void QueueEventAddCallback(EV_P_ ev_async *w, int revents)
400 /* get the control command... */
401 citthread_mutex_lock(&EventQueueMutex);
403 if (InboundEventQueues[0] == InboundEventQueue) {
404 InboundEventQueue = InboundEventQueues[1];
405 q = InboundEventQueues[0];
408 InboundEventQueue = InboundEventQueues[0];
409 q = InboundEventQueues[1];
411 citthread_mutex_unlock(&EventQueueMutex);
413 It = GetNewHashPos(q, 0);
414 while (GetNextHashPos(q, It, &len, &Key, &v))
420 DeleteHashContent(&q);
421 CtdlLogPrintf(CTDL_DEBUG, "EVENT Q Read done.\n");
425 static void EventExitCallback(EV_P_ ev_async *w, int revents)
427 ev_break(event_base, EVBREAK_ALL);
429 CtdlLogPrintf(CTDL_DEBUG, "EVENT Q exiting.\n");
434 void InitEventQueue(void)
436 struct rlimit LimitSet;
438 citthread_mutex_init(&EventQueueMutex, NULL);
440 if (pipe(event_add_pipe) != 0) {
441 CtdlLogPrintf(CTDL_EMERG, "Unable to create pipe for libev queueing: %s\n", strerror(errno));
444 LimitSet.rlim_cur = 1;
445 LimitSet.rlim_max = 1;
446 setrlimit(event_add_pipe[1], &LimitSet);
448 QueueEvents = NewHash(1, Flathash);
449 InboundEventQueues[0] = NewHash(1, Flathash);
450 InboundEventQueues[1] = NewHash(1, Flathash);
451 InboundEventQueue = InboundEventQueues[0];
454 * this thread operates the select() etc. via libev.
458 void *client_event_thread(void *arg)
460 struct CitContext libev_client_CC;
462 CtdlFillSystemContext(&libev_client_CC, "LibEv Thread");
463 // citthread_setspecific(MyConKey, (void *)&smtp_queue_CC);
464 CtdlLogPrintf(CTDL_DEBUG, "client_ev_thread() initializing\n");
466 event_base = ev_default_loop (EVFLAG_AUTO);
468 ev_async_init(&AddJob, QueueEventAddCallback);
469 ev_async_start(event_base, &AddJob);
470 ev_async_init(&ExitEventLoop, EventExitCallback);
471 ev_async_start(event_base, &ExitEventLoop);
472 ev_async_init(&WakeupCurl, WakeupCurlCallback);
473 ev_async_start(event_base, &WakeupCurl);
475 curl_init_connectionpool();
477 ev_run (event_base, 0);
480 CtdlClearSystemContext();
481 ev_loop_destroy (EV_DEFAULT_UC);
483 DeleteHash(&QueueEvents);
484 InboundEventQueue = NULL;
485 DeleteHash(&InboundEventQueues[0]);
486 DeleteHash(&InboundEventQueues[1]);
487 citthread_mutex_destroy(&EventQueueMutex);
492 /*------------------------------------------------------------------------------*/
494 * DB-Queue; does async bdb operations.
495 * has its own set of handlers.
499 int evdb_add_pipe[2] = {-1, -1};
500 citthread_mutex_t DBEventQueueMutex; /* locks the access to the following vars: */
501 HashList *DBQueueEvents = NULL;
502 HashList *DBInboundEventQueue = NULL;
503 HashList *DBInboundEventQueues[2] = { NULL, NULL };
506 ev_async DBExitEventLoop;
508 static void DBQueueEventAddCallback(EV_P_ ev_async *w, int revents)
516 /* get the control command... */
517 citthread_mutex_lock(&DBEventQueueMutex);
519 if (DBInboundEventQueues[0] == DBInboundEventQueue) {
520 DBInboundEventQueue = DBInboundEventQueues[1];
521 q = DBInboundEventQueues[0];
524 DBInboundEventQueue = DBInboundEventQueues[0];
525 q = DBInboundEventQueues[1];
527 citthread_mutex_unlock(&DBEventQueueMutex);
529 It = GetNewHashPos(q, 0);
530 while (GetNextHashPos(q, It, &len, &Key, &v))
536 DeleteHashContent(&q);
537 CtdlLogPrintf(CTDL_DEBUG, "DBEVENT Q Read done.\n");
541 static void DBEventExitCallback(EV_P_ ev_async *w, int revents)
543 ev_break(event_db, EVBREAK_ALL);
545 CtdlLogPrintf(CTDL_DEBUG, "EVENT Q exiting.\n");
550 void DBInitEventQueue(void)
552 struct rlimit LimitSet;
554 citthread_mutex_init(&DBEventQueueMutex, NULL);
556 if (pipe(evdb_add_pipe) != 0) {
557 CtdlLogPrintf(CTDL_EMERG, "Unable to create pipe for libev queueing: %s\n", strerror(errno));
560 LimitSet.rlim_cur = 1;
561 LimitSet.rlim_max = 1;
562 setrlimit(evdb_add_pipe[1], &LimitSet);
564 DBQueueEvents = NewHash(1, Flathash);
565 DBInboundEventQueues[0] = NewHash(1, Flathash);
566 DBInboundEventQueues[1] = NewHash(1, Flathash);
567 DBInboundEventQueue = DBInboundEventQueues[0];
571 * this thread operates writing to the message database via libev.
575 void *db_event_thread(void *arg)
577 struct CitContext libev_msg_CC;
579 CtdlFillSystemContext(&libev_msg_CC, "LibEv DB IO Thread");
580 // citthread_setspecific(MyConKey, (void *)&smtp_queue_CC);
581 CtdlLogPrintf(CTDL_DEBUG, "client_msgev_thread() initializing\n");
583 event_db = ev_loop_new (EVFLAG_AUTO);
585 ev_async_init(&DBAddJob, DBQueueEventAddCallback);
586 ev_async_start(event_db, &DBAddJob);
587 ev_async_init(&DBExitEventLoop, DBEventExitCallback);
588 ev_async_start(event_db, &DBExitEventLoop);
590 ev_run (event_db, 0);
593 CtdlClearSystemContext();
594 ev_loop_destroy (event_db);
596 DeleteHash(&DBQueueEvents);
597 DBInboundEventQueue = NULL;
598 DeleteHash(&DBInboundEventQueues[0]);
599 DeleteHash(&DBInboundEventQueues[1]);
600 citthread_mutex_destroy(&DBEventQueueMutex);
607 CTDL_MODULE_INIT(event_client)
609 #ifdef EXPERIMENTAL_SMTP_EVENT_CLIENT
614 CtdlThreadCreate("Client event", CTDLTHREAD_BIGSTACK, client_event_thread, NULL);
615 CtdlThreadCreate("DB event", CTDLTHREAD_BIGSTACK, db_event_thread, NULL);
616 /// todo register shutdown callback.