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