4 * Bring external RSS feeds into rooms.
6 * Copyright (c) 2007-2009 by the citadel.org team
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
27 #if TIME_WITH_SYS_TIME
28 # include <sys/time.h>
32 # include <sys/time.h>
41 #include <sys/types.h>
44 #include <curl/curl.h>
45 #include <libcitadel.h>
48 #include "citserver.h"
52 #include "ctdl_module.h"
53 #include "clientsocket.h"
55 #include "parsedate.h"
57 #include "citadel_dirs.h"
62 struct rssnetcfg *next;
77 char channel_title[256];
79 char *author_or_creator;
82 struct rssnetcfg *rnclist = NULL;
86 * Commit a fetched and parsed RSS item to disk
88 void rss_save_item(struct rss_item *ri) {
90 struct MD5Context md5context;
91 u_char rawdigest[MD5_DIGEST_LEN];
94 struct cdbdata *cdbut;
96 struct CtdlMessage *msg;
97 struct recptypes *recp = NULL;
100 recp = (struct recptypes *) malloc(sizeof(struct recptypes));
101 if (recp == NULL) return;
102 memset(recp, 0, sizeof(struct recptypes));
103 recp->recp_room = strdup(ri->roomlist);
104 recp->num_room = num_tokens(ri->roomlist, '|');
105 recp->recptypes_magic = RECPTYPES_MAGIC;
107 /* Construct a GUID to use in the S_USETABLE table.
108 * If one is not present in the item itself, make one up.
110 if (ri->guid != NULL) {
111 snprintf(utmsgid, sizeof utmsgid, "rss/%s", ri->guid);
114 MD5Init(&md5context);
115 if (ri->title != NULL) {
116 MD5Update(&md5context, (unsigned char*)ri->title, strlen(ri->title));
118 if (ri->link != NULL) {
119 MD5Update(&md5context, (unsigned char*)ri->link, strlen(ri->link));
121 MD5Final(rawdigest, &md5context);
122 for (i=0; i<MD5_DIGEST_LEN; i++) {
123 sprintf(&utmsgid[i*2], "%02X", (unsigned char) (rawdigest[i] & 0xff));
124 utmsgid[i*2] = tolower(utmsgid[i*2]);
125 utmsgid[(i*2)+1] = tolower(utmsgid[(i*2)+1]);
127 strcat(utmsgid, "_rss2ctdl");
130 /* Find out if we've already seen this item */
131 cdbut = cdb_fetch(CDB_USETABLE, utmsgid, strlen(utmsgid));
133 /* Item has already been seen */
134 CtdlLogPrintf(CTDL_DEBUG, "%s has already been seen\n", utmsgid);
137 /* rewrite the record anyway, to update the timestamp */
138 strcpy(ut.ut_msgid, utmsgid);
139 ut.ut_timestamp = time(NULL);
140 cdb_store(CDB_USETABLE, utmsgid, strlen(utmsgid), &ut, sizeof(struct UseTable) );
143 /* Item has not been seen, so save it. */
145 if (ri->description == NULL) ri->description = strdup("");
146 for (i=strlen(ri->description); i>=0; --i) {
147 if (isspace(ri->description[i])) {
148 ri->description[i] = ' ';
152 msg = malloc(sizeof(struct CtdlMessage));
153 memset(msg, 0, sizeof(struct CtdlMessage));
154 msg->cm_magic = CTDLMESSAGE_MAGIC;
155 msg->cm_anon_type = MES_NORMAL;
156 msg->cm_format_type = FMT_RFC822;
158 if (ri->author_or_creator != NULL) {
159 msg->cm_fields['A'] = html_to_ascii(ri->author_or_creator,
160 strlen(ri->author_or_creator), 512, 0);
161 striplt(msg->cm_fields['A']);
164 msg->cm_fields['A'] = strdup("rss");
167 msg->cm_fields['N'] = strdup(NODENAME);
168 if (ri->title != NULL) {
169 msg->cm_fields['U'] = html_to_ascii(ri->title, strlen(ri->title), 512, 0);
170 striplt(msg->cm_fields['U']);
172 msg->cm_fields['T'] = malloc(64);
173 snprintf(msg->cm_fields['T'], 64, "%ld", ri->pubdate);
174 if (ri->channel_title != NULL) {
175 if (!IsEmptyStr(ri->channel_title)) {
176 msg->cm_fields['O'] = strdup(ri->channel_title);
179 if (ri->link == NULL)
180 ri->link = strdup("");
181 msglen += 1024 + strlen(ri->link) + strlen(ri->description) ;
182 msg->cm_fields['M'] = malloc(msglen);
183 snprintf(msg->cm_fields['M'], msglen,
184 "Content-type: text/html; charset=\"UTF-8\"\r\n\r\n"
187 "<a href=\"%s\">%s</a>\n"
194 CtdlSubmitMsg(msg, recp, NULL, 0);
195 CtdlFreeMessage(msg);
197 /* write the uidl to the use table so we don't store this item again */
198 strcpy(ut.ut_msgid, utmsgid);
199 ut.ut_timestamp = time(NULL);
200 cdb_store(CDB_USETABLE, utmsgid, strlen(utmsgid), &ut, sizeof(struct UseTable) );
202 free_recipients(recp);
208 * Convert an RDF/RSS datestamp into a time_t
210 time_t rdf_parsedate(char *p)
216 if (strlen(p) < 10) return 0L;
218 memset(&tm, 0, sizeof tm);
220 /* YYYY-MM-DDTHH:MM format...
222 if ( (p[4] == '-') && (p[7] == '-') ) {
223 tm.tm_year = atoi(&p[0]) - 1900;
224 tm.tm_mon = atoi(&p[5]) - 1;
225 tm.tm_mday = atoi(&p[8]);
226 if ( (p[10] == 'T') && (p[13] == ':') ) {
227 tm.tm_hour = atoi(&p[11]);
228 tm.tm_min = atoi(&p[14]);
233 /* hmm... try RFC822 date stamp format */
236 if (t > 0) return(t);
238 /* yeesh. ok, just return the current date and time. */
244 void rss_xml_start(void *data, const char *supplied_el, const char **attr) {
245 struct rss_item *ri = (struct rss_item *) data;
249 /* Axe the namespace, we don't care about it */
250 safestrncpy(el, supplied_el, sizeof el);
251 while (sep = strchr(el, ':'), sep) {
255 if (!strcasecmp(el, "item")) {
256 ++ri->item_tag_nesting;
258 /* Initialize the feed item data structure */
259 if (ri->guid != NULL) free(ri->guid);
261 if (ri->title != NULL) free(ri->title);
263 if (ri->link != NULL) free(ri->link);
265 if (ri->author_or_creator != NULL) free(ri->author_or_creator);
266 ri->author_or_creator = NULL;
267 if (ri->description != NULL) free(ri->description);
268 ri->description = NULL;
270 /* Throw away any existing character data */
271 if (ri->chardata_len > 0) {
274 ri->chardata_len = 0;
282 void rss_xml_end(void *data, const char *supplied_el) {
283 struct rss_item *ri = (struct rss_item *) data;
287 /* Axe the namespace, we don't care about it */
288 safestrncpy(el, supplied_el, sizeof el);
289 while (sep = strchr(el, ':'), sep) {
293 if ( (!strcasecmp(el, "title")) && (ri->item_tag_nesting == 0) && (ri->chardata != NULL) ) {
294 safestrncpy(ri->channel_title, ri->chardata, sizeof ri->channel_title);
295 striplt(ri->channel_title);
298 if ( (!strcasecmp(el, "guid")) && (ri->chardata != NULL) ) {
299 if (ri->guid != NULL) free(ri->guid);
300 striplt(ri->chardata);
301 ri->guid = strdup(ri->chardata);
304 if ( (!strcasecmp(el, "title")) && (ri->chardata != NULL) ) {
305 if (ri->title != NULL) free(ri->title);
306 striplt(ri->chardata);
307 ri->title = strdup(ri->chardata);
310 if ( (!strcasecmp(el, "link")) && (ri->chardata != NULL) ) {
311 if (ri->link != NULL) free(ri->link);
312 striplt(ri->chardata);
313 ri->link = strdup(ri->chardata);
316 if ( (!strcasecmp(el, "description")) && (ri->chardata != NULL) ) {
317 if (ri->description != NULL) free(ri->description);
318 ri->description = strdup(ri->chardata);
321 if ( ((!strcasecmp(el, "pubdate")) || (!strcasecmp(el, "date"))) && (ri->chardata != NULL) ) {
322 striplt(ri->chardata);
323 ri->pubdate = rdf_parsedate(ri->chardata);
326 if ( ((!strcasecmp(el, "author")) || (!strcasecmp(el, "creator"))) && (ri->chardata != NULL) ) {
327 if (ri->author_or_creator != NULL) free(ri->author_or_creator);
328 striplt(ri->chardata);
329 ri->author_or_creator = strdup(ri->chardata);
332 if (!strcasecmp(el, "item")) {
333 --ri->item_tag_nesting;
337 if ( (!strcasecmp(el, "rss")) || (!strcasecmp(el, "rdf")) ) {
338 CtdlLogPrintf(CTDL_DEBUG, "End of feed detected. Closing parser.\n");
339 ri->done_parsing = 1;
342 if (ri->chardata_len > 0) {
345 ri->chardata_len = 0;
352 * This callback stores up the data which appears in between tags.
354 void rss_xml_chardata(void *data, const XML_Char *s, int len) {
355 struct rss_item *ri = (struct rss_item *) data;
360 old_len = ri->chardata_len;
361 new_len = old_len + len;
362 new_buffer = realloc(ri->chardata, new_len + 1);
363 if (new_buffer != NULL) {
364 memcpy(&new_buffer[old_len], s, len);
365 new_buffer[new_len] = 0;
366 ri->chardata = new_buffer;
367 ri->chardata_len = new_len;
374 * Callback function for passing libcurl's output to expat for parsing
376 size_t rss_libcurl_callback(void *ptr, size_t size, size_t nmemb, void *stream)
378 XML_Parse((XML_Parser)stream, ptr, (size * nmemb), 0);
387 void rss_do_fetching(char *url, char *rooms) {
393 char errmsg[1024] = "";
395 CtdlLogPrintf(CTDL_DEBUG, "Fetching RSS feed <%s>\n", url);
397 curl = curl_easy_init();
399 CtdlLogPrintf(CTDL_ALERT, "Unable to initialize libcurl.\n");
403 xp = XML_ParserCreateNS("UTF-8", ':');
405 CtdlLogPrintf(CTDL_ALERT, "Cannot create XML parser!\n");
406 curl_easy_cleanup(curl);
410 curl_easy_setopt(curl, CURLOPT_URL, url);
411 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
412 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
413 curl_easy_setopt(curl, CURLOPT_WRITEDATA, xp);
414 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, rss_libcurl_callback);
415 curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
416 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
417 #ifdef CURLOPT_HTTP_CONTENT_DECODING
418 curl_easy_setopt(curl, CURLOPT_HTTP_CONTENT_DECODING, 1);
419 curl_easy_setopt(curl, CURLOPT_ENCODING, "");
421 curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
422 curl_easy_setopt(curl, CURLOPT_TIMEOUT, 180); /* die after 180 seconds */
423 if (!IsEmptyStr(config.c_ip_addr)) {
424 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
427 memset(&ri, 0, sizeof(struct rss_item));
429 XML_SetElementHandler(xp, rss_xml_start, rss_xml_end);
430 XML_SetCharacterDataHandler(xp, rss_xml_chardata);
431 XML_SetUserData(xp, &ri);
433 if (CtdlThreadCheckStop())
436 curl_easy_cleanup(curl);
440 if (CtdlThreadCheckStop())
443 res = curl_easy_perform(curl);
445 CtdlLogPrintf(CTDL_ALERT, "libcurl error %d: %s\n", res, errmsg);
448 if (CtdlThreadCheckStop())
451 if (ri.done_parsing == 0) XML_Parse(xp, "", 0, 1);
455 curl_easy_cleanup(curl);
458 /* Free the feed item data structure */
459 if (ri.guid != NULL) free(ri.guid);
461 if (ri.title != NULL) free(ri.title);
463 if (ri.link != NULL) free(ri.link);
465 if (ri.author_or_creator != NULL) free(ri.author_or_creator);
466 ri.author_or_creator = NULL;
467 if (ri.description != NULL) free(ri.description);
468 ri.description = NULL;
469 if (ri.chardata_len > 0) {
478 * Scan a room's netconfig to determine whether it is requesting any RSS feeds
480 void rssclient_scan_room(struct ctdlroom *qrbuf, void *data)
482 char filename[PATH_MAX];
487 struct rssnetcfg *rncptr = NULL;
488 struct rssnetcfg *use_this_rncptr = NULL;
492 assoc_file_name(filename, sizeof filename, qrbuf, ctdl_netcfg_dir);
494 if (CtdlThreadCheckStop())
497 /* Only do net processing for rooms that have netconfigs */
498 fp = fopen(filename, "r");
503 while (fgets(buf, sizeof buf, fp) != NULL && !CtdlThreadCheckStop()) {
504 buf[strlen(buf)-1] = 0;
506 extract_token(instr, buf, 0, '|', sizeof instr);
507 if (!strcasecmp(instr, "rssclient")) {
509 use_this_rncptr = NULL;
511 extract_token(feedurl, buf, 1, '|', sizeof feedurl);
513 /* If any other rooms have requested the same feed, then we will just add this
514 * room to the target list for that client request.
516 for (rncptr=rnclist; rncptr!=NULL; rncptr=rncptr->next) {
517 if (!strcmp(rncptr->url, feedurl)) {
518 use_this_rncptr = rncptr;
522 /* Otherwise create a new client request */
523 if (use_this_rncptr == NULL) {
524 rncptr = (struct rssnetcfg *) malloc(sizeof(struct rssnetcfg));
525 if (rncptr != NULL) {
526 rncptr->next = rnclist;
527 safestrncpy(rncptr->url, feedurl, sizeof rncptr->url);
528 rncptr->rooms = NULL;
530 use_this_rncptr = rncptr;
534 /* Add the room name to the request */
535 if (use_this_rncptr != NULL) {
536 if (use_this_rncptr->rooms == NULL) {
537 rncptr->rooms = strdup(qrbuf->QRname);
540 len = strlen(use_this_rncptr->rooms) + strlen(qrbuf->QRname) + 5;
541 ptr = realloc(use_this_rncptr->rooms, len);
544 strcat(ptr, qrbuf->QRname);
545 use_this_rncptr->rooms = ptr;
558 * Scan for rooms that have RSS client requests configured
560 void *rssclient_scan(void *args) {
561 static time_t last_run = 0L;
562 static int doing_rssclient = 0;
563 struct rssnetcfg *rptr = NULL;
564 struct CitContext rssclientCC;
566 /* Give this thread its own private CitContext */
567 CtdlFillSystemContext(&rssclientCC, "rssclient");
568 citthread_setspecific(MyConKey, (void *)&rssclientCC );
570 CtdlThreadAllocTSD();
573 * This is a simple concurrency check to make sure only one rssclient run
574 * is done at a time. We could do this with a mutex, but since we
575 * don't really require extremely fine granularity here, we'll do it
576 * with a static variable instead.
578 if (doing_rssclient) return NULL;
581 CtdlLogPrintf(CTDL_DEBUG, "rssclient started\n");
582 CtdlForEachRoom(rssclient_scan_room, NULL);
584 while (rnclist != NULL && !CtdlThreadCheckStop()) {
585 rss_do_fetching(rnclist->url, rnclist->rooms);
587 rnclist = rnclist->next;
588 if (rptr->rooms != NULL) free(rptr->rooms);
592 CtdlLogPrintf(CTDL_DEBUG, "rssclient ended\n");
593 last_run = time(NULL);
595 if (!CtdlThreadCheckStop())
596 CtdlThreadSchedule ("RSS Client", CTDLTHREAD_BIGSTACK, rssclient_scan, NULL, last_run + config.c_net_freq);
598 CtdlLogPrintf(CTDL_DEBUG, "rssclient: Task STOPPED.\n");
603 CTDL_MODULE_INIT(rssclient)
607 CtdlLogPrintf(CTDL_INFO, "%s\n", curl_version());
608 CtdlThreadSchedule ("RSS Client", CTDLTHREAD_BIGSTACK, rssclient_scan, NULL, 0);
610 /* return our Subversion id for the Log */