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"
61 typedef struct rssnetcfg rssnetcfg;
67 time_t last_error_when;
75 typedef struct _rss_item {
85 char channel_title[256];
87 char *author_or_creator;
91 typedef struct _rsscollection {
98 struct rssnetcfg *rnclist = NULL;
107 * dug this out of the trashcan of the midgard project, lets see if it works for us.
108 * original code by Alexander Bokovoy <bokovoy@avilink.ne> distributed under GPL V2 or later
112 >= 0 - successfull, 0 means conversion doesn't use multibyte sequences
113 -1 - error during iconv_open call
114 -2 - error during iconv_close call
115 ----------------------------------
116 This function expects that multibyte encoding in 'charset' wouldn't have
117 characters with more than 3 bytes. It is not intended to convert UTF-8 because
118 we'll never receive UTF-8 in our handler (it is handled by Exat itself).
121 fill_encoding_info (const char *charset, XML_Encoding * info)
123 iconv_t cd = (iconv_t)(-1);
125 CtdlLogPrintf(0, "RSS: fill encoding info ...\n");
127 #if G_BYTE_ORDER == G_LITTLE_ENDIAN
128 cd = iconv_open ("UCS-2LE", charset);
130 cd = iconv_open ("UCS-2BE", charset);
133 if (cd == (iconv_t) (-1))
140 unsigned char buf[4];
141 unsigned int i0, i1, i2;
144 for (i0 = 0; i0 < 0x100; i0++)
148 //result = try (cd, buf, 1, &out);
158 for (i1 = 0; i1 < 0x100; i1++)
161 ///result = try (cd, buf, 2, &out);
172 for (i2 = 0; i2 < 0x100; i2++)
175 ////result = try (cd, buf, 3, &out);
191 if (iconv_close (cd) < 0)
199 iconv_convertor (void *data, const char *s)
201 XML_Encoding *info = data;
203 CtdlLogPrintf(0, "RSS: Converting ...\n");
209 result = g_byte_array_new ();
210 if (process_block (info->data, (char *) s, strlen (s), result) == 0)
212 res = *(result->data);
213 g_byte_array_free (result, TRUE);
216 g_byte_array_free (result, TRUE);
222 my_release (void *data)
224 iconv_t cd = (iconv_t) data;
225 if (iconv_close (cd) != 0)
227 /// TODO: uh no. exit (1);
231 handle_unknown_xml_encoding (void *encodingHandleData,
232 const XML_Char * name,
236 CtdlLogPrintf(0, "RSS: unknown encoding ...\n");
237 result = fill_encoding_info (name, info);
241 Special case: client asked for reverse conversion, we'll provide him with
242 iconv descriptor which handles it. Client should release it by himself.
244 if(encodingHandleData != NULL)
245 *((iconv_t *)encodingHandleData) = iconv_open(name, "UTF-8");
247 Optimization: we do not need conversion function if encoding is one-to-one,
248 info->map table will be enough
253 info->convert = NULL;
254 info->release = NULL;
258 We do need conversion function because this encoding uses multibyte sequences
260 info->data = (void *) iconv_open ("UTF-8", name);
261 if ((int)info->data == -1)
263 info->convert = iconv_convertor;
264 info->release = my_release;
267 if(encodingHandleData != NULL)
268 *(iconv_t *)encodingHandleData = NULL;
276 * Commit a fetched and parsed RSS item to disk
278 void rss_save_item(rsscollection *rssc) {
280 struct MD5Context md5context;
281 u_char rawdigest[MD5_DIGEST_LEN];
284 struct cdbdata *cdbut;
286 struct CtdlMessage *msg;
287 struct recptypes *recp = NULL;
289 rss_item *ri = rssc->Item;
291 CtdlLogPrintf(0, "RSS: saving item...\n");
292 recp = (struct recptypes *) malloc(sizeof(struct recptypes));
293 if (recp == NULL) return;
294 memset(recp, 0, sizeof(struct recptypes));
295 recp->recp_room = strdup(ri->roomlist);
296 recp->num_room = num_tokens(ri->roomlist, '|');
297 recp->recptypes_magic = RECPTYPES_MAGIC;
299 /* Construct a GUID to use in the S_USETABLE table.
300 * If one is not present in the item itself, make one up.
302 if (ri->guid != NULL) {
303 snprintf(utmsgid, sizeof utmsgid, "rss/%s", ri->guid);
306 MD5Init(&md5context);
307 if (ri->title != NULL) {
308 MD5Update(&md5context, (unsigned char*)ri->title, strlen(ri->title));
310 if (ri->link != NULL) {
311 MD5Update(&md5context, (unsigned char*)ri->link, strlen(ri->link));
313 MD5Final(rawdigest, &md5context);
314 for (i=0; i<MD5_DIGEST_LEN; i++) {
315 sprintf(&utmsgid[i*2], "%02X", (unsigned char) (rawdigest[i] & 0xff));
316 utmsgid[i*2] = tolower(utmsgid[i*2]);
317 utmsgid[(i*2)+1] = tolower(utmsgid[(i*2)+1]);
319 strcat(utmsgid, "_rss2ctdl");
322 /* Find out if we've already seen this item */
323 cdbut = cdb_fetch(CDB_USETABLE, utmsgid, strlen(utmsgid));
325 /* Item has already been seen */
326 CtdlLogPrintf(CTDL_DEBUG, "%s has already been seen\n", utmsgid);
329 /* rewrite the record anyway, to update the timestamp */
330 strcpy(ut.ut_msgid, utmsgid);
331 ut.ut_timestamp = time(NULL);
332 cdb_store(CDB_USETABLE, utmsgid, strlen(utmsgid), &ut, sizeof(struct UseTable) );
335 /* Item has not been seen, so save it. */
337 if (ri->description == NULL) ri->description = strdup("");
338 for (i=strlen(ri->description); i>=0; --i) {
339 if (isspace(ri->description[i])) {
340 ri->description[i] = ' ';
344 msg = malloc(sizeof(struct CtdlMessage));
345 memset(msg, 0, sizeof(struct CtdlMessage));
346 msg->cm_magic = CTDLMESSAGE_MAGIC;
347 msg->cm_anon_type = MES_NORMAL;
348 msg->cm_format_type = FMT_RFC822;
350 if (ri->author_or_creator != NULL) {
351 msg->cm_fields['A'] = html_to_ascii(ri->author_or_creator,
352 strlen(ri->author_or_creator), 512, 0);
353 striplt(msg->cm_fields['A']);
356 msg->cm_fields['A'] = strdup("rss");
359 msg->cm_fields['N'] = strdup(NODENAME);
360 if (ri->title != NULL) {
361 msg->cm_fields['U'] = html_to_ascii(ri->title, strlen(ri->title), 512, 0);
362 striplt(msg->cm_fields['U']);
364 msg->cm_fields['T'] = malloc(64);
365 snprintf(msg->cm_fields['T'], 64, "%ld", ri->pubdate);
366 if (ri->channel_title != NULL) {
367 if (!IsEmptyStr(ri->channel_title)) {
368 msg->cm_fields['O'] = strdup(ri->channel_title);
371 if (ri->link == NULL)
372 ri->link = strdup("");
373 msglen += 1024 + strlen(ri->link) + strlen(ri->description) ;
374 msg->cm_fields['M'] = malloc(msglen);
375 snprintf(msg->cm_fields['M'], msglen,
376 "Content-type: text/html; charset=\"UTF-8\"\r\n\r\n"
379 "<a href=\"%s\">%s</a>\n"
386 CtdlSubmitMsg(msg, recp, NULL, 0);
387 CtdlFreeMessage(msg);
389 /* write the uidl to the use table so we don't store this item again */
390 strcpy(ut.ut_msgid, utmsgid);
391 ut.ut_timestamp = time(NULL);
392 cdb_store(CDB_USETABLE, utmsgid, strlen(utmsgid), &ut, sizeof(struct UseTable) );
394 free_recipients(recp);
400 * Convert an RDF/RSS datestamp into a time_t
402 time_t rdf_parsedate(char *p)
408 if (strlen(p) < 10) return 0L;
410 memset(&tm, 0, sizeof tm);
412 /* YYYY-MM-DDTHH:MM format...
414 if ( (p[4] == '-') && (p[7] == '-') ) {
415 tm.tm_year = atoi(&p[0]) - 1900;
416 tm.tm_mon = atoi(&p[5]) - 1;
417 tm.tm_mday = atoi(&p[8]);
418 if ( (p[10] == 'T') && (p[13] == ':') ) {
419 tm.tm_hour = atoi(&p[11]);
420 tm.tm_min = atoi(&p[14]);
425 /* hmm... try RFC822 date stamp format */
428 if (t > 0) return(t);
430 /* yeesh. ok, just return the current date and time. */
438 void flush_rss_ite(rss_item *ri)
440 /* Initialize the feed item data structure */
441 if (ri->guid != NULL) free(ri->guid);
443 if (ri->title != NULL) free(ri->title);
445 if (ri->link != NULL) free(ri->link);
447 if (ri->author_or_creator != NULL) free(ri->author_or_creator);
448 ri->author_or_creator = NULL;
449 if (ri->description != NULL) free(ri->description);
450 ri->description = NULL;
451 /* Throw away any existing character data */
452 if (ri->chardata_len > 0) {
455 ri->chardata_len = 0;
459 void rss_xml_start(void *data, const char *supplied_el, const char **attr) {
460 rsscollection *rssc = (rsscollection*) data;
461 rss_item *ri = rssc->Item;
465 /* Axe the namespace, we don't care about it */
466 /// CtdlLogPrintf(0, "RSS: supplied el %d: %s...\n", rssc->Cfg->ItemType, supplied_el);
467 safestrncpy(el, supplied_el, sizeof el);
468 while (sep = strchr(el, ':'), sep) {
472 if (((rssc->Cfg->ItemType == RSS_UNSET) ||
473 (rssc->Cfg->ItemType == RSS_RSS)) &&
474 !strcasecmp(el, "item"))
476 ri->item_tag_nesting ++ ;
477 rssc->Cfg->ItemType = RSS_RSS;
480 else if (((rssc->Cfg->ItemType == RSS_UNSET) ||
481 (rssc->Cfg->ItemType == RSS_ATOM)) &&
482 !strcasecmp(el, "entry")) { /* Atom feed... */
483 CtdlLogPrintf(0, "RSS: found atom...\n");
484 ++ri->item_tag_nesting;
485 rssc->Cfg->ItemType = RSS_ATOM;
488 else if ((rssc->Cfg->ItemType == RSS_ATOM) &&
489 !strcasecmp(el, "link"))
494 for (found = 0, i = 0;!found && attr[i] != NULL; i+=2)
496 if (!strcmp(attr[i], "href"))
499 if (ri->link != NULL)
501 ri->link = strdup(attr[i+1]);
510 void rss_xml_end(void *data, const char *supplied_el) {
511 rsscollection *rssc = (rsscollection*) data;
512 rss_item *ri = rssc->Item;
516 /* Axe the namespace, we don't care about it */
517 safestrncpy(el, supplied_el, sizeof el);
518 while (sep = strchr(el, ':'), sep) {
521 // CtdlLogPrintf(0, "RSS: END %s...\n", el);
523 if ( (!strcasecmp(el, "title")) && (ri->item_tag_nesting == 0) && (ri->chardata != NULL) ) {
524 safestrncpy(ri->channel_title, ri->chardata, sizeof ri->channel_title);
525 striplt(ri->channel_title);
528 if ( (rssc->Cfg->ItemType == RSS_RSS) &&
529 (!strcasecmp(el, "guid")) && (ri->chardata != NULL) ) {
530 if (ri->guid != NULL) free(ri->guid);
531 striplt(ri->chardata);
532 ri->guid = strdup(ri->chardata);
534 else if ( (rssc->Cfg->ItemType == RSS_ATOM) &&
535 (!strcasecmp(el, "id")) && (ri->chardata != NULL) ) {
536 if (ri->guid != NULL) free(ri->guid);
537 striplt(ri->chardata);
538 ri->guid = strdup(ri->chardata);
542 else if ( (!strcasecmp(el, "title")) && (ri->chardata != NULL) ) {
543 if (ri->title != NULL) free(ri->title);
544 striplt(ri->chardata);
545 ri->title = strdup(ri->chardata);
548 else if ((rssc->Cfg->ItemType == RSS_ATOM) &&
549 (!strcasecmp(el, "content")) &&
550 (ri->chardata != NULL) ) {
551 if (ri->description != NULL) free(ri->description);
552 ri->description = strdup(ri->chardata);
554 else if ( (rssc->Cfg->ItemType == RSS_RSS) &&
555 (!strcasecmp(el, "description")) &&
556 (ri->chardata != NULL) ) {
557 if (ri->description != NULL) free(ri->description);
558 ri->description = strdup(ri->chardata);
561 else if ((rssc->Cfg->ItemType == RSS_ATOM) &&
562 ((!strcasecmp(el, "published")) ||
563 (!strcasecmp(el, "updated"))) &&
564 (ri->chardata != NULL) ) {
565 striplt(ri->chardata);
566 ri->pubdate = rdf_parsedate(ri->chardata);
570 else if ((rssc->Cfg->ItemType == RSS_RSS) &&
571 ((!strcasecmp(el, "pubdate")) ||
572 (!strcasecmp(el, "date"))) &&
573 (ri->chardata != NULL) ) {
574 striplt(ri->chardata);
575 ri->pubdate = rdf_parsedate(ri->chardata);
578 else if ((rssc->Cfg->ItemType == RSS_ATOM) &&
579 ((!strcasecmp(el, "author")) ||
580 (!strcasecmp(el, "creator"))) &&
581 (ri->chardata != NULL) ) {
582 if (ri->author_or_creator != NULL) free(ri->author_or_creator);
583 striplt(ri->chardata);
584 ri->author_or_creator = strdup(ri->chardata);
587 else if ((rssc->Cfg->ItemType == RSS_RSS) &&
588 !strcasecmp(el, "item")) {
589 --ri->item_tag_nesting;
592 else if ((rssc->Cfg->ItemType == RSS_ATOM) &&
593 !strcasecmp(el, "entry")) {
594 --ri->item_tag_nesting;
598 else if ( (!strcasecmp(el, "rss")) ||
599 (!strcasecmp(el, "rdf")) ) {
600 // CtdlLogPrintf(CTDL_DEBUG, "End of feed detected. Closing parser.\n");
601 ri->done_parsing = 1;
604 if (ri->chardata_len > 0) {
607 ri->chardata_len = 0;
614 * This callback stores up the data which appears in between tags.
616 void rss_xml_chardata(void *data, const XML_Char *s, int len) {
617 rsscollection *rssc = (rsscollection*) data;
618 rss_item *ri = rssc->Item;
623 old_len = ri->chardata_len;
624 new_len = old_len + len;
625 new_buffer = realloc(ri->chardata, new_len + 1);
626 if (new_buffer != NULL) {
627 memcpy(&new_buffer[old_len], s, len);
628 new_buffer[new_len] = 0;
629 ri->chardata = new_buffer;
630 ri->chardata_len = new_len;
637 * Callback function for passing libcurl's output to expat for parsing
639 size_t rss_libcurl_callback(void *ptr, size_t size, size_t nmemb, void *stream)
641 XML_Parse((XML_Parser)stream, ptr, (size * nmemb), 0);
650 void rss_do_fetching(rssnetcfg *Cfg) {
657 char errmsg[1024] = "";
662 CtdlLogPrintf(CTDL_DEBUG, "Fetching RSS feed <%s>\n", Cfg->url);
664 curl = curl_easy_init();
666 CtdlLogPrintf(CTDL_ALERT, "Unable to initialize libcurl.\n");
670 xp = XML_ParserCreateNS("UTF-8", ':');
672 CtdlLogPrintf(CTDL_ALERT, "Cannot create XML parser!\n");
673 curl_easy_cleanup(curl);
677 curl_easy_setopt(curl, CURLOPT_URL, Cfg->url);
678 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
679 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
680 curl_easy_setopt(curl, CURLOPT_WRITEDATA, xp);
681 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, rss_libcurl_callback);
682 curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
683 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
684 #ifdef CURLOPT_HTTP_CONTENT_DECODING
685 curl_easy_setopt(curl, CURLOPT_HTTP_CONTENT_DECODING, 1);
686 curl_easy_setopt(curl, CURLOPT_ENCODING, "");
688 curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
689 curl_easy_setopt(curl, CURLOPT_TIMEOUT, 180); /* die after 180 seconds */
690 if (!IsEmptyStr(config.c_ip_addr)) {
691 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
694 memset(&ri, 0, sizeof(rss_item));
695 ri.roomlist = Cfg->rooms;
698 XML_SetUnknownEncodingHandler(xp,
699 handle_unknown_xml_encoding,
703 XML_SetElementHandler(xp, rss_xml_start, rss_xml_end);
704 XML_SetCharacterDataHandler(xp, rss_xml_chardata);
705 XML_SetUserData(xp, &rssc);
706 if (CtdlThreadCheckStop())
709 curl_easy_cleanup(curl);
713 if (CtdlThreadCheckStop())
716 res = curl_easy_perform(curl);
718 CtdlLogPrintf(CTDL_ALERT, "libcurl error %d: %s\n", res, errmsg);
721 if (CtdlThreadCheckStop())
724 if (ri.done_parsing == 0)
725 XML_Parse(xp, "", 0, 1);
728 CtdlLogPrintf(CTDL_ALERT, "RSS: XML Status [%s] \n",
730 XML_GetErrorCode(xp)));
733 curl_easy_cleanup(curl);
741 * Scan a room's netconfig to determine whether it is requesting any RSS feeds
743 void rssclient_scan_room(struct ctdlroom *qrbuf, void *data)
745 char filename[PATH_MAX];
750 rssnetcfg *rncptr = NULL;
751 rssnetcfg *use_this_rncptr = NULL;
755 assoc_file_name(filename, sizeof filename, qrbuf, ctdl_netcfg_dir);
757 if (CtdlThreadCheckStop())
760 /* Only do net processing for rooms that have netconfigs */
761 fp = fopen(filename, "r");
766 while (fgets(buf, sizeof buf, fp) != NULL && !CtdlThreadCheckStop()) {
767 buf[strlen(buf)-1] = 0;
769 extract_token(instr, buf, 0, '|', sizeof instr);
770 if (!strcasecmp(instr, "rssclient")) {
772 use_this_rncptr = NULL;
774 extract_token(feedurl, buf, 1, '|', sizeof feedurl);
776 /* If any other rooms have requested the same feed, then we will just add this
777 * room to the target list for that client request.
779 for (rncptr=rnclist; rncptr!=NULL; rncptr=rncptr->next) {
780 if (!strcmp(rncptr->url, feedurl)) {
781 use_this_rncptr = rncptr;
785 /* Otherwise create a new client request */
786 if (use_this_rncptr == NULL) {
787 rncptr = (rssnetcfg *) malloc(sizeof(rssnetcfg));
788 rncptr->ItemType = RSS_UNSET;
789 if (rncptr != NULL) {
790 rncptr->next = rnclist;
791 safestrncpy(rncptr->url, feedurl, sizeof rncptr->url);
792 rncptr->rooms = NULL;
794 use_this_rncptr = rncptr;
798 /* Add the room name to the request */
799 if (use_this_rncptr != NULL) {
800 if (use_this_rncptr->rooms == NULL) {
801 rncptr->rooms = strdup(qrbuf->QRname);
804 len = strlen(use_this_rncptr->rooms) + strlen(qrbuf->QRname) + 5;
805 ptr = realloc(use_this_rncptr->rooms, len);
808 strcat(ptr, qrbuf->QRname);
809 use_this_rncptr->rooms = ptr;
822 * Scan for rooms that have RSS client requests configured
824 void *rssclient_scan(void *args) {
825 static time_t last_run = 0L;
826 static int doing_rssclient = 0;
827 rssnetcfg *rptr = NULL;
828 CitContext rssclientCC;
830 /* Give this thread its own private CitContext */
831 CtdlFillSystemContext(&rssclientCC, "rssclient");
832 citthread_setspecific(MyConKey, (void *)&rssclientCC );
834 CtdlThreadAllocTSD();
837 * This is a simple concurrency check to make sure only one rssclient run
838 * is done at a time. We could do this with a mutex, but since we
839 * don't really require extremely fine granularity here, we'll do it
840 * with a static variable instead.
842 if (doing_rssclient) return NULL;
845 CtdlLogPrintf(CTDL_DEBUG, "rssclient started\n");
846 CtdlForEachRoom(rssclient_scan_room, NULL);
848 while (rnclist != NULL && !CtdlThreadCheckStop()) {
849 rss_do_fetching(rnclist);
851 rnclist = rnclist->next;
852 if (rptr->rooms != NULL) free(rptr->rooms);
856 CtdlLogPrintf(CTDL_DEBUG, "rssclient ended\n");
857 last_run = time(NULL);
859 if (!CtdlThreadCheckStop())
860 CtdlThreadSchedule ("RSS Client", CTDLTHREAD_BIGSTACK, rssclient_scan, NULL, last_run + config.c_net_freq);
862 CtdlLogPrintf(CTDL_DEBUG, "rssclient: Task STOPPED.\n");
867 CTDL_MODULE_INIT(rssclient)
871 CtdlLogPrintf(CTDL_INFO, "%s\n", curl_version());
872 CtdlThreadSchedule ("RSS Client", CTDLTHREAD_BIGSTACK, rssclient_scan, NULL, 0);
874 /* return our Subversion id for the Log */