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