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"
63 /*****************************************************************************
64 * libevent / curl integration *
65 *****************************************************************************/
68 sta = curl_multi_setopt(mhnd, (CURLMOPT_##s), (v)); \
70 syslog(LOG_ERR, "EVCURL: error setting option " #s " on curl multi handle: %s\n", curl_easy_strerror(sta)); \
75 typedef struct _evcurl_global_data {
83 evcurl_global_data global;
86 gotstatus(evcurl_global_data *global, int nnrun)
95 syslog(LOG_DEBUG, "CURLEV: gotstatus(): about to call curl_multi_info_read\n");
96 while ((msg = curl_multi_info_read(mhnd, &nmsg))) {
97 syslog(LOG_ERR, "EVCURL: got curl multi_info message msg=%d\n", msg->msg);
98 if (CURLMSG_DONE == msg->msg) {
106 chnd = msg->easy_handle;
107 sta = curl_easy_getinfo(chnd, CURLINFO_PRIVATE, &chandle);
108 syslog(LOG_ERR, "EVCURL: request complete\n");
110 syslog(LOG_ERR, "EVCURL: error asking curl for private cookie of curl handle: %s\n", curl_easy_strerror(sta));
111 IO = (AsyncIO *)chandle;
113 ///// ev_io_stop(event_base, &IO->recv_event);
115 sta = msg->data.result;
117 syslog(LOG_ERR, "EVCURL: error description: %s\n", IO->HttpReq.errdesc);
118 syslog(LOG_ERR, "EVCURL: error performing request: %s\n", curl_easy_strerror(sta));
120 sta = curl_easy_getinfo(chnd, CURLINFO_RESPONSE_CODE, &IO->HttpReq.httpcode);
122 syslog(LOG_ERR, "EVCURL: error asking curl for response code from request: %s\n", curl_easy_strerror(sta));
123 syslog(LOG_ERR, "EVCURL: http response code was %ld\n", (long)IO->HttpReq.httpcode);
124 /// syslog(LOG_ERR, "EVCURL: disconnecting [%s]\nn", ChrPtr(IO->ConnectMe->URL));
125 msta = curl_multi_remove_handle(mhnd, chnd);
127 syslog(LOG_ERR, "EVCURL: warning problem detaching completed handle from curl multi: %s\n", curl_multi_strerror(msta));
128 /// syslog(LOG_ERR, "EVCURL: disconnection done [%s]\nn", ChrPtr(IO->ConnectMe->URL));
130 IO->HttpReq.attached = 0;
132 //// syslog(LOG_ERR, "EVCURL: done with [%s]\nn", ChrPtr(IO->ConnectMe->URL));
135 curl_easy_cleanup(IO->HttpReq.chnd);
136 curl_slist_free_all(IO->HttpReq.headers);
138 FreeStrBuf(&IO->HttpReq.ReplyData);
139 FreeURL(&IO->ConnectMe);
140 RemoveContext(IO->CitContext);
148 stepmulti(evcurl_global_data *global, curl_socket_t fd) {
152 if (global == NULL) {
153 syslog(LOG_DEBUG, "EVCURL: stepmulti(NULL): wtf?\n");
156 msta = curl_multi_socket_action(global->mhnd, fd, 0, &nnrun);
157 syslog(LOG_DEBUG, "EVCURL: stepmulti(): calling gotstatus()\n");
159 syslog(LOG_ERR, "EVCURL: error in curl processing events on multi handle, fd %d: %s\n", (int)fd, curl_multi_strerror(msta));
160 if (global->nrun != nnrun)
161 gotstatus(global, nnrun);
165 gottime(struct ev_loop *loop, ev_timer *timeev, int events) {
166 syslog(LOG_DEBUG, "EVCURL: waking up curl for timeout\n");
167 evcurl_global_data *global = (void *)timeev->data;
168 stepmulti(global, CURL_SOCKET_TIMEOUT);
172 gotio(struct ev_loop *loop, ev_io *ioev, int events) {
173 syslog(LOG_DEBUG, "EVCURL: waking up curl for io on fd %d\n", (int)ioev->fd);
174 stepmulti(&global, ioev->fd);
178 gotdata(void *data, size_t size, size_t nmemb, void *cglobal) {
179 AsyncIO *IO = (AsyncIO*) cglobal;
180 //evcurl_request_data *D = (evcurl_request_data*) data;
181 /// syslog(LOG_DEBUG, "EVCURL: gotdata(): calling CurlFillStrBuf_callback()\n");
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 syslog(LOG_DEBUG, "EVCURL: gotwatchsock called fd=%d action=%d\n", (int)fd, action);
214 syslog(LOG_ERR,"EVCURL: called first time to register this sockwatcker\n");
215 sta = curl_easy_getinfo(easy, CURLINFO_PRIVATE, &f);
217 syslog(LOG_ERR, "EVCURL: error asking curl for private cookie of curl handle: %s\n", curl_easy_strerror(sta));
221 ev_init(&IO->recv_event, &gotio);
222 curl_multi_assign(mhnd, fd, IO);
224 if (action == CURL_POLL_REMOVE) {
225 syslog(LOG_ERR,"EVCURL: called last time to unregister this sockwatcher\n");
226 ev_io_stop(event_base, &IO->recv_event);
227 FreeStrBuf(&IO->HttpReq.ReplyData);
228 FreeURL(&IO->ConnectMe);
229 RemoveContext(IO->CitContext);
232 int events = (action & CURL_POLL_IN ? EV_READ : 0) | (action & CURL_POLL_OUT ? EV_WRITE : 0);
233 ev_io_stop(event_base, &IO->recv_event);
235 ev_io_set(&IO->recv_event, fd, events);
236 ev_io_start(event_base, &IO->recv_event);
242 void curl_init_connectionpool(void)
246 ev_timer_init(&global.timeev, &gottime, 14.0, 14.0);
247 global.timeev.data = (void *)&global;
249 CURLcode sta = curl_global_init(CURL_GLOBAL_ALL);
253 syslog(LOG_ERR,"EVCURL: error initializing curl library: %s\n", curl_easy_strerror(sta));
256 mhnd = global.mhnd = curl_multi_init();
259 syslog(LOG_ERR,"EVCURL: error initializing curl multi handle\n");
263 MOPT(SOCKETFUNCTION, &gotwatchsock);
264 MOPT(SOCKETDATA, (void *)&global);
265 MOPT(TIMERFUNCTION, &gotwatchtime);
266 MOPT(TIMERDATA, (void *)&global);
274 int evcurl_init(AsyncIO *IO,
277 IO_CallBack CallBack,
278 IO_CallBack Terminate)
283 syslog(LOG_DEBUG, "EVCURL: evcurl_init called ms\n");
284 IO->HttpReq.attached = 0;
285 IO->SendDone = CallBack;
286 IO->Terminate = Terminate;
287 chnd = IO->HttpReq.chnd = curl_easy_init();
290 syslog(LOG_ERR, "EVCURL: error initializing curl handle\n");
294 strcpy(IO->HttpReq.errdesc, Desc);
296 OPT(VERBOSE, (long)1);
297 /* unset in production */
298 OPT(NOPROGRESS, (long)1);
299 OPT(NOSIGNAL, (long)1);
300 OPT(FAILONERROR, (long)1);
302 OPT(FOLLOWLOCATION, (long)1);
303 OPT(MAXREDIRS, (long)7);
304 OPT(USERAGENT, CITADEL);
306 OPT(TIMEOUT, (long)1800);
307 OPT(LOW_SPEED_LIMIT, (long)64);
308 OPT(LOW_SPEED_TIME, (long)600);
309 OPT(CONNECTTIMEOUT, (long)600);
310 OPT(PRIVATE, (void *)IO);
312 OPT(FORBID_REUSE, 1);
313 OPT(WRITEFUNCTION, &gotdata);
314 OPT(WRITEDATA, (void *)IO);
315 OPT(ERRORBUFFER, IO->HttpReq.errdesc);
318 (!IsEmptyStr(config.c_ip_addr))
319 && (strcmp(config.c_ip_addr, "*"))
320 && (strcmp(config.c_ip_addr, "::"))
321 && (strcmp(config.c_ip_addr, "0.0.0.0"))
323 OPT(INTERFACE, config.c_ip_addr);
325 /* point to a structure that points back to the perl structure and stuff */
326 syslog(LOG_DEBUG, "EVCURL: Loading URL: %s\n", IO->ConnectMe->PlainUrl);
327 OPT(URL, IO->ConnectMe->PlainUrl);
328 if (StrLength(IO->ConnectMe->CurlCreds))
330 OPT(HTTPAUTH, (long)CURLAUTH_BASIC);
331 OPT(USERPWD, ChrPtr(IO->ConnectMe->CurlCreds));
333 #ifdef CURLOPT_HTTP_CONTENT_DECODING
334 OPT(HTTP_CONTENT_DECODING, 1);
337 if (StrLength(IO->HttpReq.PostData) > 0)
339 OPT(POSTFIELDS, ChrPtr(IO->HttpReq.PostData));
340 OPT(POSTFIELDSIZE, StrLength(IO->HttpReq.PostData));
343 else if ((IO->HttpReq.PlainPostDataLen != 0) && (IO->HttpReq.PlainPostData != NULL))
345 OPT(POSTFIELDS, IO->HttpReq.PlainPostData);
346 OPT(POSTFIELDSIZE, IO->HttpReq.PlainPostDataLen);
349 IO->HttpReq.headers = curl_slist_append(IO->HttpReq.headers, "Connection: close");
350 OPT(HTTPHEADER, IO->HttpReq.headers);
356 evcurl_handle_start(AsyncIO *IO)
360 syslog(LOG_DEBUG, "EVCURL: attaching to curl multi handle\n");
361 msta = curl_multi_add_handle(global.mhnd, IO->HttpReq.chnd);
363 syslog(LOG_ERR, "EVCURL: error attaching to curl multi handle: %s\n", curl_multi_strerror(msta));
364 IO->HttpReq.attached = 1;
365 ev_async_send (event_base, &WakeupCurl);
369 static void WakeupCurlCallback(EV_P_ ev_async *w, int revents)
371 syslog(LOG_DEBUG, "EVCURL: waking up curl multi handle\n");
373 curl_multi_perform(&global, CURL_POLL_NONE);
376 static void evcurl_shutdown (void)
378 curl_multi_cleanup(global.mhnd);
380 /*****************************************************************************
381 * libevent integration *
382 *****************************************************************************/
384 * client event queue plus its methods.
385 * this currently is the main loop (which may change in some future?)
387 int evbase_count = 0;
388 int event_add_pipe[2] = {-1, -1};
389 pthread_mutex_t EventQueueMutex; /* locks the access to the following vars: */
390 HashList *QueueEvents = NULL;
391 HashList *InboundEventQueue = NULL;
392 HashList *InboundEventQueues[2] = { NULL, NULL };
395 ev_async ExitEventLoop;
397 static void QueueEventAddCallback(EV_P_ ev_async *w, int revents)
405 /* get the control command... */
406 pthread_mutex_lock(&EventQueueMutex);
408 if (InboundEventQueues[0] == InboundEventQueue) {
409 InboundEventQueue = InboundEventQueues[1];
410 q = InboundEventQueues[0];
413 InboundEventQueue = InboundEventQueues[0];
414 q = InboundEventQueues[1];
416 pthread_mutex_unlock(&EventQueueMutex);
418 It = GetNewHashPos(q, 0);
419 while (GetNextHashPos(q, It, &len, &Key, &v))
425 DeleteHashContent(&q);
426 syslog(LOG_DEBUG, "EVENT Q Read done.\n");
430 static void EventExitCallback(EV_P_ ev_async *w, int revents)
432 ev_break(event_base, EVBREAK_ALL);
434 syslog(LOG_DEBUG, "EVENT Q exiting.\n");
439 void InitEventQueue(void)
441 struct rlimit LimitSet;
443 pthread_mutex_init(&EventQueueMutex, NULL);
445 if (pipe(event_add_pipe) != 0) {
446 syslog(LOG_EMERG, "Unable to create pipe for libev queueing: %s\n", strerror(errno));
449 LimitSet.rlim_cur = 1;
450 LimitSet.rlim_max = 1;
451 setrlimit(event_add_pipe[1], &LimitSet);
453 QueueEvents = NewHash(1, Flathash);
454 InboundEventQueues[0] = NewHash(1, Flathash);
455 InboundEventQueues[1] = NewHash(1, Flathash);
456 InboundEventQueue = InboundEventQueues[0];
459 * this thread operates the select() etc. via libev.
463 void *client_event_thread(void *arg)
465 struct CitContext libev_client_CC;
467 CtdlFillSystemContext(&libev_client_CC, "LibEv Thread");
468 // citthread_setspecific(MyConKey, (void *)&smtp_queue_CC);
469 syslog(LOG_DEBUG, "client_ev_thread() initializing\n");
471 event_base = ev_default_loop (EVFLAG_AUTO);
473 ev_async_init(&AddJob, QueueEventAddCallback);
474 ev_async_start(event_base, &AddJob);
475 ev_async_init(&ExitEventLoop, EventExitCallback);
476 ev_async_start(event_base, &ExitEventLoop);
477 ev_async_init(&WakeupCurl, WakeupCurlCallback);
478 ev_async_start(event_base, &WakeupCurl);
480 curl_init_connectionpool();
482 ev_run (event_base, 0);
485 ///what todo here? CtdlClearSystemContext();
486 ev_loop_destroy (EV_DEFAULT_UC);
488 DeleteHash(&QueueEvents);
489 InboundEventQueue = NULL;
490 DeleteHash(&InboundEventQueues[0]);
491 DeleteHash(&InboundEventQueues[1]);
492 /* citthread_mutex_destroy(&EventQueueMutex); TODO */
497 /*------------------------------------------------------------------------------*/
499 * DB-Queue; does async bdb operations.
500 * has its own set of handlers.
504 int evdb_add_pipe[2] = {-1, -1};
505 pthread_mutex_t DBEventQueueMutex; /* locks the access to the following vars: */
506 HashList *DBQueueEvents = NULL;
507 HashList *DBInboundEventQueue = NULL;
508 HashList *DBInboundEventQueues[2] = { NULL, NULL };
511 ev_async DBExitEventLoop;
513 extern void ShutDownDBCLient(AsyncIO *IO);
515 static void DBQueueEventAddCallback(EV_P_ ev_async *w, int revents)
523 /* get the control command... */
524 pthread_mutex_lock(&DBEventQueueMutex);
526 if (DBInboundEventQueues[0] == DBInboundEventQueue) {
527 DBInboundEventQueue = DBInboundEventQueues[1];
528 q = DBInboundEventQueues[0];
531 DBInboundEventQueue = DBInboundEventQueues[0];
532 q = DBInboundEventQueues[1];
534 pthread_mutex_unlock(&DBEventQueueMutex);
536 It = GetNewHashPos(q, 0);
537 while (GetNextHashPos(q, It, &len, &Key, &v))
541 rc = h->EvAttch(h->IO);
545 ShutDownDBCLient(h->IO);
551 DeleteHashContent(&q);
552 syslog(LOG_DEBUG, "DBEVENT Q Read done.\n");
556 static void DBEventExitCallback(EV_P_ ev_async *w, int revents)
558 syslog(LOG_DEBUG, "EVENT Q exiting.\n");
559 ev_break(event_db, EVBREAK_ALL);
564 void DBInitEventQueue(void)
566 struct rlimit LimitSet;
568 pthread_mutex_init(&DBEventQueueMutex, NULL);
570 if (pipe(evdb_add_pipe) != 0) {
571 syslog(LOG_EMERG, "Unable to create pipe for libev queueing: %s\n", strerror(errno));
574 LimitSet.rlim_cur = 1;
575 LimitSet.rlim_max = 1;
576 setrlimit(evdb_add_pipe[1], &LimitSet);
578 DBQueueEvents = NewHash(1, Flathash);
579 DBInboundEventQueues[0] = NewHash(1, Flathash);
580 DBInboundEventQueues[1] = NewHash(1, Flathash);
581 DBInboundEventQueue = DBInboundEventQueues[0];
585 * this thread operates writing to the message database via libev.
589 void *db_event_thread(void *arg)
591 struct CitContext libev_msg_CC;
593 CtdlFillSystemContext(&libev_msg_CC, "LibEv DB IO Thread");
594 // citthread_setspecific(MyConKey, (void *)&smtp_queue_CC);
595 syslog(LOG_DEBUG, "client_msgev_thread() initializing\n");
597 event_db = ev_loop_new (EVFLAG_AUTO);
599 ev_async_init(&DBAddJob, DBQueueEventAddCallback);
600 ev_async_start(event_db, &DBAddJob);
601 ev_async_init(&DBExitEventLoop, DBEventExitCallback);
602 ev_async_start(event_db, &DBExitEventLoop);
604 ev_run (event_db, 0);
607 //// what to do here? CtdlClearSystemContext();
608 ev_loop_destroy (event_db);
610 DeleteHash(&DBQueueEvents);
611 DBInboundEventQueue = NULL;
612 DeleteHash(&DBInboundEventQueues[0]);
613 DeleteHash(&DBInboundEventQueues[1]);
614 /* citthread_mutex_destroy(&DBEventQueueMutex); TODO */
619 CTDL_MODULE_INIT(event_client)
625 CtdlThreadCreate(/*"Client event", */ client_event_thread);
626 CtdlThreadCreate(/*"DB event", */db_event_thread);
627 /// todo register shutdown callback.