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);
166 msglen = 1024 + strlen(ri->link) + strlen(ri->description) ;
167 msg->cm_fields['M'] = malloc(msglen);
168 snprintf(msg->cm_fields['M'], msglen,
169 "Content-type: text/html\r\n\r\n"
172 "<a href=\"%s\">%s</a>\n"
179 CtdlSubmitMsg(msg, recp, NULL, 0);
180 CtdlFreeMessage(msg);
182 /* write the uidl to the use table so we don't store this item again */
183 strcpy(ut.ut_msgid, utmsgid);
184 ut.ut_timestamp = time(NULL);
185 cdb_store(CDB_USETABLE, utmsgid, strlen(utmsgid), &ut, sizeof(struct UseTable) );
187 free_recipients(recp);
193 * Convert an RDF/RSS datestamp into a time_t
195 time_t rdf_parsedate(char *p)
201 if (strlen(p) < 10) return 0L;
203 memset(&tm, 0, sizeof tm);
205 /* YYYY-MM-DDTHH:MM format...
207 if ( (p[4] == '-') && (p[7] == '-') ) {
208 tm.tm_year = atoi(&p[0]) - 1900;
209 tm.tm_mon = atoi(&p[5]) - 1;
210 tm.tm_mday = atoi(&p[8]);
211 if ( (p[10] == 'T') && (p[13] == ':') ) {
212 tm.tm_hour = atoi(&p[11]);
213 tm.tm_min = atoi(&p[14]);
218 /* hmm... try RFC822 date stamp format */
221 if (t > 0) return(t);
223 /* yeesh. ok, just return the current date and time. */
229 void rss_xml_start(void *data, const char *supplied_el, const char **attr) {
230 struct rss_item *ri = (struct rss_item *) data;
234 /* Axe the namespace, we don't care about it */
235 safestrncpy(el, supplied_el, sizeof el);
236 while (sep = strchr(el, ':'), sep) {
240 if (!strcasecmp(el, "item")) {
241 ++ri->item_tag_nesting;
243 /* Initialize the feed item data structure */
244 if (ri->guid != NULL) free(ri->guid);
246 if (ri->title != NULL) free(ri->title);
248 if (ri->link != NULL) free(ri->link);
250 if (ri->author_or_creator != NULL) free(ri->author_or_creator);
251 ri->author_or_creator = NULL;
252 if (ri->description != NULL) free(ri->description);
253 ri->description = NULL;
255 /* Throw away any existing character data */
256 if (ri->chardata_len > 0) {
259 ri->chardata_len = 0;
267 void rss_xml_end(void *data, const char *supplied_el) {
268 struct rss_item *ri = (struct rss_item *) data;
272 /* Axe the namespace, we don't care about it */
273 safestrncpy(el, supplied_el, sizeof el);
274 while (sep = strchr(el, ':'), sep) {
278 if ( (!strcasecmp(el, "title")) && (ri->item_tag_nesting == 0) && (ri->chardata != NULL) ) {
279 safestrncpy(ri->channel_title, ri->chardata, sizeof ri->channel_title);
280 striplt(ri->channel_title);
283 if ( (!strcasecmp(el, "guid")) && (ri->chardata != NULL) ) {
284 if (ri->guid != NULL) free(ri->guid);
285 striplt(ri->chardata);
286 ri->guid = strdup(ri->chardata);
289 if ( (!strcasecmp(el, "title")) && (ri->chardata != NULL) ) {
290 if (ri->title != NULL) free(ri->title);
291 striplt(ri->chardata);
292 ri->title = strdup(ri->chardata);
295 if ( (!strcasecmp(el, "link")) && (ri->chardata != NULL) ) {
296 if (ri->link != NULL) free(ri->link);
297 striplt(ri->chardata);
298 ri->link = strdup(ri->chardata);
301 if ( (!strcasecmp(el, "description")) && (ri->chardata != NULL) ) {
302 if (ri->description != NULL) free(ri->description);
303 ri->description = strdup(ri->chardata);
306 if ( ((!strcasecmp(el, "pubdate")) || (!strcasecmp(el, "date"))) && (ri->chardata != NULL) ) {
307 striplt(ri->chardata);
308 ri->pubdate = rdf_parsedate(ri->chardata);
311 if ( ((!strcasecmp(el, "author")) || (!strcasecmp(el, "creator"))) && (ri->chardata != NULL) ) {
312 if (ri->author_or_creator != NULL) free(ri->author_or_creator);
313 striplt(ri->chardata);
314 ri->author_or_creator = strdup(ri->chardata);
317 if (!strcasecmp(el, "item")) {
318 --ri->item_tag_nesting;
322 if ( (!strcasecmp(el, "rss")) || (!strcasecmp(el, "rdf")) ) {
323 CtdlLogPrintf(CTDL_DEBUG, "End of feed detected. Closing parser.\n");
324 ri->done_parsing = 1;
327 if (ri->chardata_len > 0) {
330 ri->chardata_len = 0;
337 * This callback stores up the data which appears in between tags.
339 void rss_xml_chardata(void *data, const XML_Char *s, int len) {
340 struct rss_item *ri = (struct rss_item *) data;
345 old_len = ri->chardata_len;
346 new_len = old_len + len;
347 new_buffer = realloc(ri->chardata, new_len + 1);
348 if (new_buffer != NULL) {
349 memcpy(&new_buffer[old_len], s, len);
350 new_buffer[new_len] = 0;
351 ri->chardata = new_buffer;
352 ri->chardata_len = new_len;
359 * Callback function for passing libcurl's output to expat for parsing
361 size_t rss_libcurl_callback(void *ptr, size_t size, size_t nmemb, void *stream)
363 XML_Parse((XML_Parser)stream, ptr, (size * nmemb), 0);
372 void rss_do_fetching(char *url, char *rooms) {
378 char errmsg[1024] = "";
380 CtdlLogPrintf(CTDL_DEBUG, "Fetching RSS feed <%s>\n", url);
382 curl = curl_easy_init();
384 CtdlLogPrintf(CTDL_ALERT, "Unable to initialize libcurl.\n");
388 xp = XML_ParserCreateNS("UTF-8", ':');
390 CtdlLogPrintf(CTDL_ALERT, "Cannot create XML parser!\n");
391 curl_easy_cleanup(curl);
395 curl_easy_setopt(curl, CURLOPT_URL, url);
396 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
397 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
398 curl_easy_setopt(curl, CURLOPT_WRITEDATA, xp);
399 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, rss_libcurl_callback);
400 curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
401 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
402 curl_easy_setopt(curl, CURLOPT_HTTP_CONTENT_DECODING, 1);
403 curl_easy_setopt(curl, CURLOPT_ENCODING, "");
404 curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
405 curl_easy_setopt(curl, CURLOPT_TIMEOUT, 180); /* die after 180 seconds */
406 if (!IsEmptyStr(config.c_ip_addr)) {
407 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
410 memset(&ri, 0, sizeof(struct rss_item));
412 XML_SetElementHandler(xp, rss_xml_start, rss_xml_end);
413 XML_SetCharacterDataHandler(xp, rss_xml_chardata);
414 XML_SetUserData(xp, &ri);
416 if (CtdlThreadCheckStop())
419 curl_easy_cleanup(curl);
423 if (CtdlThreadCheckStop())
426 res = curl_easy_perform(curl);
428 CtdlLogPrintf(CTDL_ALERT, "libcurl error %d: %s\n", res, errmsg);
431 if (CtdlThreadCheckStop())
434 if (ri.done_parsing == 0) XML_Parse(xp, "", 0, 1);
438 curl_easy_cleanup(curl);
441 /* Free the feed item data structure */
442 if (ri.guid != NULL) free(ri.guid);
444 if (ri.title != NULL) free(ri.title);
446 if (ri.link != NULL) free(ri.link);
448 if (ri.author_or_creator != NULL) free(ri.author_or_creator);
449 ri.author_or_creator = NULL;
450 if (ri.description != NULL) free(ri.description);
451 ri.description = NULL;
452 if (ri.chardata_len > 0) {
461 * Scan a room's netconfig to determine whether it is requesting any RSS feeds
463 void rssclient_scan_room(struct ctdlroom *qrbuf, void *data)
465 char filename[PATH_MAX];
470 struct rssnetcfg *rncptr = NULL;
471 struct rssnetcfg *use_this_rncptr = NULL;
475 assoc_file_name(filename, sizeof filename, qrbuf, ctdl_netcfg_dir);
477 if (CtdlThreadCheckStop())
480 /* Only do net processing for rooms that have netconfigs */
481 fp = fopen(filename, "r");
486 while (fgets(buf, sizeof buf, fp) != NULL && !CtdlThreadCheckStop()) {
487 buf[strlen(buf)-1] = 0;
489 extract_token(instr, buf, 0, '|', sizeof instr);
490 if (!strcasecmp(instr, "rssclient")) {
492 use_this_rncptr = NULL;
494 extract_token(feedurl, buf, 1, '|', sizeof feedurl);
496 /* If any other rooms have requested the same feed, then we will just add this
497 * room to the target list for that client request.
499 for (rncptr=rnclist; rncptr!=NULL; rncptr=rncptr->next) {
500 if (!strcmp(rncptr->url, feedurl)) {
501 use_this_rncptr = rncptr;
505 /* Otherwise create a new client request */
506 if (use_this_rncptr == NULL) {
507 rncptr = (struct rssnetcfg *) malloc(sizeof(struct rssnetcfg));
508 if (rncptr != NULL) {
509 rncptr->next = rnclist;
510 safestrncpy(rncptr->url, feedurl, sizeof rncptr->url);
511 rncptr->rooms = NULL;
513 use_this_rncptr = rncptr;
517 /* Add the room name to the request */
518 if (use_this_rncptr != NULL) {
519 if (use_this_rncptr->rooms == NULL) {
520 rncptr->rooms = strdup(qrbuf->QRname);
523 len = strlen(use_this_rncptr->rooms) + strlen(qrbuf->QRname) + 5;
524 ptr = realloc(use_this_rncptr->rooms, len);
527 strcat(ptr, qrbuf->QRname);
528 use_this_rncptr->rooms = ptr;
541 * Scan for rooms that have RSS client requests configured
543 void *rssclient_scan(void *args) {
544 static time_t last_run = 0L;
545 static int doing_rssclient = 0;
546 struct rssnetcfg *rptr = NULL;
547 struct CitContext rssclientCC;
549 /* Give this thread its own private CitContext */
550 CtdlFillSystemContext(&rssclientCC, "rssclient");
551 citthread_setspecific(MyConKey, (void *)&rssclientCC );
553 CtdlThreadAllocTSD();
556 * This is a simple concurrency check to make sure only one rssclient run
557 * is done at a time. We could do this with a mutex, but since we
558 * don't really require extremely fine granularity here, we'll do it
559 * with a static variable instead.
561 if (doing_rssclient) return NULL;
564 CtdlLogPrintf(CTDL_DEBUG, "rssclient started\n");
565 ForEachRoom(rssclient_scan_room, NULL);
567 while (rnclist != NULL && !CtdlThreadCheckStop()) {
568 rss_do_fetching(rnclist->url, rnclist->rooms);
570 rnclist = rnclist->next;
571 if (rptr->rooms != NULL) free(rptr->rooms);
575 CtdlLogPrintf(CTDL_DEBUG, "rssclient ended\n");
576 last_run = time(NULL);
578 if (!CtdlThreadCheckStop())
579 CtdlThreadSchedule ("RSS Client", CTDLTHREAD_BIGSTACK, rssclient_scan, NULL, last_run + config.c_net_freq);
581 CtdlLogPrintf(CTDL_DEBUG, "rssclient: Task STOPPED.\n");
586 CTDL_MODULE_INIT(rssclient)
590 CtdlLogPrintf(CTDL_INFO, "%s\n", curl_version());
591 CtdlThreadSchedule ("RSS Client", CTDLTHREAD_BIGSTACK, rssclient_scan, NULL, 0);
593 /* return our Subversion id for the Log */