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 #include "event_client.h"
59 #include "serv_curl.h"
64 /*****************************************************************************
65 * libevent / curl integration *
66 *****************************************************************************/
69 sta = curl_multi_setopt(mhnd, (CURLMOPT_##s), (v)); \
71 syslog(LOG_ERR, "EVCURL: error setting option " #s " on curl multi handle: %s\n", curl_easy_strerror(sta)); \
76 typedef struct _evcurl_global_data {
84 evcurl_global_data global;
96 syslog(LOG_DEBUG, "CURLEV: gotstatus(): about to call curl_multi_info_read\n");
97 while ((msg = curl_multi_info_read(mhnd, &nmsg))) {
98 syslog(LOG_ERR, "EVCURL: got curl multi_info message msg=%d\n", msg->msg);
99 if (CURLMSG_DONE == msg->msg) {
107 chnd = msg->easy_handle;
108 sta = curl_easy_getinfo(chnd, CURLINFO_PRIVATE, &chandle);
109 syslog(LOG_ERR, "EVCURL: request complete\n");
111 syslog(LOG_ERR, "EVCURL: error asking curl for private cookie of curl handle: %s\n", curl_easy_strerror(sta));
112 IO = (AsyncIO *)chandle;
114 ev_io_stop(event_base, &IO->recv_event);
115 ev_io_stop(event_base, &IO->send_event);
117 sta = msg->data.result;
119 EV_syslog(LOG_ERR, "EVCURL: error description: %s\n", IO->HttpReq.errdesc);
120 EV_syslog(LOG_ERR, "EVCURL: error performing request: %s\n", curl_easy_strerror(sta));
122 sta = curl_easy_getinfo(chnd, CURLINFO_RESPONSE_CODE, &IO->HttpReq.httpcode);
124 EV_syslog(LOG_ERR, "EVCURL: error asking curl for response code from request: %s\n", curl_easy_strerror(sta));
125 EV_syslog(LOG_ERR, "EVCURL: http response code was %ld\n", (long)IO->HttpReq.httpcode);
128 curl_slist_free_all(IO->HttpReq.headers);
129 msta = curl_multi_remove_handle(mhnd, chnd);
131 EV_syslog(LOG_ERR, "EVCURL: warning problem detaching completed handle from curl multi: %s\n", curl_multi_strerror(msta));
133 curl_easy_cleanup(IO->HttpReq.chnd);
134 IO->HttpReq.chnd = NULL;
136 IO->HttpReq.attached = 0;
139 FreeStrBuf(&IO->HttpReq.ReplyData);
140 FreeURL(&IO->ConnectMe);
141 RemoveContext(IO->CitContext);
148 stepmulti(void *data, curl_socket_t fd, int which)
150 int running_handles = 0;
153 msta = curl_multi_socket_action(global.mhnd, fd, which, &running_handles);
154 syslog(LOG_DEBUG, "EVCURL: stepmulti(): calling gotstatus()\n");
156 syslog(LOG_ERR, "EVCURL: error in curl processing events on multi handle, fd %d: %s\n", (int)fd, curl_multi_strerror(msta));
157 if (global.nrun != running_handles)
158 gotstatus(running_handles);
162 gottime(struct ev_loop *loop, ev_timer *timeev, int events) {
163 syslog(LOG_DEBUG, "EVCURL: waking up curl for timeout\n");
164 stepmulti(NULL, CURL_SOCKET_TIMEOUT, 0);
168 got_in(struct ev_loop *loop, ev_io *ioev, int events) {
169 syslog(LOG_DEBUG, "EVCURL: waking up curl for io on fd %d\n", (int)ioev->fd);
170 stepmulti(ioev->data, ioev->fd, CURL_CSELECT_IN);
174 got_out(struct ev_loop *loop, ev_io *ioev, int events) {
175 syslog(LOG_DEBUG, "EVCURL: waking up curl for io on fd %d\n", (int)ioev->fd);
176 stepmulti(ioev->data, ioev->fd, CURL_CSELECT_OUT);
180 gotdata(void *data, size_t size, size_t nmemb, void *cglobal) {
181 AsyncIO *IO = (AsyncIO*) cglobal;
183 if (IO->HttpReq.ReplyData == NULL)
185 IO->HttpReq.ReplyData = NewStrBufPlain(NULL, SIZ);
187 return CurlFillStrBuf_callback(data, size, nmemb, IO->HttpReq.ReplyData);
191 gotwatchtime(CURLM *multi, long tblock_ms, void *cglobal) {
192 syslog(LOG_DEBUG, "EVCURL: gotwatchtime called %ld ms\n", tblock_ms);
193 evcurl_global_data *global = cglobal;
194 ev_timer_stop(EV_DEFAULT, &global->timeev);
195 if (tblock_ms < 0 || 14000 < tblock_ms)
197 ev_timer_set(&global->timeev, 0.5e-3 + 1.0e-3 * tblock_ms, 14.0);
198 ev_timer_start(EV_DEFAULT_UC, &global->timeev);
199 curl_multi_perform(global, CURL_POLL_NONE);
204 gotwatchsock(CURL *easy, curl_socket_t fd, int action, void *cglobal, void *vIO) {
205 evcurl_global_data *global = cglobal;
206 CURLM *mhnd = global->mhnd;
208 AsyncIO *IO = (AsyncIO*) vIO;
211 EV_syslog(LOG_DEBUG, "EVCURL: gotwatchsock called fd=%d action=%d\n", (int)fd, action);
213 sta = curl_easy_getinfo(easy, CURLINFO_PRIVATE, &f);
215 EV_syslog(LOG_ERR, "EVCURL: error asking curl for private cookie of curl handle: %s\n", curl_easy_strerror(sta));
219 if (IO->SendBuf.fd != 0)
221 ev_io_stop(event_base, &IO->recv_event);
222 ev_io_stop(event_base, &IO->send_event);
225 ev_io_init(&IO->recv_event, &got_in, fd, EV_READ);
226 ev_io_init(&IO->send_event, &got_out, fd, EV_WRITE);
227 curl_multi_assign(mhnd, fd, IO);
234 EVM_syslog(LOG_ERR,"EVCURL: called first time to register this sockwatcker\n");
236 case CURL_POLL_REMOVE:
237 EVM_syslog(LOG_ERR,"EVCURL: called last time to unregister this sockwatcher\n");
238 ev_io_stop(event_base, &IO->recv_event);
239 ev_io_stop(event_base, &IO->send_event);
242 ev_io_stop(event_base, &IO->recv_event);
243 ev_io_start(event_base, &IO->send_event);
246 ev_io_stop(event_base, &IO->send_event);
247 ev_io_start(event_base, &IO->recv_event);
249 case CURL_POLL_INOUT:
250 ev_io_start(event_base, &IO->send_event);
251 ev_io_start(event_base, &IO->recv_event);
257 void curl_init_connectionpool(void)
261 ev_timer_init(&global.timeev, &gottime, 14.0, 14.0);
262 global.timeev.data = (void *)&global;
264 CURLcode sta = curl_global_init(CURL_GLOBAL_ALL);
268 syslog(LOG_ERR,"EVCURL: error initializing curl library: %s\n", curl_easy_strerror(sta));
271 mhnd = global.mhnd = curl_multi_init();
274 syslog(LOG_ERR,"EVCURL: error initializing curl multi handle\n");
278 MOPT(SOCKETFUNCTION, &gotwatchsock);
279 MOPT(SOCKETDATA, (void *)&global);
280 MOPT(TIMERFUNCTION, &gotwatchtime);
281 MOPT(TIMERDATA, (void *)&global);
289 int evcurl_init(AsyncIO *IO,
292 IO_CallBack CallBack,
293 IO_CallBack Terminate)
298 EVM_syslog(LOG_DEBUG, "EVCURL: evcurl_init called ms\n");
299 IO->HttpReq.attached = 0;
300 IO->SendDone = CallBack;
301 IO->Terminate = Terminate;
302 chnd = IO->HttpReq.chnd = curl_easy_init();
305 EVM_syslog(LOG_ERR, "EVCURL: error initializing curl handle\n");
309 strcpy(IO->HttpReq.errdesc, Desc);
311 OPT(VERBOSE, (long)1);
312 /* unset in production */
313 OPT(NOPROGRESS, (long)1);
314 OPT(NOSIGNAL, (long)1);
315 OPT(FAILONERROR, (long)1);
317 OPT(FOLLOWLOCATION, (long)1);
318 OPT(MAXREDIRS, (long)7);
319 OPT(USERAGENT, CITADEL);
321 OPT(TIMEOUT, (long)1800);
322 OPT(LOW_SPEED_LIMIT, (long)64);
323 OPT(LOW_SPEED_TIME, (long)600);
324 OPT(CONNECTTIMEOUT, (long)600);
325 OPT(PRIVATE, (void *)IO);
327 OPT(FORBID_REUSE, 1);
328 OPT(WRITEFUNCTION, &gotdata);
329 OPT(WRITEDATA, (void *)IO);
330 OPT(ERRORBUFFER, IO->HttpReq.errdesc);
333 (!IsEmptyStr(config.c_ip_addr))
334 && (strcmp(config.c_ip_addr, "*"))
335 && (strcmp(config.c_ip_addr, "::"))
336 && (strcmp(config.c_ip_addr, "0.0.0.0"))
338 OPT(INTERFACE, config.c_ip_addr);
340 /* point to a structure that points back to the perl structure and stuff */
341 EV_syslog(LOG_DEBUG, "EVCURL: Loading URL: %s\n", IO->ConnectMe->PlainUrl);
342 OPT(URL, IO->ConnectMe->PlainUrl);
343 if (StrLength(IO->ConnectMe->CurlCreds))
345 OPT(HTTPAUTH, (long)CURLAUTH_BASIC);
346 OPT(USERPWD, ChrPtr(IO->ConnectMe->CurlCreds));
348 #ifdef CURLOPT_HTTP_CONTENT_DECODING
349 OPT(HTTP_CONTENT_DECODING, 1);
352 if (StrLength(IO->HttpReq.PostData) > 0)
354 OPT(POSTFIELDS, ChrPtr(IO->HttpReq.PostData));
355 OPT(POSTFIELDSIZE, StrLength(IO->HttpReq.PostData));
358 else if ((IO->HttpReq.PlainPostDataLen != 0) && (IO->HttpReq.PlainPostData != NULL))
360 OPT(POSTFIELDS, IO->HttpReq.PlainPostData);
361 OPT(POSTFIELDSIZE, IO->HttpReq.PlainPostDataLen);
364 IO->HttpReq.headers = curl_slist_append(IO->HttpReq.headers, "Connection: close");
365 OPT(HTTPHEADER, IO->HttpReq.headers);
371 evcurl_handle_start(AsyncIO *IO)
374 IO->NextState = eConnect;
375 EVM_syslog(LOG_DEBUG, "EVCURL: attaching to curl multi handle\n");
376 msta = curl_multi_add_handle(global.mhnd, IO->HttpReq.chnd);
378 EV_syslog(LOG_ERR, "EVCURL: error attaching to curl multi handle: %s\n", curl_multi_strerror(msta));
379 IO->HttpReq.attached = 1;
380 ev_async_send (event_base, &WakeupCurl);
384 static void WakeupCurlCallback(EV_P_ ev_async *w, int revents)
386 syslog(LOG_DEBUG, "EVCURL: waking up curl multi handle\n");
388 curl_multi_perform(&global, CURL_POLL_NONE);
391 static void evcurl_shutdown (void)
393 curl_multi_cleanup(global.mhnd);
395 /*****************************************************************************
396 * libevent integration *
397 *****************************************************************************/
399 * client event queue plus its methods.
400 * this currently is the main loop (which may change in some future?)
402 int evbase_count = 0;
403 int event_add_pipe[2] = {-1, -1};
404 pthread_mutex_t EventQueueMutex; /* locks the access to the following vars: */
405 HashList *QueueEvents = NULL;
406 HashList *InboundEventQueue = NULL;
407 HashList *InboundEventQueues[2] = { NULL, NULL };
410 ev_async ExitEventLoop;
412 static void QueueEventAddCallback(EV_P_ ev_async *w, int revents)
420 /* get the control command... */
421 pthread_mutex_lock(&EventQueueMutex);
423 if (InboundEventQueues[0] == InboundEventQueue) {
424 InboundEventQueue = InboundEventQueues[1];
425 q = InboundEventQueues[0];
428 InboundEventQueue = InboundEventQueues[0];
429 q = InboundEventQueues[1];
431 pthread_mutex_unlock(&EventQueueMutex);
433 It = GetNewHashPos(q, 0);
434 while (GetNextHashPos(q, It, &len, &Key, &v))
438 h->IO->ID = EvIDSource++;
442 DeleteHashContent(&q);
443 syslog(LOG_DEBUG, "EVENT Q Read done.\n");
447 static void EventExitCallback(EV_P_ ev_async *w, int revents)
449 ev_break(event_base, EVBREAK_ALL);
451 syslog(LOG_DEBUG, "EVENT Q exiting.\n");
456 void InitEventQueue(void)
458 struct rlimit LimitSet;
460 pthread_mutex_init(&EventQueueMutex, NULL);
462 if (pipe(event_add_pipe) != 0) {
463 syslog(LOG_EMERG, "Unable to create pipe for libev queueing: %s\n", strerror(errno));
466 LimitSet.rlim_cur = 1;
467 LimitSet.rlim_max = 1;
468 setrlimit(event_add_pipe[1], &LimitSet);
470 QueueEvents = NewHash(1, Flathash);
471 InboundEventQueues[0] = NewHash(1, Flathash);
472 InboundEventQueues[1] = NewHash(1, Flathash);
473 InboundEventQueue = InboundEventQueues[0];
476 * this thread operates the select() etc. via libev.
480 void *client_event_thread(void *arg)
482 struct CitContext libev_client_CC;
484 CtdlFillSystemContext(&libev_client_CC, "LibEv Thread");
485 // citthread_setspecific(MyConKey, (void *)&smtp_queue_CC);
486 syslog(LOG_DEBUG, "client_ev_thread() initializing\n");
488 event_base = ev_default_loop (EVFLAG_AUTO);
490 ev_async_init(&AddJob, QueueEventAddCallback);
491 ev_async_start(event_base, &AddJob);
492 ev_async_init(&ExitEventLoop, EventExitCallback);
493 ev_async_start(event_base, &ExitEventLoop);
494 ev_async_init(&WakeupCurl, WakeupCurlCallback);
495 ev_async_start(event_base, &WakeupCurl);
497 curl_init_connectionpool();
499 ev_run (event_base, 0);
502 ///what todo here? CtdlClearSystemContext();
503 ev_loop_destroy (EV_DEFAULT_UC);
505 DeleteHash(&QueueEvents);
506 InboundEventQueue = NULL;
507 DeleteHash(&InboundEventQueues[0]);
508 DeleteHash(&InboundEventQueues[1]);
509 /* citthread_mutex_destroy(&EventQueueMutex); TODO */
514 /*------------------------------------------------------------------------------*/
516 * DB-Queue; does async bdb operations.
517 * has its own set of handlers.
521 int evdb_add_pipe[2] = {-1, -1};
522 pthread_mutex_t DBEventQueueMutex; /* locks the access to the following vars: */
523 HashList *DBQueueEvents = NULL;
524 HashList *DBInboundEventQueue = NULL;
525 HashList *DBInboundEventQueues[2] = { NULL, NULL };
528 ev_async DBExitEventLoop;
530 extern void ShutDownDBCLient(AsyncIO *IO);
532 static void DBQueueEventAddCallback(EV_P_ ev_async *w, int revents)
540 /* get the control command... */
541 pthread_mutex_lock(&DBEventQueueMutex);
543 if (DBInboundEventQueues[0] == DBInboundEventQueue) {
544 DBInboundEventQueue = DBInboundEventQueues[1];
545 q = DBInboundEventQueues[0];
548 DBInboundEventQueue = DBInboundEventQueues[0];
549 q = DBInboundEventQueues[1];
551 pthread_mutex_unlock(&DBEventQueueMutex);
553 It = GetNewHashPos(q, 0);
554 while (GetNextHashPos(q, It, &len, &Key, &v))
559 h->IO->ID = EvIDSource++;
560 rc = h->EvAttch(h->IO);
564 ShutDownDBCLient(h->IO);
570 DeleteHashContent(&q);
571 syslog(LOG_DEBUG, "DBEVENT Q Read done.\n");
575 static void DBEventExitCallback(EV_P_ ev_async *w, int revents)
577 syslog(LOG_DEBUG, "EVENT Q exiting.\n");
578 ev_break(event_db, EVBREAK_ALL);
583 void DBInitEventQueue(void)
585 struct rlimit LimitSet;
587 pthread_mutex_init(&DBEventQueueMutex, NULL);
589 if (pipe(evdb_add_pipe) != 0) {
590 syslog(LOG_EMERG, "Unable to create pipe for libev queueing: %s\n", strerror(errno));
593 LimitSet.rlim_cur = 1;
594 LimitSet.rlim_max = 1;
595 setrlimit(evdb_add_pipe[1], &LimitSet);
597 DBQueueEvents = NewHash(1, Flathash);
598 DBInboundEventQueues[0] = NewHash(1, Flathash);
599 DBInboundEventQueues[1] = NewHash(1, Flathash);
600 DBInboundEventQueue = DBInboundEventQueues[0];
604 * this thread operates writing to the message database via libev.
608 void *db_event_thread(void *arg)
610 struct CitContext libev_msg_CC;
612 CtdlFillSystemContext(&libev_msg_CC, "LibEv DB IO Thread");
613 // citthread_setspecific(MyConKey, (void *)&smtp_queue_CC);
614 syslog(LOG_DEBUG, "client_msgev_thread() initializing\n");
616 event_db = ev_loop_new (EVFLAG_AUTO);
618 ev_async_init(&DBAddJob, DBQueueEventAddCallback);
619 ev_async_start(event_db, &DBAddJob);
620 ev_async_init(&DBExitEventLoop, DBEventExitCallback);
621 ev_async_start(event_db, &DBExitEventLoop);
623 ev_run (event_db, 0);
626 //// what to do here? CtdlClearSystemContext();
627 ev_loop_destroy (event_db);
629 DeleteHash(&DBQueueEvents);
630 DBInboundEventQueue = NULL;
631 DeleteHash(&DBInboundEventQueues[0]);
632 DeleteHash(&DBInboundEventQueues[1]);
633 /* citthread_mutex_destroy(&DBEventQueueMutex); TODO */
638 CTDL_MODULE_INIT(event_client)
644 CtdlThreadCreate(/*"Client event", */ client_event_thread);
645 CtdlThreadCreate(/*"DB event", */db_event_thread);
646 /// todo register shutdown callback.