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];
65 char *author_or_creator;
68 struct rssnetcfg *rnclist = NULL;
72 * Commit a fetched and parsed RSS item to disk
74 void rss_save_item(struct rss_item *ri) {
76 struct MD5Context md5context;
77 u_char rawdigest[MD5_DIGEST_LEN];
80 struct cdbdata *cdbut;
82 struct CtdlMessage *msg;
83 struct recptypes *recp = NULL;
86 recp = (struct recptypes *) malloc(sizeof(struct recptypes));
87 if (recp == NULL) return;
88 memset(recp, 0, sizeof(struct recptypes));
89 recp->recp_room = strdup(ri->roomlist);
90 recp->num_room = num_tokens(ri->roomlist, '|');
91 recp->recptypes_magic = RECPTYPES_MAGIC;
93 /* Construct a GUID to use in the S_USETABLE table.
94 * If one is not present in the item itself, make one up.
96 if (ri->guid != NULL) {
97 snprintf(utmsgid, sizeof utmsgid, "rss/%s", ri->guid);
100 MD5Init(&md5context);
101 if (ri->title != NULL) {
102 MD5Update(&md5context, (unsigned char*)ri->title, strlen(ri->title));
104 if (ri->link != NULL) {
105 MD5Update(&md5context, (unsigned char*)ri->link, strlen(ri->link));
107 MD5Final(rawdigest, &md5context);
108 for (i=0; i<MD5_DIGEST_LEN; i++) {
109 sprintf(&utmsgid[i*2], "%02X", (unsigned char) (rawdigest[i] & 0xff));
110 utmsgid[i*2] = tolower(utmsgid[i*2]);
111 utmsgid[(i*2)+1] = tolower(utmsgid[(i*2)+1]);
113 strcat(utmsgid, "_rss2ctdl");
116 /* Find out if we've already seen this item */
117 cdbut = cdb_fetch(CDB_USETABLE, utmsgid, strlen(utmsgid));
119 /* Item has already been seen */
120 CtdlLogPrintf(CTDL_DEBUG, "%s has already been seen\n", utmsgid);
123 /* rewrite the record anyway, to update the timestamp */
124 strcpy(ut.ut_msgid, utmsgid);
125 ut.ut_timestamp = time(NULL);
126 cdb_store(CDB_USETABLE, utmsgid, strlen(utmsgid), &ut, sizeof(struct UseTable) );
129 /* Item has not been seen, so save it. */
131 if (ri->description == NULL) ri->description = strdup("");
132 for (i=strlen(ri->description); i>=0; --i) {
133 if (isspace(ri->description[i])) {
134 ri->description[i] = ' ';
138 msg = malloc(sizeof(struct CtdlMessage));
139 memset(msg, 0, sizeof(struct CtdlMessage));
140 msg->cm_magic = CTDLMESSAGE_MAGIC;
141 msg->cm_anon_type = MES_NORMAL;
142 msg->cm_format_type = FMT_RFC822;
144 if (ri->author_or_creator != NULL) {
145 msg->cm_fields['A'] = html_to_ascii(ri->author_or_creator,
146 strlen(ri->author_or_creator), 512, 0);
147 striplt(msg->cm_fields['A']);
150 msg->cm_fields['A'] = strdup("rss");
153 msg->cm_fields['N'] = strdup(NODENAME);
154 if (ri->title != NULL) {
155 msg->cm_fields['U'] = html_to_ascii(ri->title, strlen(ri->title), 512, 0);
156 striplt(msg->cm_fields['U']);
158 msg->cm_fields['T'] = malloc(64);
159 snprintf(msg->cm_fields['T'], 64, "%ld", ri->pubdate);
160 if (ri->channel_title != NULL) {
161 if (!IsEmptyStr(ri->channel_title)) {
162 msg->cm_fields['O'] = strdup(ri->channel_title);
165 if (ri->link == NULL)
166 ri->link = strdup("");
167 msglen += 1024 + strlen(ri->link) + strlen(ri->description) ;
168 msg->cm_fields['M'] = malloc(msglen);
169 snprintf(msg->cm_fields['M'], msglen,
170 "Content-type: text/html\r\n\r\n"
173 "<a href=\"%s\">%s</a>\n"
180 CtdlSubmitMsg(msg, recp, NULL, 0);
181 CtdlFreeMessage(msg);
183 /* write the uidl to the use table so we don't store this item again */
184 strcpy(ut.ut_msgid, utmsgid);
185 ut.ut_timestamp = time(NULL);
186 cdb_store(CDB_USETABLE, utmsgid, strlen(utmsgid), &ut, sizeof(struct UseTable) );
188 free_recipients(recp);
194 * Convert an RDF/RSS datestamp into a time_t
196 time_t rdf_parsedate(char *p)
202 if (strlen(p) < 10) return 0L;
204 memset(&tm, 0, sizeof tm);
206 /* YYYY-MM-DDTHH:MM format...
208 if ( (p[4] == '-') && (p[7] == '-') ) {
209 tm.tm_year = atoi(&p[0]) - 1900;
210 tm.tm_mon = atoi(&p[5]) - 1;
211 tm.tm_mday = atoi(&p[8]);
212 if ( (p[10] == 'T') && (p[13] == ':') ) {
213 tm.tm_hour = atoi(&p[11]);
214 tm.tm_min = atoi(&p[14]);
219 /* hmm... try RFC822 date stamp format */
222 if (t > 0) return(t);
224 /* yeesh. ok, just return the current date and time. */
230 void rss_xml_start(void *data, const char *supplied_el, const char **attr) {
231 struct rss_item *ri = (struct rss_item *) data;
235 /* Axe the namespace, we don't care about it */
236 safestrncpy(el, supplied_el, sizeof el);
237 while (sep = strchr(el, ':'), sep) {
241 if (!strcasecmp(el, "item")) {
242 ++ri->item_tag_nesting;
244 /* Initialize the feed item data structure */
245 if (ri->guid != NULL) free(ri->guid);
247 if (ri->title != NULL) free(ri->title);
249 if (ri->link != NULL) free(ri->link);
251 if (ri->author_or_creator != NULL) free(ri->author_or_creator);
252 ri->author_or_creator = NULL;
253 if (ri->description != NULL) free(ri->description);
254 ri->description = NULL;
256 /* Throw away any existing character data */
257 if (ri->chardata_len > 0) {
260 ri->chardata_len = 0;
268 void rss_xml_end(void *data, const char *supplied_el) {
269 struct rss_item *ri = (struct rss_item *) data;
273 /* Axe the namespace, we don't care about it */
274 safestrncpy(el, supplied_el, sizeof el);
275 while (sep = strchr(el, ':'), sep) {
279 if ( (!strcasecmp(el, "title")) && (ri->item_tag_nesting == 0) && (ri->chardata != NULL) ) {
280 safestrncpy(ri->channel_title, ri->chardata, sizeof ri->channel_title);
281 striplt(ri->channel_title);
284 if ( (!strcasecmp(el, "guid")) && (ri->chardata != NULL) ) {
285 if (ri->guid != NULL) free(ri->guid);
286 striplt(ri->chardata);
287 ri->guid = strdup(ri->chardata);
290 if ( (!strcasecmp(el, "title")) && (ri->chardata != NULL) ) {
291 if (ri->title != NULL) free(ri->title);
292 striplt(ri->chardata);
293 ri->title = strdup(ri->chardata);
296 if ( (!strcasecmp(el, "link")) && (ri->chardata != NULL) ) {
297 if (ri->link != NULL) free(ri->link);
298 striplt(ri->chardata);
299 ri->link = strdup(ri->chardata);
302 if ( (!strcasecmp(el, "description")) && (ri->chardata != NULL) ) {
303 if (ri->description != NULL) free(ri->description);
304 ri->description = strdup(ri->chardata);
307 if ( ((!strcasecmp(el, "pubdate")) || (!strcasecmp(el, "date"))) && (ri->chardata != NULL) ) {
308 striplt(ri->chardata);
309 ri->pubdate = rdf_parsedate(ri->chardata);
312 if ( ((!strcasecmp(el, "author")) || (!strcasecmp(el, "creator"))) && (ri->chardata != NULL) ) {
313 if (ri->author_or_creator != NULL) free(ri->author_or_creator);
314 striplt(ri->chardata);
315 ri->author_or_creator = strdup(ri->chardata);
318 if (!strcasecmp(el, "item")) {
319 --ri->item_tag_nesting;
323 if ( (!strcasecmp(el, "rss")) || (!strcasecmp(el, "rdf")) ) {
324 CtdlLogPrintf(CTDL_DEBUG, "End of feed detected. Closing parser.\n");
325 ri->done_parsing = 1;
328 if (ri->chardata_len > 0) {
331 ri->chardata_len = 0;
338 * This callback stores up the data which appears in between tags.
340 void rss_xml_chardata(void *data, const XML_Char *s, int len) {
341 struct rss_item *ri = (struct rss_item *) data;
346 old_len = ri->chardata_len;
347 new_len = old_len + len;
348 new_buffer = realloc(ri->chardata, new_len + 1);
349 if (new_buffer != NULL) {
350 memcpy(&new_buffer[old_len], s, len);
351 new_buffer[new_len] = 0;
352 ri->chardata = new_buffer;
353 ri->chardata_len = new_len;
360 * Callback function for passing libcurl's output to expat for parsing
362 size_t rss_libcurl_callback(void *ptr, size_t size, size_t nmemb, void *stream)
364 XML_Parse((XML_Parser)stream, ptr, (size * nmemb), 0);
373 void rss_do_fetching(char *url, char *rooms) {
379 char errmsg[1024] = "";
381 CtdlLogPrintf(CTDL_DEBUG, "Fetching RSS feed <%s>\n", url);
383 curl = curl_easy_init();
385 CtdlLogPrintf(CTDL_ALERT, "Unable to initialize libcurl.\n");
389 xp = XML_ParserCreateNS("UTF-8", ':');
391 CtdlLogPrintf(CTDL_ALERT, "Cannot create XML parser!\n");
392 curl_easy_cleanup(curl);
396 curl_easy_setopt(curl, CURLOPT_URL, url);
397 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
398 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
399 curl_easy_setopt(curl, CURLOPT_WRITEDATA, xp);
400 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, rss_libcurl_callback);
401 curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
402 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
403 #ifdef CURLOPT_HTTP_CONTENT_DECODING
404 curl_easy_setopt(curl, CURLOPT_HTTP_CONTENT_DECODING, 1);
405 curl_easy_setopt(curl, CURLOPT_ENCODING, "");
407 curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
408 curl_easy_setopt(curl, CURLOPT_TIMEOUT, 180); /* die after 180 seconds */
409 if (!IsEmptyStr(config.c_ip_addr)) {
410 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
413 memset(&ri, 0, sizeof(struct rss_item));
415 XML_SetElementHandler(xp, rss_xml_start, rss_xml_end);
416 XML_SetCharacterDataHandler(xp, rss_xml_chardata);
417 XML_SetUserData(xp, &ri);
419 if (CtdlThreadCheckStop())
422 curl_easy_cleanup(curl);
426 if (CtdlThreadCheckStop())
429 res = curl_easy_perform(curl);
431 CtdlLogPrintf(CTDL_ALERT, "libcurl error %d: %s\n", res, errmsg);
434 if (CtdlThreadCheckStop())
437 if (ri.done_parsing == 0) XML_Parse(xp, "", 0, 1);
441 curl_easy_cleanup(curl);
444 /* Free the feed item data structure */
445 if (ri.guid != NULL) free(ri.guid);
447 if (ri.title != NULL) free(ri.title);
449 if (ri.link != NULL) free(ri.link);
451 if (ri.author_or_creator != NULL) free(ri.author_or_creator);
452 ri.author_or_creator = NULL;
453 if (ri.description != NULL) free(ri.description);
454 ri.description = NULL;
455 if (ri.chardata_len > 0) {
464 * Scan a room's netconfig to determine whether it is requesting any RSS feeds
466 void rssclient_scan_room(struct ctdlroom *qrbuf, void *data)
468 char filename[PATH_MAX];
473 struct rssnetcfg *rncptr = NULL;
474 struct rssnetcfg *use_this_rncptr = NULL;
478 assoc_file_name(filename, sizeof filename, qrbuf, ctdl_netcfg_dir);
480 if (CtdlThreadCheckStop())
483 /* Only do net processing for rooms that have netconfigs */
484 fp = fopen(filename, "r");
489 while (fgets(buf, sizeof buf, fp) != NULL && !CtdlThreadCheckStop()) {
490 buf[strlen(buf)-1] = 0;
492 extract_token(instr, buf, 0, '|', sizeof instr);
493 if (!strcasecmp(instr, "rssclient")) {
495 use_this_rncptr = NULL;
497 extract_token(feedurl, buf, 1, '|', sizeof feedurl);
499 /* If any other rooms have requested the same feed, then we will just add this
500 * room to the target list for that client request.
502 for (rncptr=rnclist; rncptr!=NULL; rncptr=rncptr->next) {
503 if (!strcmp(rncptr->url, feedurl)) {
504 use_this_rncptr = rncptr;
508 /* Otherwise create a new client request */
509 if (use_this_rncptr == NULL) {
510 rncptr = (struct rssnetcfg *) malloc(sizeof(struct rssnetcfg));
511 if (rncptr != NULL) {
512 rncptr->next = rnclist;
513 safestrncpy(rncptr->url, feedurl, sizeof rncptr->url);
514 rncptr->rooms = NULL;
516 use_this_rncptr = rncptr;
520 /* Add the room name to the request */
521 if (use_this_rncptr != NULL) {
522 if (use_this_rncptr->rooms == NULL) {
523 rncptr->rooms = strdup(qrbuf->QRname);
526 len = strlen(use_this_rncptr->rooms) + strlen(qrbuf->QRname) + 5;
527 ptr = realloc(use_this_rncptr->rooms, len);
530 strcat(ptr, qrbuf->QRname);
531 use_this_rncptr->rooms = ptr;
544 * Scan for rooms that have RSS client requests configured
546 void *rssclient_scan(void *args) {
547 static time_t last_run = 0L;
548 static int doing_rssclient = 0;
549 struct rssnetcfg *rptr = NULL;
550 struct CitContext rssclientCC;
552 /* Give this thread its own private CitContext */
553 CtdlFillSystemContext(&rssclientCC, "rssclient");
554 citthread_setspecific(MyConKey, (void *)&rssclientCC );
556 CtdlThreadAllocTSD();
559 * This is a simple concurrency check to make sure only one rssclient run
560 * is done at a time. We could do this with a mutex, but since we
561 * don't really require extremely fine granularity here, we'll do it
562 * with a static variable instead.
564 if (doing_rssclient) return NULL;
567 CtdlLogPrintf(CTDL_DEBUG, "rssclient started\n");
568 ForEachRoom(rssclient_scan_room, NULL);
570 while (rnclist != NULL && !CtdlThreadCheckStop()) {
571 rss_do_fetching(rnclist->url, rnclist->rooms);
573 rnclist = rnclist->next;
574 if (rptr->rooms != NULL) free(rptr->rooms);
578 CtdlLogPrintf(CTDL_DEBUG, "rssclient ended\n");
579 last_run = time(NULL);
581 if (!CtdlThreadCheckStop())
582 CtdlThreadSchedule ("RSS Client", CTDLTHREAD_BIGSTACK, rssclient_scan, NULL, last_run + config.c_net_freq);
584 CtdlLogPrintf(CTDL_DEBUG, "rssclient: Task STOPPED.\n");
589 CTDL_MODULE_INIT(rssclient)
593 CtdlLogPrintf(CTDL_INFO, "%s\n", curl_version());
594 CtdlThreadSchedule ("RSS Client", CTDLTHREAD_BIGSTACK, rssclient_scan, NULL, 0);
596 /* return our Subversion id for the Log */