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 if (ri->title != NULL) {
145 msg->cm_fields['U'] = html_to_ascii(ri->title, strlen(ri->title), 512, 0);
147 msg->cm_fields['T'] = malloc(64);
148 snprintf(msg->cm_fields['T'], 64, "%ld", ri->pubdate);
149 if (ri->channel_title != NULL) {
150 if (!IsEmptyStr(ri->channel_title)) {
151 msg->cm_fields['O'] = strdup(ri->channel_title);
155 msglen = 1024 + strlen(ri->link) + strlen(ri->description) ;
156 msg->cm_fields['M'] = malloc(msglen);
157 snprintf(msg->cm_fields['M'], msglen,
158 "Content-type: text/html\r\n\r\n"
161 "<a href=\"%s\">%s</a>\n"
168 CtdlSubmitMsg(msg, recp, NULL, 0);
169 CtdlFreeMessage(msg);
171 /* write the uidl to the use table so we don't store this item again */
172 strcpy(ut.ut_msgid, utmsgid);
173 ut.ut_timestamp = time(NULL);
174 cdb_store(CDB_USETABLE, utmsgid, strlen(utmsgid), &ut, sizeof(struct UseTable) );
176 free_recipients(recp);
182 * Convert an RDF/RSS datestamp into a time_t
184 time_t rdf_parsedate(char *p)
190 if (strlen(p) < 10) return 0L;
192 memset(&tm, 0, sizeof tm);
194 /* YYYY-MM-DDTHH:MM format...
196 if ( (p[4] == '-') && (p[7] == '-') ) {
197 tm.tm_year = atoi(&p[0]) - 1900;
198 tm.tm_mon = atoi(&p[5]) - 1;
199 tm.tm_mday = atoi(&p[8]);
200 if ( (p[10] == 'T') && (p[13] == ':') ) {
201 tm.tm_hour = atoi(&p[11]);
202 tm.tm_min = atoi(&p[14]);
207 /* hmm... try RFC822 date stamp format */
210 if (t > 0) return(t);
212 /* yeesh. ok, just return the current date and time. */
218 void rss_xml_start(void *data, const char *supplied_el, const char **attr) {
219 struct rss_item *ri = (struct rss_item *) data;
223 /* Axe the namespace, we don't care about it */
224 safestrncpy(el, supplied_el, sizeof el);
225 while (sep = strchr(el, ':'), sep) {
229 if (!strcasecmp(el, "item")) {
230 ++ri->item_tag_nesting;
232 /* Initialize the feed item data structure */
233 if (ri->guid != NULL) free(ri->guid);
235 if (ri->title != NULL) free(ri->title);
237 if (ri->link != NULL) free(ri->link);
239 if (ri->description != NULL) free(ri->description);
240 ri->description = NULL;
242 /* Throw away any existing character data */
243 if (ri->chardata_len > 0) {
246 ri->chardata_len = 0;
254 void rss_xml_end(void *data, const char *supplied_el) {
255 struct rss_item *ri = (struct rss_item *) data;
259 /* Axe the namespace, we don't care about it */
260 safestrncpy(el, supplied_el, sizeof el);
261 while (sep = strchr(el, ':'), sep) {
265 if ( (!strcasecmp(el, "title")) && (ri->item_tag_nesting == 0) && (ri->chardata != NULL) ) {
266 safestrncpy(ri->channel_title, ri->chardata, sizeof ri->channel_title);
267 striplt(ri->channel_title);
270 if ( (!strcasecmp(el, "guid")) && (ri->chardata != NULL) ) {
271 if (ri->guid != NULL) free(ri->guid);
272 striplt(ri->chardata);
273 ri->guid = strdup(ri->chardata);
276 if ( (!strcasecmp(el, "title")) && (ri->chardata != NULL) ) {
277 if (ri->title != NULL) free(ri->title);
278 striplt(ri->chardata);
279 ri->title = strdup(ri->chardata);
282 if ( (!strcasecmp(el, "link")) && (ri->chardata != NULL) ) {
283 if (ri->link != NULL) free(ri->link);
284 striplt(ri->chardata);
285 ri->link = strdup(ri->chardata);
288 if ( (!strcasecmp(el, "description")) && (ri->chardata != NULL) ) {
289 if (ri->description != NULL) free(ri->description);
290 ri->description = strdup(ri->chardata);
293 if ( ((!strcasecmp(el, "pubdate")) || (!strcasecmp(el, "date"))) && (ri->chardata != NULL) ) {
294 striplt(ri->chardata);
295 ri->pubdate = rdf_parsedate(ri->chardata);
298 if (!strcasecmp(el, "item")) {
299 --ri->item_tag_nesting;
303 if ( (!strcasecmp(el, "rss")) || (!strcasecmp(el, "rdf")) ) {
304 CtdlLogPrintf(CTDL_DEBUG, "End of feed detected. Closing parser.\n");
305 ri->done_parsing = 1;
308 if (ri->chardata_len > 0) {
311 ri->chardata_len = 0;
318 * This callback stores up the data which appears in between tags.
320 void rss_xml_chardata(void *data, const XML_Char *s, int len) {
321 struct rss_item *ri = (struct rss_item *) data;
326 old_len = ri->chardata_len;
327 new_len = old_len + len;
328 new_buffer = realloc(ri->chardata, new_len + 1);
329 if (new_buffer != NULL) {
330 memcpy(&new_buffer[old_len], s, len);
331 new_buffer[new_len] = 0;
332 ri->chardata = new_buffer;
333 ri->chardata_len = new_len;
340 * Callback function for passing libcurl's output to expat for parsing
342 size_t rss_libcurl_callback(void *ptr, size_t size, size_t nmemb, void *stream)
344 XML_Parse((XML_Parser)stream, ptr, (size * nmemb), 0);
353 void rss_do_fetching(char *url, char *rooms) {
359 char errmsg[1024] = "";
361 CtdlLogPrintf(CTDL_DEBUG, "Fetching RSS feed <%s>\n", url);
363 curl = curl_easy_init();
365 CtdlLogPrintf(CTDL_ALERT, "Unable to initialize libcurl.\n");
369 xp = XML_ParserCreateNS("UTF-8", ':');
371 CtdlLogPrintf(CTDL_ALERT, "Cannot create XML parser!\n");
372 curl_easy_cleanup(curl);
376 curl_easy_setopt(curl, CURLOPT_URL, url);
377 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
378 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
379 curl_easy_setopt(curl, CURLOPT_WRITEDATA, xp);
380 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, rss_libcurl_callback);
381 curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
382 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
383 curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
384 if (!IsEmptyStr(config.c_ip_addr)) {
385 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
388 memset(&ri, 0, sizeof(struct rss_item));
390 XML_SetElementHandler(xp, rss_xml_start, rss_xml_end);
391 XML_SetCharacterDataHandler(xp, rss_xml_chardata);
392 XML_SetUserData(xp, &ri);
394 if (CtdlThreadCheckStop())
397 curl_easy_cleanup(curl);
401 if (CtdlThreadCheckStop())
404 res = curl_easy_perform(curl);
406 CtdlLogPrintf(CTDL_ALERT, "libcurl error %d: %s\n", res, errmsg);
409 if (CtdlThreadCheckStop())
412 if (ri.done_parsing == 0) XML_Parse(xp, "", 0, 1);
416 curl_easy_cleanup(curl);
419 /* Free the feed item data structure */
420 if (ri.guid != NULL) free(ri.guid);
422 if (ri.title != NULL) free(ri.title);
424 if (ri.link != NULL) free(ri.link);
426 if (ri.description != NULL) free(ri.description);
427 ri.description = NULL;
428 if (ri.chardata_len > 0) {
437 * Scan a room's netconfig to determine whether it is requesting any RSS feeds
439 void rssclient_scan_room(struct ctdlroom *qrbuf, void *data)
441 char filename[PATH_MAX];
446 struct rssnetcfg *rncptr = NULL;
447 struct rssnetcfg *use_this_rncptr = NULL;
451 assoc_file_name(filename, sizeof filename, qrbuf, ctdl_netcfg_dir);
453 if (CtdlThreadCheckStop())
456 /* Only do net processing for rooms that have netconfigs */
457 fp = fopen(filename, "r");
462 while (fgets(buf, sizeof buf, fp) != NULL && !CtdlThreadCheckStop()) {
463 buf[strlen(buf)-1] = 0;
465 extract_token(instr, buf, 0, '|', sizeof instr);
466 if (!strcasecmp(instr, "rssclient")) {
468 use_this_rncptr = NULL;
470 extract_token(feedurl, buf, 1, '|', sizeof feedurl);
472 /* If any other rooms have requested the same feed, then we will just add this
473 * room to the target list for that client request.
475 for (rncptr=rnclist; rncptr!=NULL; rncptr=rncptr->next) {
476 if (!strcmp(rncptr->url, feedurl)) {
477 use_this_rncptr = rncptr;
481 /* Otherwise create a new client request */
482 if (use_this_rncptr == NULL) {
483 rncptr = (struct rssnetcfg *) malloc(sizeof(struct rssnetcfg));
484 if (rncptr != NULL) {
485 rncptr->next = rnclist;
486 safestrncpy(rncptr->url, feedurl, sizeof rncptr->url);
487 rncptr->rooms = NULL;
489 use_this_rncptr = rncptr;
493 /* Add the room name to the request */
494 if (use_this_rncptr != NULL) {
495 if (use_this_rncptr->rooms == NULL) {
496 rncptr->rooms = strdup(qrbuf->QRname);
499 len = strlen(use_this_rncptr->rooms) + strlen(qrbuf->QRname) + 5;
500 ptr = realloc(use_this_rncptr->rooms, len);
503 strcat(ptr, qrbuf->QRname);
504 use_this_rncptr->rooms = ptr;
517 * Scan for rooms that have RSS client requests configured
519 void *rssclient_scan(void *args) {
520 static time_t last_run = 0L;
521 static int doing_rssclient = 0;
522 struct rssnetcfg *rptr = NULL;
523 struct CitContext rssclientCC;
525 /* Give this thread its own private CitContext */
526 CtdlFillSystemContext(&rssclientCC, "rssclient");
527 citthread_setspecific(MyConKey, (void *)&rssclientCC );
529 CtdlThreadAllocTSD();
532 * This is a simple concurrency check to make sure only one rssclient run
533 * is done at a time. We could do this with a mutex, but since we
534 * don't really require extremely fine granularity here, we'll do it
535 * with a static variable instead.
537 if (doing_rssclient) return NULL;
540 CtdlLogPrintf(CTDL_DEBUG, "rssclient started\n");
541 ForEachRoom(rssclient_scan_room, NULL);
543 while (rnclist != NULL && !CtdlThreadCheckStop()) {
544 rss_do_fetching(rnclist->url, rnclist->rooms);
546 rnclist = rnclist->next;
547 if (rptr->rooms != NULL) free(rptr->rooms);
551 CtdlLogPrintf(CTDL_DEBUG, "rssclient ended\n");
552 last_run = time(NULL);
554 if (!CtdlThreadCheckStop())
555 CtdlThreadSchedule ("RSS Client", CTDLTHREAD_BIGSTACK, rssclient_scan, NULL, last_run + config.c_net_freq);
557 CtdlLogPrintf(CTDL_DEBUG, "rssclient: Task STOPPED.\n");
562 CTDL_MODULE_INIT(rssclient)
566 CtdlLogPrintf(CTDL_INFO, "%s\n", curl_version());
567 CtdlThreadSchedule ("RSS Client", CTDLTHREAD_BIGSTACK, rssclient_scan, NULL, 0);
569 /* return our Subversion id for the Log */
570 return "$Id: serv_rssclient.c 5652 2007-10-29 20:14:48Z ajc $";