Merge branch 'master' of ssh://git.citadel.org/appl/gitroot/citadel
[citadel.git] / citadel / modules / rssclient / serv_rssclient.c
1 /*
2  * Bring external RSS feeds into rooms.
3  *
4  * Copyright (c) 2007-2010 by the citadel.org team
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 #include <stdlib.h>
22 #include <unistd.h>
23 #include <stdio.h>
24
25 #if TIME_WITH_SYS_TIME
26 # include <sys/time.h>
27 # include <time.h>
28 #else
29 # if HAVE_SYS_TIME_H
30 #  include <sys/time.h>
31 # else
32 #  include <time.h>
33 # endif
34 #endif
35
36 #include <ctype.h>
37 #include <string.h>
38 #include <errno.h>
39 #include <sys/types.h>
40 #include <sys/stat.h>
41 #include <expat.h>
42 #include <curl/curl.h>
43 #include <libcitadel.h>
44 #include "citadel.h"
45 #include "server.h"
46 #include "citserver.h"
47 #include "support.h"
48 #include "config.h"
49 #include "threads.h"
50 #include "ctdl_module.h"
51 #include "clientsocket.h"
52 #include "msgbase.h"
53 #include "parsedate.h"
54 #include "database.h"
55 #include "citadel_dirs.h"
56 #include "md5.h"
57 #include "context.h"
58
59 typedef struct rssnetcfg rssnetcfg;
60
61 struct rssnetcfg {
62         rssnetcfg *next;
63         char url[256];
64         char *rooms;
65         time_t last_error_when;
66         int ItemType;
67 };
68
69 #define RSS_UNSET 0
70 #define RSS_RSS 1
71 #define RSS_ATOM 2
72
73 typedef struct _rss_item {
74         char *chardata;
75         int chardata_len;
76         char *roomlist;
77         int done_parsing;
78         char *guid;
79         char *title;
80         char *link;
81         char *description;
82         time_t pubdate;
83         char channel_title[256];
84         int item_tag_nesting;
85         char *author_or_creator;
86         char *author_url;
87         StrBuf *CData;
88 }rss_item;
89
90
91 typedef struct _rsscollection {
92         rss_item *Item;
93         rssnetcfg *Cfg;
94         
95
96 } rsscollection;
97
98 struct rssnetcfg *rnclist = NULL;
99
100
101 #if 0
102 #ifdef HAVE_ICONV
103 #include <iconv.h>
104
105
106 /* 
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
109  */
110
111 /* Returns: 
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). 
119 */ 
120 static int 
121 fill_encoding_info (const char *charset, XML_Encoding * info) 
122
123   iconv_t cd = (iconv_t)(-1); 
124   int flag; 
125         CtdlLogPrintf(0, "RSS: fill encoding info ...\n");
126  
127 #if G_BYTE_ORDER == G_LITTLE_ENDIAN 
128   cd = iconv_open ("UCS-2LE", charset); 
129 #else 
130   cd = iconv_open ("UCS-2BE", charset); 
131 #endif 
132  
133   if (cd == (iconv_t) (-1)) 
134     { 
135       return -1; 
136     } 
137  
138   { 
139     unsigned short out; 
140     unsigned char buf[4]; 
141     unsigned int i0, i1, i2; 
142     int result; 
143     flag = 0; 
144     for (i0 = 0; i0 < 0x100; i0++) 
145       { 
146         buf[0] = i0; 
147         info->map[i0] = 0; 
148         //result = try (cd, buf, 1, &out); 
149         if (result < 0) 
150           { 
151           } 
152         else if (result > 0) 
153           { 
154             info->map[i0] = out; 
155           } 
156         else 
157           { 
158             for (i1 = 0; i1 < 0x100; i1++) 
159               { 
160                 buf[1] = i1; 
161                 ///result = try (cd, buf, 2, &out); 
162                 if (result < 0) 
163                   { 
164                   } 
165                 else if (result > 0) 
166                   { 
167                     flag++; 
168                     info->map[i0] = -2; 
169                   } 
170                 else 
171                   { 
172                     for (i2 = 0; i2 < 0x100; i2++) 
173                       { 
174                         buf[2] = i2; 
175                         ////result = try (cd, buf, 3, &out); 
176                         if (result < 0) 
177                           { 
178                           } 
179                         else if (result > 0) 
180                           { 
181                             flag++; 
182                             info->map[i0] = -3; 
183                           } 
184                       } 
185                   } 
186               } 
187           } 
188       } 
189   } 
190  
191   if (iconv_close (cd) < 0) 
192     { 
193       return -2; 
194     } 
195   return flag; 
196
197
198 static int 
199 iconv_convertor (void *data, const char *s) 
200
201   XML_Encoding *info = data; 
202   int res; 
203         CtdlLogPrintf(0, "RSS: Converting ...\n");
204
205   if (s == NULL) 
206     return -1; 
207 /*
208   GByteArray *result; 
209   result = g_byte_array_new (); 
210   if (process_block (info->data, (char *) s, strlen (s), result) == 0) 
211     { 
212       res = *(result->data); 
213       g_byte_array_free (result, TRUE); 
214       return res; 
215     } 
216   g_byte_array_free (result, TRUE); 
217 */
218   return -1; 
219
220
221 static void 
222 my_release (void *data) 
223
224   iconv_t cd = (iconv_t) data; 
225   if (iconv_close (cd) != 0) 
226     { 
227 /// TODO: uh no.      exit (1); 
228     } 
229
230 int 
231 handle_unknown_xml_encoding (void *encodingHandleData, 
232                              const XML_Char * name, 
233                              XML_Encoding * info) 
234
235   int result; 
236   CtdlLogPrintf(0, "RSS: unknown encoding ...\n");
237   result = fill_encoding_info (name, info); 
238   if (result >= 0) 
239     { 
240       /*  
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. 
243       */ 
244       if(encodingHandleData != NULL) 
245             *((iconv_t *)encodingHandleData) = iconv_open(name, "UTF-8"); 
246       /*  
247          Optimization: we do not need conversion function if encoding is one-to-one,  
248          info->map table will be enough  
249        */ 
250       if (result == 0) 
251         { 
252           info->data = NULL; 
253           info->convert = NULL; 
254           info->release = NULL; 
255           return 1; 
256         } 
257       /*  
258          We do need conversion function because this encoding uses multibyte sequences 
259        */ 
260       info->data = (void *) iconv_open ("UTF-8", name); 
261       if ((int)info->data == -1) 
262         return -1; 
263       info->convert = iconv_convertor; 
264       info->release = my_release; 
265       return 1; 
266     } 
267   if(encodingHandleData != NULL)  
268     *(iconv_t *)encodingHandleData = NULL; 
269   return 0; 
270
271
272 #endif
273 #endif
274
275 /*
276  * Commit a fetched and parsed RSS item to disk
277  */
278 void rss_save_item(rsscollection *rssc) {
279
280         struct MD5Context md5context;
281         u_char rawdigest[MD5_DIGEST_LEN];
282         int i;
283         char utmsgid[SIZ];
284         struct cdbdata *cdbut;
285         struct UseTable ut;
286         struct CtdlMessage *msg;
287         struct recptypes *recp = NULL;
288         int msglen = 0;
289         rss_item *ri = rssc->Item;
290
291         recp = (struct recptypes *) malloc(sizeof(struct recptypes));
292         if (recp == NULL) return;
293         memset(recp, 0, sizeof(struct recptypes));
294         memset(&ut, 0, sizeof(struct UseTable));
295         recp->recp_room = strdup(ri->roomlist);
296         recp->num_room = num_tokens(ri->roomlist, '|');
297         recp->recptypes_magic = RECPTYPES_MAGIC;
298    
299         /* Construct a GUID to use in the S_USETABLE table.
300          * If one is not present in the item itself, make one up.
301          */
302         if (ri->guid != NULL) {
303                 snprintf(utmsgid, sizeof utmsgid, "rss/%s", ri->guid);
304         }
305         else {
306                 MD5Init(&md5context);
307                 if (ri->title != NULL) {
308                         MD5Update(&md5context, (unsigned char*)ri->title, strlen(ri->title));
309                 }
310                 if (ri->link != NULL) {
311                         MD5Update(&md5context, (unsigned char*)ri->link, strlen(ri->link));
312                 }
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]);
318                 }
319                 strcat(utmsgid, "_rss2ctdl");
320         }
321
322         /* Find out if we've already seen this item */
323
324         cdbut = cdb_fetch(CDB_USETABLE, utmsgid, strlen(utmsgid));
325         if (cdbut != NULL) {
326                 /* Item has already been seen */
327                 CtdlLogPrintf(CTDL_DEBUG, "%s has already been seen\n", utmsgid);
328                 cdb_free(cdbut);
329
330                 /* rewrite the record anyway, to update the timestamp */
331                 strcpy(ut.ut_msgid, utmsgid);
332                 ut.ut_timestamp = time(NULL);
333                 cdb_store(CDB_USETABLE, utmsgid, strlen(utmsgid), &ut, sizeof(struct UseTable) );
334         }
335         else {
336                 /* Item has not been seen, so save it. */
337                 CtdlLogPrintf(CTDL_DEBUG, "RSS: saving item...\n");
338                 if (ri->description == NULL) ri->description = strdup("");
339                 for (i=strlen(ri->description); i>=0; --i) {
340                         if (isspace(ri->description[i])) {
341                                 ri->description[i] = ' ';
342                         }
343                 }
344
345                 msg = malloc(sizeof(struct CtdlMessage));
346                 memset(msg, 0, sizeof(struct CtdlMessage));
347                 msg->cm_magic = CTDLMESSAGE_MAGIC;
348                 msg->cm_anon_type = MES_NORMAL;
349                 msg->cm_format_type = FMT_RFC822;
350
351                 if (ri->guid != NULL) {
352                         msg->cm_fields['E'] = strdup(ri->guid);
353                 }
354
355                 if (ri->author_or_creator != NULL) {
356                         char *From;
357                         StrBuf *Encoded, *QPEncoded;
358                         StrBuf *UserName;
359                         StrBuf *EmailAddress;
360                         StrBuf *EncBuf;
361                         
362                         UserName = NewStrBuf();
363                         EmailAddress = NewStrBuf();
364                         EncBuf = NewStrBuf();
365
366                         From = html_to_ascii(ri->author_or_creator,
367                                              strlen(ri->author_or_creator), 
368                                              512, 0);
369
370                         Encoded = NewStrBufPlain(From, -1);
371                         free(From);
372                         StrBufTrim(Encoded);
373                         QPEncoded = StrBufSanitizeEmailRecipientVector(Encoded, UserName, EmailAddress, EncBuf);
374                         msg->cm_fields['A'] = SmashStrBuf(&QPEncoded);
375
376                         FreeStrBuf(&Encoded);
377                         FreeStrBuf(&UserName);
378                         FreeStrBuf(&EmailAddress);
379                         FreeStrBuf(&EncBuf);
380
381                 }
382                 else {
383                         msg->cm_fields['A'] = strdup("rss");
384                 }
385
386                 msg->cm_fields['N'] = strdup(NODENAME);
387                 if (ri->title != NULL) {
388                         long len;
389                         char *Sbj;
390                         StrBuf *Encoded, *QPEncoded;
391
392                         QPEncoded = NULL;
393                         len = strlen(ri->title);
394                         Sbj = html_to_ascii(ri->title, len, 512, 0);
395                         Encoded = NewStrBufPlain(Sbj, -1);
396                         free(Sbj);
397
398                         StrBufTrim(Encoded);
399                         StrBufRFC2047encode(&QPEncoded, Encoded);
400
401                         msg->cm_fields['U'] = SmashStrBuf(&QPEncoded);
402                         FreeStrBuf(&Encoded);
403                 }
404                 msg->cm_fields['T'] = malloc(64);
405                 snprintf(msg->cm_fields['T'], 64, "%ld", ri->pubdate);
406                 if (ri->channel_title != NULL) {
407                         if (!IsEmptyStr(ri->channel_title)) {
408                                 msg->cm_fields['O'] = strdup(ri->channel_title);
409                         }
410                 }
411                 if (ri->link == NULL) 
412                         ri->link = strdup("");
413                 msglen += 1024 + strlen(ri->link) + strlen(ri->description) ;
414                 msg->cm_fields['M'] = malloc(msglen);
415                 snprintf(msg->cm_fields['M'], msglen,
416                         "Content-type: text/html; charset=\"UTF-8\"\r\n\r\n"
417                         "<html><body>\n"
418                         "%s<br><br>\n"
419                         "<a href=\"%s\">%s</a>\n"
420                         "</body></html>\n"
421                         ,
422                         ri->description,
423                         ri->link, ri->link
424                 );
425
426                 CtdlSubmitMsg(msg, recp, NULL, 0);
427                 CtdlFreeMessage(msg);
428
429                 /* write the uidl to the use table so we don't store this item again */
430                 strcpy(ut.ut_msgid, utmsgid);
431                 ut.ut_timestamp = time(NULL);
432                 cdb_store(CDB_USETABLE, utmsgid, strlen(utmsgid), &ut, sizeof(struct UseTable) );
433         }
434         free_recipients(recp);
435 }
436
437
438
439 /*
440  * Convert an RDF/RSS datestamp into a time_t
441  */
442 time_t rdf_parsedate(char *p)
443 {
444         struct tm tm;
445         time_t t = 0;
446
447         if (!p) return 0L;
448         if (strlen(p) < 10) return 0L;
449
450         memset(&tm, 0, sizeof tm);
451
452         /*
453          * If the timestamp appears to be in W3C datetime format, try to
454          * parse it.  See also: http://www.w3.org/TR/NOTE-datetime
455          *
456          * This code, along with parsedate.c, is a potential candidate for
457          * moving into libcitadel.
458          */
459         if ( (p[4] == '-') && (p[7] == '-') ) {
460                 tm.tm_year = atoi(&p[0]) - 1900;
461                 tm.tm_mon = atoi(&p[5]) - 1;
462                 tm.tm_mday = atoi(&p[8]);
463                 if ( (p[10] == 'T') && (p[13] == ':') ) {
464                         tm.tm_hour = atoi(&p[11]);
465                         tm.tm_min = atoi(&p[14]);
466                 }
467                 return mktime(&tm);
468         }
469
470         /* hmm... try RFC822 date stamp format */
471
472         t = parsedate(p);
473         if (t > 0) return(t);
474
475         /* yeesh.  ok, just return the current date and time. */
476         return(time(NULL));
477 }
478
479 #define RSS_UNSET 0
480 #define RSS_RSS 1
481 #define RSS_ATOM 2
482
483 void flush_rss_ite(rss_item *ri)
484 {
485         /* Initialize the feed item data structure */
486         if (ri->guid != NULL) free(ri->guid);
487         ri->guid = NULL;
488         if (ri->title != NULL) free(ri->title);
489         ri->title = NULL;
490         if (ri->link != NULL) free(ri->link);
491         ri->link = NULL;
492         if (ri->author_or_creator != NULL) free(ri->author_or_creator);
493         ri->author_or_creator = NULL;
494         if (ri->author_url != NULL) free(ri->author_url);
495         ri->author_url = NULL;
496         if (ri->description != NULL) free(ri->description);
497         ri->description = NULL;
498         /* Throw away any existing character data */
499         if (ri->chardata_len > 0) {
500                 free(ri->chardata);
501                 ri->chardata = 0;
502                 ri->chardata_len = 0;
503         }
504         FreeStrBuf(&ri->CData);
505 }
506
507 void rss_xml_start(void *data, const char *supplied_el, const char **attr) {
508         rsscollection *rssc = (rsscollection*) data;
509         rss_item *ri = rssc->Item;
510         char el[256];
511         char *sep = NULL;
512
513         /* Axe the namespace, we don't care about it */
514 ///     CtdlLogPrintf(0, "RSS: supplied el %d: %s...\n", rssc->Cfg->ItemType, supplied_el);
515         safestrncpy(el, supplied_el, sizeof el);
516         while (sep = strchr(el, ':'), sep) {
517                 strcpy(el, ++sep);
518         }
519
520         if ((rssc->Cfg->ItemType == RSS_UNSET) && !strcasecmp(el, "rss")) 
521         {
522                 CtdlLogPrintf(9, "RSS: This is an RSS feed.\n");
523                 rssc->Cfg->ItemType = RSS_RSS;
524         }
525         if ((rssc->Cfg->ItemType == RSS_UNSET) && !strcasecmp(el, "rdf")) 
526         {
527                 CtdlLogPrintf(9, "RSS: This is an RDF feed.\n");
528                 rssc->Cfg->ItemType = RSS_RSS;
529         }
530         else if ((rssc->Cfg->ItemType == RSS_UNSET) && !strcasecmp(el, "feed")) 
531         {
532                 CtdlLogPrintf(9, "RSS: This is an ATOM feed.\n");
533                 rssc->Cfg->ItemType = RSS_ATOM;
534         }
535         else if ((rssc->Cfg->ItemType == RSS_RSS) &&
536             !strcasecmp(el, "item")) 
537         {
538                 ri->item_tag_nesting ++ ;
539                 flush_rss_ite(ri);
540         }
541         else if ( (rssc->Cfg->ItemType == RSS_ATOM) &&
542                  !strcasecmp(el, "entry")) 
543         { /* Atom feed... */
544                 ++ri->item_tag_nesting;
545                 flush_rss_ite(ri);
546         }
547         else if ((rssc->Cfg->ItemType == RSS_ATOM) &&
548                  !strcasecmp(el, "link"))
549         {
550                 int found ;
551                 int i;
552
553                 for (found = 0, i = 0;!found && attr[i] != NULL; i+=2)
554                 {
555                         if (!strcmp(attr[i], "href"))
556                         {
557                                 found = 1;
558                                 if (ri->link != NULL)
559                                         free(ri->link);
560                                 ri->link = strdup(attr[i+1]);
561                                 striplt(ri->link);
562                         }
563                 }
564
565         }
566
567 }
568
569 void rss_xml_end(void *data, const char *supplied_el) {
570         rsscollection *rssc = (rsscollection*) data;
571         rss_item *ri = rssc->Item;
572         char el[256];
573         char *sep = NULL;
574
575         /* Axe the namespace, we don't care about it */
576         safestrncpy(el, supplied_el, sizeof el);
577         while (sep = strchr(el, ':'), sep) {
578                 strcpy(el, ++sep);
579         }
580 //      CtdlLogPrintf(0, "RSS: END %s...\n", el);
581
582         if ( (!strcasecmp(el, "title")) && (ri->item_tag_nesting == 0) && (ri->chardata != NULL) ) {
583                 safestrncpy(ri->channel_title, ri->chardata, sizeof ri->channel_title);
584                 striplt(ri->channel_title);
585         }
586
587         if ( (rssc->Cfg->ItemType == RSS_RSS) && 
588              (!strcasecmp(el, "guid")) && (ri->chardata != NULL) ) {
589                 if (ri->guid != NULL) free(ri->guid);
590                 striplt(ri->chardata);
591                 ri->guid = strdup(ri->chardata);
592         }
593         else if ( (rssc->Cfg->ItemType == RSS_ATOM) && 
594                   (!strcasecmp(el, "id")) && (ri->chardata != NULL) ) {
595                 if (ri->guid != NULL) free(ri->guid);
596                 striplt(ri->chardata);
597                 ri->guid = strdup(ri->chardata);
598         }
599
600         else if ( (rssc->Cfg->ItemType == RSS_RSS) && (!strcasecmp(el, "link")) && (ri->chardata != NULL) ) {
601                 if (ri->link != NULL) free(ri->link);
602                 striplt(ri->chardata);
603                 ri->link = strdup(ri->chardata);
604         }
605
606         else if ( (!strcasecmp(el, "title")) && (ri->chardata != NULL) ) {
607                 if (ri->title != NULL) free(ri->title);
608                 striplt(ri->chardata);
609                 ri->title = strdup(ri->chardata);
610         }
611
612         else if ((rssc->Cfg->ItemType == RSS_ATOM) && 
613                  (!strcasecmp(el, "content")) && 
614                  (ri->chardata != NULL) ) {
615                 if (ri->description != NULL) free(ri->description);
616                 ri->description = strdup(ri->chardata);
617         }
618         else if ( (rssc->Cfg->ItemType == RSS_RSS) && 
619                   (!strcasecmp(el, "description")) &&
620                   (ri->chardata != NULL) ) {
621                 if (ri->description != NULL) free(ri->description);
622                 ri->description = strdup(ri->chardata);
623         }
624                   
625         else if ((rssc->Cfg->ItemType == RSS_ATOM) && 
626                  ((!strcasecmp(el, "published")) ||
627                   (!strcasecmp(el, "updated"))) &&
628                  (ri->chardata != NULL) ) {
629                 striplt(ri->chardata);
630                 ri->pubdate = rdf_parsedate(ri->chardata);
631         }
632
633
634         else if ((rssc->Cfg->ItemType == RSS_RSS) && 
635                  ((!strcasecmp(el, "pubdate")) || 
636                   (!strcasecmp(el, "date"))) && 
637                  (ri->chardata != NULL) ) {
638                 striplt(ri->chardata);
639                 ri->pubdate = rdf_parsedate(ri->chardata);
640         }
641
642         else if ((rssc->Cfg->ItemType == RSS_RSS) && 
643                  ((!strcasecmp(el, "author")) || 
644                   (!strcasecmp(el, "creator"))) && 
645                  (ri->chardata != NULL) ) {
646                 if (ri->author_or_creator != NULL) free(ri->author_or_creator);
647                 striplt(ri->chardata);
648                 ri->author_or_creator = strdup(ri->chardata);
649         }
650
651         else if ((rssc->Cfg->ItemType == RSS_ATOM) && 
652                  (!strcasecmp(el, "name")) && 
653                  (ri->chardata != NULL) ) {
654                 if (ri->author_or_creator != NULL) free(ri->author_or_creator);
655                 striplt(ri->chardata);
656                 ri->author_or_creator = strdup(ri->chardata);
657         }
658         else if ((rssc->Cfg->ItemType == RSS_ATOM) && 
659                  (!strcasecmp(el, "uri")) && 
660                  (ri->chardata != NULL) ) {
661                 if (ri->author_url != NULL) free(ri->author_url);
662                 striplt(ri->chardata);
663                 ri->author_url = strdup(ri->chardata);
664         }
665
666         else if ((rssc->Cfg->ItemType == RSS_RSS) && 
667                  !strcasecmp(el, "item")) {
668                 --ri->item_tag_nesting;
669                 rss_save_item(rssc);
670         }
671         else if ((rssc->Cfg->ItemType == RSS_ATOM) && 
672                  !strcasecmp(el, "entry")) {
673                 --ri->item_tag_nesting;
674                 rss_save_item(rssc);
675         }
676
677         else if ( (!strcasecmp(el, "rss")) || 
678                   (!strcasecmp(el, "rdf")) ) {
679 //              CtdlLogPrintf(CTDL_DEBUG, "End of feed detected.  Closing parser.\n");
680                 ri->done_parsing = 1;
681         }
682
683         if (ri->chardata_len > 0) {
684                 free(ri->chardata);
685                 ri->chardata = 0;
686                 ri->chardata_len = 0;
687         }
688
689 }
690
691
692 /*
693  * This callback stores up the data which appears in between tags.
694  */
695 void rss_xml_cdata_start(void *data) {
696         rsscollection *rssc = (rsscollection*) data;
697         rss_item *ri = rssc->Item;
698
699         ri->CData = NewStrBuf();
700 }
701
702 void rss_xml_cdata_end(void *data) {
703         rsscollection *rssc = (rsscollection*) data;
704         rss_item *ri = rssc->Item;
705
706         ri->description = SmashStrBuf(&ri->CData);
707 }
708 void rss_xml_chardata(void *data, const XML_Char *s, int len) {
709         rsscollection *rssc = (rsscollection*) data;
710         rss_item *ri = rssc->Item;
711         int old_len;
712         int new_len;
713         char *new_buffer;
714
715         if (ri->CData != NULL) {
716                 StrBufAppendBufPlain (ri->CData, s, len, 0);
717         } else {
718                 old_len = ri->chardata_len;
719                 new_len = old_len + len;
720                 new_buffer = realloc(ri->chardata, new_len + 1);
721                 if (new_buffer != NULL) {
722                         memcpy(&new_buffer[old_len], s, len);
723                         new_buffer[new_len] = 0;
724                         ri->chardata = new_buffer;
725                         ri->chardata_len = new_len;
726                 }
727         }
728 }
729
730 /*
731  * Callback function for passing libcurl's output to expat for parsing
732  */
733 size_t rss_libcurl_callback(void *ptr, size_t size, size_t nmemb, void *stream)
734 {
735         XML_Parse((XML_Parser)stream, ptr, (size * nmemb), 0);
736         return (size*nmemb);
737 }
738
739
740
741 /*
742  * Begin a feed parse
743  */
744 void rss_do_fetching(rssnetcfg *Cfg) {
745         rsscollection rssc;
746         rss_item ri;
747         XML_Parser xp;
748
749         CURL *curl;
750         CURLcode res;
751         char errmsg[1024] = "";
752
753         rssc.Item = &ri;
754         rssc.Cfg = Cfg;
755
756         CtdlLogPrintf(CTDL_DEBUG, "Fetching RSS feed <%s>\n", Cfg->url);
757
758         curl = curl_easy_init();
759         if (!curl) {
760                 CtdlLogPrintf(CTDL_ALERT, "Unable to initialize libcurl.\n");
761                 return;
762         }
763
764         xp = XML_ParserCreateNS("UTF-8", ':');
765         if (!xp) {
766                 CtdlLogPrintf(CTDL_ALERT, "Cannot create XML parser!\n");
767                 curl_easy_cleanup(curl);
768                 return;
769         }
770
771         curl_easy_setopt(curl, CURLOPT_URL, Cfg->url);
772         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
773         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
774         curl_easy_setopt(curl, CURLOPT_WRITEDATA, xp);
775         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, rss_libcurl_callback);
776         curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
777         curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
778 #ifdef CURLOPT_HTTP_CONTENT_DECODING
779         curl_easy_setopt(curl, CURLOPT_HTTP_CONTENT_DECODING, 1);
780         curl_easy_setopt(curl, CURLOPT_ENCODING, "");
781 #endif
782         curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
783         curl_easy_setopt(curl, CURLOPT_TIMEOUT, 180);           /* die after 180 seconds */
784         if (
785                 (!IsEmptyStr(config.c_ip_addr))
786                 && (strcmp(config.c_ip_addr, "*"))
787                 && (strcmp(config.c_ip_addr, "::"))
788                 && (strcmp(config.c_ip_addr, "0.0.0.0"))
789         ) {
790                 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
791         }
792
793         memset(&ri, 0, sizeof(rss_item));
794         ri.roomlist = Cfg->rooms;
795 #ifdef HAVE_ICONV
796 #if 0
797         XML_SetUnknownEncodingHandler(xp,
798                                       handle_unknown_xml_encoding,
799                                       NULL);
800 #endif
801 #endif
802         XML_SetElementHandler(xp, rss_xml_start, rss_xml_end);
803         XML_SetCharacterDataHandler(xp, rss_xml_chardata);
804         XML_SetUserData(xp, &rssc);
805         XML_SetCdataSectionHandler(xp,
806                                    rss_xml_cdata_start,
807                                    rss_xml_cdata_end);
808         if (CtdlThreadCheckStop())
809         {
810                 XML_ParserFree(xp);
811                 curl_easy_cleanup(curl);
812                 return;
813         }
814         
815         if (CtdlThreadCheckStop())
816                 goto shutdown ;
817
818         res = curl_easy_perform(curl);
819         if (res) {
820                 CtdlLogPrintf(CTDL_ALERT, "libcurl error %d: %s\n", res, errmsg);
821         }
822
823         if (CtdlThreadCheckStop())
824                 goto shutdown ;
825
826         if (ri.done_parsing == 0)
827                 XML_Parse(xp, "", 0, 1);
828
829
830         CtdlLogPrintf(CTDL_ALERT, "RSS: XML Status [%s] \n", 
831                       XML_ErrorString(
832                               XML_GetErrorCode(xp)));
833
834 shutdown:
835         curl_easy_cleanup(curl);
836         XML_ParserFree(xp);
837
838         flush_rss_ite(&ri);
839 }
840
841
842 /*
843  * Scan a room's netconfig to determine whether it is requesting any RSS feeds
844  */
845 void rssclient_scan_room(struct ctdlroom *qrbuf, void *data)
846 {
847         char filename[PATH_MAX];
848         char buf[1024];
849         char instr[32];
850         FILE *fp;
851         char feedurl[256];
852         rssnetcfg *rncptr = NULL;
853         rssnetcfg *use_this_rncptr = NULL;
854         int len = 0;
855         char *ptr = NULL;
856
857         assoc_file_name(filename, sizeof filename, qrbuf, ctdl_netcfg_dir);
858
859         if (CtdlThreadCheckStop())
860                 return;
861                 
862         /* Only do net processing for rooms that have netconfigs */
863         fp = fopen(filename, "r");
864         if (fp == NULL) {
865                 return;
866         }
867
868         while (fgets(buf, sizeof buf, fp) != NULL && !CtdlThreadCheckStop()) {
869                 buf[strlen(buf)-1] = 0;
870
871                 extract_token(instr, buf, 0, '|', sizeof instr);
872                 if (!strcasecmp(instr, "rssclient")) {
873
874                         use_this_rncptr = NULL;
875
876                         extract_token(feedurl, buf, 1, '|', sizeof feedurl);
877
878                         /* If any other rooms have requested the same feed, then we will just add this
879                          * room to the target list for that client request.
880                          */
881                         for (rncptr=rnclist; rncptr!=NULL; rncptr=rncptr->next) {
882                                 if (!strcmp(rncptr->url, feedurl)) {
883                                         use_this_rncptr = rncptr;
884                                 }
885                         }
886
887                         /* Otherwise create a new client request */
888                         if (use_this_rncptr == NULL) {
889                                 rncptr = (rssnetcfg *) malloc(sizeof(rssnetcfg));
890                                 rncptr->ItemType = RSS_UNSET;
891                                 if (rncptr != NULL) {
892                                         rncptr->next = rnclist;
893                                         safestrncpy(rncptr->url, feedurl, sizeof rncptr->url);
894                                         rncptr->rooms = NULL;
895                                         rnclist = rncptr;
896                                         use_this_rncptr = rncptr;
897                                 }
898                         }
899
900                         /* Add the room name to the request */
901                         if (use_this_rncptr != NULL) {
902                                 if (use_this_rncptr->rooms == NULL) {
903                                         rncptr->rooms = strdup(qrbuf->QRname);
904                                 }
905                                 else {
906                                         len = strlen(use_this_rncptr->rooms) + strlen(qrbuf->QRname) + 5;
907                                         ptr = realloc(use_this_rncptr->rooms, len);
908                                         if (ptr != NULL) {
909                                                 strcat(ptr, "|");
910                                                 strcat(ptr, qrbuf->QRname);
911                                                 use_this_rncptr->rooms = ptr;
912                                         }
913                                 }
914                         }
915                 }
916
917         }
918
919         fclose(fp);
920
921 }
922
923 /*
924  * Scan for rooms that have RSS client requests configured
925  */
926 void *rssclient_scan(void *args) {
927         static time_t last_run = 0L;
928         static int doing_rssclient = 0;
929         rssnetcfg *rptr = NULL;
930         CitContext rssclientCC;
931
932         /* Give this thread its own private CitContext */
933         CtdlFillSystemContext(&rssclientCC, "rssclient");
934         citthread_setspecific(MyConKey, (void *)&rssclientCC );
935
936         /*
937          * This is a simple concurrency check to make sure only one rssclient run
938          * is done at a time.  We could do this with a mutex, but since we
939          * don't really require extremely fine granularity here, we'll do it
940          * with a static variable instead.
941          */
942         if (doing_rssclient) return NULL;
943         doing_rssclient = 1;
944
945         CtdlLogPrintf(CTDL_DEBUG, "rssclient started\n");
946         CtdlForEachRoom(rssclient_scan_room, NULL);
947
948         while (rnclist != NULL && !CtdlThreadCheckStop()) {
949                 rss_do_fetching(rnclist);
950                 rptr = rnclist;
951                 rnclist = rnclist->next;
952                 if (rptr->rooms != NULL) free(rptr->rooms);
953                 free(rptr);
954         }
955
956         CtdlLogPrintf(CTDL_DEBUG, "rssclient ended\n");
957         last_run = time(NULL);
958         doing_rssclient = 0;
959         if (!CtdlThreadCheckStop())
960                 CtdlThreadSchedule ("RSS Client", CTDLTHREAD_BIGSTACK, rssclient_scan, NULL, last_run + config.c_net_freq);
961         else
962                 CtdlLogPrintf(CTDL_DEBUG, "rssclient: Task STOPPED.\n");
963         CtdlClearSystemContext();
964         return NULL;
965 }
966
967
968 CTDL_MODULE_INIT(rssclient)
969 {
970         if (threading)
971         {
972                 CtdlLogPrintf(CTDL_INFO, "%s\n", curl_version());
973                 CtdlThreadSchedule ("RSS Client", CTDLTHREAD_BIGSTACK, rssclient_scan, NULL, 0);
974         }
975         /* return our Subversion id for the Log */
976         return "rssclient";
977 }