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];
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);
149 msg->cm_fields['A'] = strdup("rss");
152 msg->cm_fields['N'] = strdup(NODENAME);
153 if (ri->title != NULL) {
154 msg->cm_fields['U'] = html_to_ascii(ri->title, strlen(ri->title), 512, 0);
156 msg->cm_fields['T'] = malloc(64);
157 snprintf(msg->cm_fields['T'], 64, "%ld", ri->pubdate);
158 if (ri->channel_title != NULL) {
159 if (!IsEmptyStr(ri->channel_title)) {
160 msg->cm_fields['O'] = strdup(ri->channel_title);
164 msglen = 1024 + strlen(ri->link) + strlen(ri->description) ;
165 msg->cm_fields['M'] = malloc(msglen);
166 snprintf(msg->cm_fields['M'], msglen,
167 "Content-type: text/html\r\n\r\n"
170 "<a href=\"%s\">%s</a>\n"
177 CtdlSubmitMsg(msg, recp, NULL, 0);
178 CtdlFreeMessage(msg);
180 /* write the uidl to the use table so we don't store this item again */
181 strcpy(ut.ut_msgid, utmsgid);
182 ut.ut_timestamp = time(NULL);
183 cdb_store(CDB_USETABLE, utmsgid, strlen(utmsgid), &ut, sizeof(struct UseTable) );
185 free_recipients(recp);
191 * Convert an RDF/RSS datestamp into a time_t
193 time_t rdf_parsedate(char *p)
199 if (strlen(p) < 10) return 0L;
201 memset(&tm, 0, sizeof tm);
203 /* YYYY-MM-DDTHH:MM format...
205 if ( (p[4] == '-') && (p[7] == '-') ) {
206 tm.tm_year = atoi(&p[0]) - 1900;
207 tm.tm_mon = atoi(&p[5]) - 1;
208 tm.tm_mday = atoi(&p[8]);
209 if ( (p[10] == 'T') && (p[13] == ':') ) {
210 tm.tm_hour = atoi(&p[11]);
211 tm.tm_min = atoi(&p[14]);
216 /* hmm... try RFC822 date stamp format */
219 if (t > 0) return(t);
221 /* yeesh. ok, just return the current date and time. */
227 void rss_xml_start(void *data, const char *supplied_el, const char **attr) {
228 struct rss_item *ri = (struct rss_item *) data;
232 /* Axe the namespace, we don't care about it */
233 safestrncpy(el, supplied_el, sizeof el);
234 while (sep = strchr(el, ':'), sep) {
238 if (!strcasecmp(el, "item")) {
239 ++ri->item_tag_nesting;
241 /* Initialize the feed item data structure */
242 if (ri->guid != NULL) free(ri->guid);
244 if (ri->title != NULL) free(ri->title);
246 if (ri->link != NULL) free(ri->link);
248 if (ri->author_or_creator != NULL) free(ri->author_or_creator);
249 ri->author_or_creator = NULL;
250 if (ri->description != NULL) free(ri->description);
251 ri->description = NULL;
253 /* Throw away any existing character data */
254 if (ri->chardata_len > 0) {
257 ri->chardata_len = 0;
265 void rss_xml_end(void *data, const char *supplied_el) {
266 struct rss_item *ri = (struct rss_item *) data;
270 /* Axe the namespace, we don't care about it */
271 safestrncpy(el, supplied_el, sizeof el);
272 while (sep = strchr(el, ':'), sep) {
276 if ( (!strcasecmp(el, "title")) && (ri->item_tag_nesting == 0) && (ri->chardata != NULL) ) {
277 safestrncpy(ri->channel_title, ri->chardata, sizeof ri->channel_title);
278 striplt(ri->channel_title);
281 if ( (!strcasecmp(el, "guid")) && (ri->chardata != NULL) ) {
282 if (ri->guid != NULL) free(ri->guid);
283 striplt(ri->chardata);
284 ri->guid = strdup(ri->chardata);
287 if ( (!strcasecmp(el, "title")) && (ri->chardata != NULL) ) {
288 if (ri->title != NULL) free(ri->title);
289 striplt(ri->chardata);
290 ri->title = strdup(ri->chardata);
293 if ( (!strcasecmp(el, "link")) && (ri->chardata != NULL) ) {
294 if (ri->link != NULL) free(ri->link);
295 striplt(ri->chardata);
296 ri->link = strdup(ri->chardata);
299 if ( (!strcasecmp(el, "description")) && (ri->chardata != NULL) ) {
300 if (ri->description != NULL) free(ri->description);
301 ri->description = strdup(ri->chardata);
304 if ( ((!strcasecmp(el, "pubdate")) || (!strcasecmp(el, "date"))) && (ri->chardata != NULL) ) {
305 striplt(ri->chardata);
306 ri->pubdate = rdf_parsedate(ri->chardata);
309 if ( ((!strcasecmp(el, "author")) || (!strcasecmp(el, "creator"))) && (ri->chardata != NULL) ) {
310 if (ri->author_or_creator != NULL) free(ri->title);
311 striplt(ri->chardata);
312 ri->author_or_creator = strdup(ri->chardata);
315 if (!strcasecmp(el, "item")) {
316 --ri->item_tag_nesting;
320 if ( (!strcasecmp(el, "rss")) || (!strcasecmp(el, "rdf")) ) {
321 CtdlLogPrintf(CTDL_DEBUG, "End of feed detected. Closing parser.\n");
322 ri->done_parsing = 1;
325 if (ri->chardata_len > 0) {
328 ri->chardata_len = 0;
335 * This callback stores up the data which appears in between tags.
337 void rss_xml_chardata(void *data, const XML_Char *s, int len) {
338 struct rss_item *ri = (struct rss_item *) data;
343 old_len = ri->chardata_len;
344 new_len = old_len + len;
345 new_buffer = realloc(ri->chardata, new_len + 1);
346 if (new_buffer != NULL) {
347 memcpy(&new_buffer[old_len], s, len);
348 new_buffer[new_len] = 0;
349 ri->chardata = new_buffer;
350 ri->chardata_len = new_len;
357 * Callback function for passing libcurl's output to expat for parsing
359 size_t rss_libcurl_callback(void *ptr, size_t size, size_t nmemb, void *stream)
361 XML_Parse((XML_Parser)stream, ptr, (size * nmemb), 0);
370 void rss_do_fetching(char *url, char *rooms) {
376 char errmsg[1024] = "";
378 CtdlLogPrintf(CTDL_DEBUG, "Fetching RSS feed <%s>\n", url);
380 curl = curl_easy_init();
382 CtdlLogPrintf(CTDL_ALERT, "Unable to initialize libcurl.\n");
386 xp = XML_ParserCreateNS("UTF-8", ':');
388 CtdlLogPrintf(CTDL_ALERT, "Cannot create XML parser!\n");
389 curl_easy_cleanup(curl);
393 curl_easy_setopt(curl, CURLOPT_URL, url);
394 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
395 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
396 curl_easy_setopt(curl, CURLOPT_WRITEDATA, xp);
397 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, rss_libcurl_callback);
398 curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
399 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
400 curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
401 if (!IsEmptyStr(config.c_ip_addr)) {
402 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
405 memset(&ri, 0, sizeof(struct rss_item));
407 XML_SetElementHandler(xp, rss_xml_start, rss_xml_end);
408 XML_SetCharacterDataHandler(xp, rss_xml_chardata);
409 XML_SetUserData(xp, &ri);
411 if (CtdlThreadCheckStop())
414 curl_easy_cleanup(curl);
418 if (CtdlThreadCheckStop())
421 res = curl_easy_perform(curl);
423 CtdlLogPrintf(CTDL_ALERT, "libcurl error %d: %s\n", res, errmsg);
426 if (CtdlThreadCheckStop())
429 if (ri.done_parsing == 0) XML_Parse(xp, "", 0, 1);
433 curl_easy_cleanup(curl);
436 /* Free the feed item data structure */
437 if (ri.guid != NULL) free(ri.guid);
439 if (ri.title != NULL) free(ri.title);
441 if (ri.link != NULL) free(ri.link);
443 if (ri.author_or_creator != NULL) free(ri.author_or_creator);
444 ri.author_or_creator = NULL;
445 if (ri.description != NULL) free(ri.description);
446 ri.description = NULL;
447 if (ri.chardata_len > 0) {
456 * Scan a room's netconfig to determine whether it is requesting any RSS feeds
458 void rssclient_scan_room(struct ctdlroom *qrbuf, void *data)
460 char filename[PATH_MAX];
465 struct rssnetcfg *rncptr = NULL;
466 struct rssnetcfg *use_this_rncptr = NULL;
470 assoc_file_name(filename, sizeof filename, qrbuf, ctdl_netcfg_dir);
472 if (CtdlThreadCheckStop())
475 /* Only do net processing for rooms that have netconfigs */
476 fp = fopen(filename, "r");
481 while (fgets(buf, sizeof buf, fp) != NULL && !CtdlThreadCheckStop()) {
482 buf[strlen(buf)-1] = 0;
484 extract_token(instr, buf, 0, '|', sizeof instr);
485 if (!strcasecmp(instr, "rssclient")) {
487 use_this_rncptr = NULL;
489 extract_token(feedurl, buf, 1, '|', sizeof feedurl);
491 /* If any other rooms have requested the same feed, then we will just add this
492 * room to the target list for that client request.
494 for (rncptr=rnclist; rncptr!=NULL; rncptr=rncptr->next) {
495 if (!strcmp(rncptr->url, feedurl)) {
496 use_this_rncptr = rncptr;
500 /* Otherwise create a new client request */
501 if (use_this_rncptr == NULL) {
502 rncptr = (struct rssnetcfg *) malloc(sizeof(struct rssnetcfg));
503 if (rncptr != NULL) {
504 rncptr->next = rnclist;
505 safestrncpy(rncptr->url, feedurl, sizeof rncptr->url);
506 rncptr->rooms = NULL;
508 use_this_rncptr = rncptr;
512 /* Add the room name to the request */
513 if (use_this_rncptr != NULL) {
514 if (use_this_rncptr->rooms == NULL) {
515 rncptr->rooms = strdup(qrbuf->QRname);
518 len = strlen(use_this_rncptr->rooms) + strlen(qrbuf->QRname) + 5;
519 ptr = realloc(use_this_rncptr->rooms, len);
522 strcat(ptr, qrbuf->QRname);
523 use_this_rncptr->rooms = ptr;
536 * Scan for rooms that have RSS client requests configured
538 void *rssclient_scan(void *args) {
539 static time_t last_run = 0L;
540 static int doing_rssclient = 0;
541 struct rssnetcfg *rptr = NULL;
542 struct CitContext rssclientCC;
544 /* Give this thread its own private CitContext */
545 CtdlFillSystemContext(&rssclientCC, "rssclient");
546 citthread_setspecific(MyConKey, (void *)&rssclientCC );
548 CtdlThreadAllocTSD();
551 * This is a simple concurrency check to make sure only one rssclient run
552 * is done at a time. We could do this with a mutex, but since we
553 * don't really require extremely fine granularity here, we'll do it
554 * with a static variable instead.
556 if (doing_rssclient) return NULL;
559 CtdlLogPrintf(CTDL_DEBUG, "rssclient started\n");
560 ForEachRoom(rssclient_scan_room, NULL);
562 while (rnclist != NULL && !CtdlThreadCheckStop()) {
563 rss_do_fetching(rnclist->url, rnclist->rooms);
565 rnclist = rnclist->next;
566 if (rptr->rooms != NULL) free(rptr->rooms);
570 CtdlLogPrintf(CTDL_DEBUG, "rssclient ended\n");
571 last_run = time(NULL);
573 if (!CtdlThreadCheckStop())
574 CtdlThreadSchedule ("RSS Client", CTDLTHREAD_BIGSTACK, rssclient_scan, NULL, last_run + config.c_net_freq);
576 CtdlLogPrintf(CTDL_DEBUG, "rssclient: Task STOPPED.\n");
581 CTDL_MODULE_INIT(rssclient)
585 CtdlLogPrintf(CTDL_INFO, "%s\n", curl_version());
586 CtdlThreadSchedule ("RSS Client", CTDLTHREAD_BIGSTACK, rssclient_scan, NULL, 0);
588 /* return our Subversion id for the Log */
589 return "$Id: serv_rssclient.c 5652 2007-10-29 20:14:48Z ajc $";