2 * $Id: serv_rssclient.c 5652 2007-10-29 20:14:48Z ajc $
4 * Bring external RSS feeds into rooms.
12 #if TIME_WITH_SYS_TIME
13 # include <sys/time.h>
17 # include <sys/time.h>
26 #include <sys/types.h>
29 #include <curl/curl.h>
30 #include <libcitadel.h>
33 #include "citserver.h"
38 #include "ctdl_module.h"
39 #include "clientsocket.h"
41 #include "parsedate.h"
43 #include "citadel_dirs.h"
48 struct rssnetcfg *next;
63 char channel_title[256];
67 struct rssnetcfg *rnclist = NULL;
71 * Commit a fetched and parsed RSS item to disk
73 void rss_save_item(struct rss_item *ri) {
75 struct MD5Context md5context;
76 u_char rawdigest[MD5_DIGEST_LEN];
79 struct cdbdata *cdbut;
81 struct CtdlMessage *msg;
82 struct recptypes *recp = NULL;
85 recp = (struct recptypes *) malloc(sizeof(struct recptypes));
86 if (recp == NULL) return;
87 memset(recp, 0, sizeof(struct recptypes));
88 recp->recp_room = strdup(ri->roomlist);
89 recp->num_room = num_tokens(ri->roomlist, '|');
90 recp->recptypes_magic = RECPTYPES_MAGIC;
92 /* Construct a GUID to use in the S_USETABLE table.
93 * If one is not present in the item itself, make one up.
95 if (ri->guid != NULL) {
96 snprintf(utmsgid, sizeof utmsgid, "rss/%s", ri->guid);
100 if (ri->title != NULL) {
101 MD5Update(&md5context, (unsigned char*)ri->title, strlen(ri->title));
103 if (ri->link != NULL) {
104 MD5Update(&md5context, (unsigned char*)ri->link, strlen(ri->link));
106 MD5Final(rawdigest, &md5context);
107 for (i=0; i<MD5_DIGEST_LEN; i++) {
108 sprintf(&utmsgid[i*2], "%02X", (unsigned char) (rawdigest[i] & 0xff));
109 utmsgid[i*2] = tolower(utmsgid[i*2]);
110 utmsgid[(i*2)+1] = tolower(utmsgid[(i*2)+1]);
112 strcat(utmsgid, "_rss2ctdl");
115 /* Find out if we've already seen this item */
116 cdbut = cdb_fetch(CDB_USETABLE, utmsgid, strlen(utmsgid));
118 /* Item has already been seen */
119 CtdlLogPrintf(CTDL_DEBUG, "%s has already been seen\n", utmsgid);
122 /* rewrite the record anyway, to update the timestamp */
123 strcpy(ut.ut_msgid, utmsgid);
124 ut.ut_timestamp = time(NULL);
125 cdb_store(CDB_USETABLE, utmsgid, strlen(utmsgid), &ut, sizeof(struct UseTable) );
128 /* Item has not been seen, so save it. */
130 if (ri->description == NULL) ri->description = strdup("");
131 for (i=strlen(ri->description); i>=0; --i) {
132 if (isspace(ri->description[i])) {
133 ri->description[i] = ' ';
137 msg = malloc(sizeof(struct CtdlMessage));
138 memset(msg, 0, sizeof(struct CtdlMessage));
139 msg->cm_magic = CTDLMESSAGE_MAGIC;
140 msg->cm_anon_type = MES_NORMAL;
141 msg->cm_format_type = FMT_RFC822;
142 msg->cm_fields['A'] = strdup("rss");
143 msg->cm_fields['N'] = strdup(NODENAME);
144 msg->cm_fields['U'] = html_to_ascii(ri->title,
147 msg->cm_fields['T'] = malloc(64);
148 snprintf(msg->cm_fields['T'], 64, "%ld", ri->pubdate);
149 if (!IsEmptyStr(ri->channel_title)) {
150 msg->cm_fields['O'] = strdup(ri->channel_title);
153 msglen = 1024 + strlen(ri->link) + strlen(ri->description) ;
154 msg->cm_fields['M'] = malloc(msglen);
155 snprintf(msg->cm_fields['M'], msglen,
156 "Content-type: text/html\r\n\r\n"
159 "<a href=\"%s\">%s</a>\n"
166 CtdlSubmitMsg(msg, recp, NULL, 0);
167 CtdlFreeMessage(msg);
169 /* write the uidl to the use table so we don't store this item again */
170 strcpy(ut.ut_msgid, utmsgid);
171 ut.ut_timestamp = time(NULL);
172 cdb_store(CDB_USETABLE, utmsgid, strlen(utmsgid), &ut, sizeof(struct UseTable) );
174 free_recipients(recp);
180 * Convert an RDF/RSS datestamp into a time_t
182 time_t rdf_parsedate(char *p)
188 if (strlen(p) < 10) return 0L;
190 memset(&tm, 0, sizeof tm);
192 /* YYYY-MM-DDTHH:MM format...
194 if ( (p[4] == '-') && (p[7] == '-') ) {
195 tm.tm_year = atoi(&p[0]) - 1900;
196 tm.tm_mon = atoi(&p[5]) - 1;
197 tm.tm_mday = atoi(&p[8]);
198 if ( (p[10] == 'T') && (p[13] == ':') ) {
199 tm.tm_hour = atoi(&p[11]);
200 tm.tm_min = atoi(&p[14]);
205 /* hmm... try RFC822 date stamp format */
208 if (t > 0) return(t);
210 /* yeesh. ok, just return the current date and time. */
216 void rss_xml_start(void *data, const char *supplied_el, const char **attr) {
217 struct rss_item *ri = (struct rss_item *) data;
221 /* Axe the namespace, we don't care about it */
222 safestrncpy(el, supplied_el, sizeof el);
223 while (sep = strchr(el, ':'), sep) {
227 if (!strcasecmp(el, "item")) {
228 ++ri->item_tag_nesting;
230 /* Initialize the feed item data structure */
231 if (ri->guid != NULL) free(ri->guid);
233 if (ri->title != NULL) free(ri->title);
235 if (ri->link != NULL) free(ri->link);
237 if (ri->description != NULL) free(ri->description);
238 ri->description = NULL;
240 /* Throw away any existing character data */
241 if (ri->chardata_len > 0) {
244 ri->chardata_len = 0;
252 void rss_xml_end(void *data, const char *supplied_el) {
253 struct rss_item *ri = (struct rss_item *) data;
257 /* Axe the namespace, we don't care about it */
258 safestrncpy(el, supplied_el, sizeof el);
259 while (sep = strchr(el, ':'), sep) {
263 if ( (!strcasecmp(el, "title")) && (ri->item_tag_nesting == 0) && (ri->chardata != NULL) ) {
264 safestrncpy(ri->channel_title, ri->chardata, sizeof ri->channel_title);
265 striplt(ri->channel_title);
268 if ( (!strcasecmp(el, "guid")) && (ri->chardata != NULL) ) {
269 if (ri->guid != NULL) free(ri->guid);
270 striplt(ri->chardata);
271 ri->guid = strdup(ri->chardata);
274 if ( (!strcasecmp(el, "title")) && (ri->chardata != NULL) ) {
275 if (ri->title != NULL) free(ri->title);
276 striplt(ri->chardata);
277 ri->title = strdup(ri->chardata);
280 if ( (!strcasecmp(el, "link")) && (ri->chardata != NULL) ) {
281 if (ri->link != NULL) free(ri->link);
282 striplt(ri->chardata);
283 ri->link = strdup(ri->chardata);
286 if ( (!strcasecmp(el, "description")) && (ri->chardata != NULL) ) {
287 if (ri->description != NULL) free(ri->description);
288 ri->description = strdup(ri->chardata);
291 if ( ((!strcasecmp(el, "pubdate")) || (!strcasecmp(el, "date"))) && (ri->chardata != NULL) ) {
292 striplt(ri->chardata);
293 ri->pubdate = rdf_parsedate(ri->chardata);
296 if (!strcasecmp(el, "item")) {
297 --ri->item_tag_nesting;
301 if ( (!strcasecmp(el, "rss")) || (!strcasecmp(el, "rdf")) ) {
302 CtdlLogPrintf(CTDL_DEBUG, "End of feed detected. Closing parser.\n");
303 ri->done_parsing = 1;
306 if (ri->chardata_len > 0) {
309 ri->chardata_len = 0;
316 * This callback stores up the data which appears in between tags.
318 void rss_xml_chardata(void *data, const XML_Char *s, int len) {
319 struct rss_item *ri = (struct rss_item *) data;
324 old_len = ri->chardata_len;
325 new_len = old_len + len;
326 new_buffer = realloc(ri->chardata, new_len + 1);
327 if (new_buffer != NULL) {
328 memcpy(&new_buffer[old_len], s, len);
329 new_buffer[new_len] = 0;
330 ri->chardata = new_buffer;
331 ri->chardata_len = new_len;
338 * Callback function for passing libcurl's output to expat for parsing
340 size_t rss_libcurl_callback(void *ptr, size_t size, size_t nmemb, void *stream)
342 XML_Parse((XML_Parser)stream, ptr, (size * nmemb), 0);
351 void rss_do_fetching(char *url, char *rooms) {
357 char errmsg[1024] = "";
359 CtdlLogPrintf(CTDL_DEBUG, "Fetching RSS feed <%s>\n", url);
361 curl = curl_easy_init();
363 CtdlLogPrintf(CTDL_ALERT, "Unable to initialize libcurl.\n");
367 xp = XML_ParserCreateNS("UTF-8", ':');
369 CtdlLogPrintf(CTDL_ALERT, "Cannot create XML parser!\n");
370 curl_easy_cleanup(curl);
374 curl_easy_setopt(curl, CURLOPT_URL, url);
375 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
376 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
377 curl_easy_setopt(curl, CURLOPT_WRITEDATA, xp);
378 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, rss_libcurl_callback);
379 curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
380 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
381 curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
382 if (!IsEmptyStr(config.c_ip_addr)) {
383 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
386 memset(&ri, 0, sizeof(struct rss_item));
388 XML_SetElementHandler(xp, rss_xml_start, rss_xml_end);
389 XML_SetCharacterDataHandler(xp, rss_xml_chardata);
390 XML_SetUserData(xp, &ri);
392 if (CtdlThreadCheckStop())
395 curl_easy_cleanup(curl);
399 if (CtdlThreadCheckStop())
402 res = curl_easy_perform(curl);
404 CtdlLogPrintf(CTDL_ALERT, "libcurl error %d: %s\n", res, errmsg);
407 if (CtdlThreadCheckStop())
410 if (ri.done_parsing == 0) XML_Parse(xp, "", 0, 1);
414 curl_easy_cleanup(curl);
417 /* Free the feed item data structure */
418 if (ri.guid != NULL) free(ri.guid);
420 if (ri.title != NULL) free(ri.title);
422 if (ri.link != NULL) free(ri.link);
424 if (ri.description != NULL) free(ri.description);
425 ri.description = NULL;
426 if (ri.chardata_len > 0) {
435 * Scan a room's netconfig to determine whether it is requesting any RSS feeds
437 void rssclient_scan_room(struct ctdlroom *qrbuf, void *data)
439 char filename[PATH_MAX];
444 struct rssnetcfg *rncptr = NULL;
445 struct rssnetcfg *use_this_rncptr = NULL;
449 assoc_file_name(filename, sizeof filename, qrbuf, ctdl_netcfg_dir);
451 if (CtdlThreadCheckStop())
454 /* Only do net processing for rooms that have netconfigs */
455 fp = fopen(filename, "r");
460 while (fgets(buf, sizeof buf, fp) != NULL && !CtdlThreadCheckStop()) {
461 buf[strlen(buf)-1] = 0;
463 extract_token(instr, buf, 0, '|', sizeof instr);
464 if (!strcasecmp(instr, "rssclient")) {
466 use_this_rncptr = NULL;
468 extract_token(feedurl, buf, 1, '|', sizeof feedurl);
470 /* If any other rooms have requested the same feed, then we will just add this
471 * room to the target list for that client request.
473 for (rncptr=rnclist; rncptr!=NULL; rncptr=rncptr->next) {
474 if (!strcmp(rncptr->url, feedurl)) {
475 use_this_rncptr = rncptr;
479 /* Otherwise create a new client request */
480 if (use_this_rncptr == NULL) {
481 rncptr = (struct rssnetcfg *) malloc(sizeof(struct rssnetcfg));
482 if (rncptr != NULL) {
483 rncptr->next = rnclist;
484 safestrncpy(rncptr->url, feedurl, sizeof rncptr->url);
485 rncptr->rooms = NULL;
487 use_this_rncptr = rncptr;
491 /* Add the room name to the request */
492 if (use_this_rncptr != NULL) {
493 if (use_this_rncptr->rooms == NULL) {
494 rncptr->rooms = strdup(qrbuf->QRname);
497 len = strlen(use_this_rncptr->rooms) + strlen(qrbuf->QRname) + 5;
498 ptr = realloc(use_this_rncptr->rooms, len);
501 strcat(ptr, qrbuf->QRname);
502 use_this_rncptr->rooms = ptr;
515 * Scan for rooms that have RSS client requests configured
517 void *rssclient_scan(void *args) {
518 static time_t last_run = 0L;
519 static int doing_rssclient = 0;
520 struct rssnetcfg *rptr = NULL;
521 struct CitContext rssclientCC;
523 /* Give this thread its own private CitContext */
524 CtdlFillPrivateContext(&rssclientCC, "rssclient");
525 citthread_setspecific(MyConKey, (void *)&rssclientCC );
527 CtdlThreadAllocTSD();
530 * This is a simple concurrency check to make sure only one rssclient run
531 * is done at a time. We could do this with a mutex, but since we
532 * don't really require extremely fine granularity here, we'll do it
533 * with a static variable instead.
535 if (doing_rssclient) return NULL;
538 CtdlLogPrintf(CTDL_DEBUG, "rssclient started\n");
539 ForEachRoom(rssclient_scan_room, NULL);
541 while (rnclist != NULL && !CtdlThreadCheckStop()) {
542 rss_do_fetching(rnclist->url, rnclist->rooms);
544 rnclist = rnclist->next;
545 if (rptr->rooms != NULL) free(rptr->rooms);
549 CtdlLogPrintf(CTDL_DEBUG, "rssclient ended\n");
550 last_run = time(NULL);
552 if (!CtdlThreadCheckStop())
553 CtdlThreadSchedule ("RSS Client", CTDLTHREAD_BIGSTACK, rssclient_scan, NULL, last_run + config.c_net_freq);
555 CtdlLogPrintf(CTDL_DEBUG, "rssclient: Task STOPPED.\n");
560 CTDL_MODULE_INIT(rssclient)
564 CtdlLogPrintf(CTDL_INFO, "%s\n", curl_version());
565 CtdlThreadSchedule ("RSS Client", CTDLTHREAD_BIGSTACK, rssclient_scan, NULL, 0);
567 /* return our Subversion id for the Log */
568 return "$Id: serv_rssclient.c 5652 2007-10-29 20:14:48Z ajc $";