* start atom feed reader implementation, most of the freshmeat.org feed seems to...
[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 }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         CtdlLogPrintf(0, "RSS: saving item...\n");
292         recp = (struct recptypes *) malloc(sizeof(struct recptypes));
293         if (recp == NULL) return;
294         memset(recp, 0, sizeof(struct recptypes));
295         recp->recp_room = strdup(ri->roomlist);
296         recp->num_room = num_tokens(ri->roomlist, '|');
297         recp->recptypes_magic = RECPTYPES_MAGIC;
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         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
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->author_or_creator != NULL) {
351                         msg->cm_fields['A'] = html_to_ascii(ri->author_or_creator,
352                                 strlen(ri->author_or_creator), 512, 0);
353                         striplt(msg->cm_fields['A']);
354                 }
355                 else {
356                         msg->cm_fields['A'] = strdup("rss");
357                 }
358
359                 msg->cm_fields['N'] = strdup(NODENAME);
360                 if (ri->title != NULL) {
361                         msg->cm_fields['U'] = html_to_ascii(ri->title, strlen(ri->title), 512, 0);
362                         striplt(msg->cm_fields['U']);
363                 }
364                 msg->cm_fields['T'] = malloc(64);
365                 snprintf(msg->cm_fields['T'], 64, "%ld", ri->pubdate);
366                 if (ri->channel_title != NULL) {
367                         if (!IsEmptyStr(ri->channel_title)) {
368                                 msg->cm_fields['O'] = strdup(ri->channel_title);
369                         }
370                 }
371                 if (ri->link == NULL) 
372                         ri->link = strdup("");
373                 msglen += 1024 + strlen(ri->link) + strlen(ri->description) ;
374                 msg->cm_fields['M'] = malloc(msglen);
375                 snprintf(msg->cm_fields['M'], msglen,
376                         "Content-type: text/html; charset=\"UTF-8\"\r\n\r\n"
377                         "<html><body>\n"
378                         "%s<br><br>\n"
379                         "<a href=\"%s\">%s</a>\n"
380                         "</body></html>\n"
381                         ,
382                         ri->description,
383                         ri->link, ri->link
384                 );
385
386                 CtdlSubmitMsg(msg, recp, NULL, 0);
387                 CtdlFreeMessage(msg);
388
389                 /* write the uidl to the use table so we don't store this item again */
390                 strcpy(ut.ut_msgid, utmsgid);
391                 ut.ut_timestamp = time(NULL);
392                 cdb_store(CDB_USETABLE, utmsgid, strlen(utmsgid), &ut, sizeof(struct UseTable) );
393         }
394         free_recipients(recp);
395 }
396
397
398
399 /*
400  * Convert an RDF/RSS datestamp into a time_t
401  */
402 time_t rdf_parsedate(char *p)
403 {
404         struct tm tm;
405         time_t t = 0;
406
407         if (!p) return 0L;
408         if (strlen(p) < 10) return 0L;
409
410         memset(&tm, 0, sizeof tm);
411
412         /* YYYY-MM-DDTHH:MM format...
413          */
414         if ( (p[4] == '-') && (p[7] == '-') ) {
415                 tm.tm_year = atoi(&p[0]) - 1900;
416                 tm.tm_mon = atoi(&p[5]) - 1;
417                 tm.tm_mday = atoi(&p[8]);
418                 if ( (p[10] == 'T') && (p[13] == ':') ) {
419                         tm.tm_hour = atoi(&p[11]);
420                         tm.tm_min = atoi(&p[14]);
421                 }
422                 return mktime(&tm);
423         }
424
425         /* hmm... try RFC822 date stamp format */
426
427         t = parsedate(p);
428         if (t > 0) return(t);
429
430         /* yeesh.  ok, just return the current date and time. */
431         return(time(NULL));
432 }
433
434 #define RSS_UNSET 0
435 #define RSS_RSS 1
436 #define RSS_ATOM 2
437
438 void flush_rss_ite(rss_item *ri)
439 {
440         /* Initialize the feed item data structure */
441         if (ri->guid != NULL) free(ri->guid);
442         ri->guid = NULL;
443         if (ri->title != NULL) free(ri->title);
444         ri->title = NULL;
445         if (ri->link != NULL) free(ri->link);
446         ri->link = NULL;
447         if (ri->author_or_creator != NULL) free(ri->author_or_creator);
448         ri->author_or_creator = NULL;
449         if (ri->description != NULL) free(ri->description);
450         ri->description = NULL;
451         /* Throw away any existing character data */
452         if (ri->chardata_len > 0) {
453                 free(ri->chardata);
454                 ri->chardata = 0;
455                 ri->chardata_len = 0;
456         }
457 }
458
459 void rss_xml_start(void *data, const char *supplied_el, const char **attr) {
460         rsscollection *rssc = (rsscollection*) data;
461         rss_item *ri = rssc->Item;
462         char el[256];
463         char *sep = NULL;
464
465         /* Axe the namespace, we don't care about it */
466 ///     CtdlLogPrintf(0, "RSS: supplied el %d: %s...\n", rssc->Cfg->ItemType, supplied_el);
467         safestrncpy(el, supplied_el, sizeof el);
468         while (sep = strchr(el, ':'), sep) {
469                 strcpy(el, ++sep);
470         }
471
472         if (((rssc->Cfg->ItemType == RSS_UNSET) || 
473              (rssc->Cfg->ItemType == RSS_RSS)) &&
474             !strcasecmp(el, "item")) 
475         {
476                 ri->item_tag_nesting ++ ;
477                 rssc->Cfg->ItemType = RSS_RSS;
478                 flush_rss_ite(ri);
479         }
480         else if (((rssc->Cfg->ItemType == RSS_UNSET) || 
481                   (rssc->Cfg->ItemType == RSS_ATOM)) &&
482                  !strcasecmp(el, "entry")) { /* Atom feed... */
483                 CtdlLogPrintf(0, "RSS: found atom...\n");
484                 ++ri->item_tag_nesting;
485                 rssc->Cfg->ItemType = RSS_ATOM;
486                 flush_rss_ite(ri);
487         }
488         else if ((rssc->Cfg->ItemType == RSS_ATOM) &&
489                  !strcasecmp(el, "link"))
490         {
491                 int found ;
492                 int i;
493
494                 for (found = 0, i = 0;!found && attr[i] != NULL; i+=2)
495                 {
496                         if (!strcmp(attr[i], "href"))
497                         {
498                                 found = 1;
499                                 if (ri->link != NULL)
500                                         free(ri->link);
501                                 ri->link = strdup(attr[i+1]);
502                                 striplt(ri->link);
503                         }
504                 }
505
506         }
507
508 }
509
510 void rss_xml_end(void *data, const char *supplied_el) {
511         rsscollection *rssc = (rsscollection*) data;
512         rss_item *ri = rssc->Item;
513         char el[256];
514         char *sep = NULL;
515
516         /* Axe the namespace, we don't care about it */
517         safestrncpy(el, supplied_el, sizeof el);
518         while (sep = strchr(el, ':'), sep) {
519                 strcpy(el, ++sep);
520         }
521 //      CtdlLogPrintf(0, "RSS: END %s...\n", el);
522
523         if ( (!strcasecmp(el, "title")) && (ri->item_tag_nesting == 0) && (ri->chardata != NULL) ) {
524                 safestrncpy(ri->channel_title, ri->chardata, sizeof ri->channel_title);
525                 striplt(ri->channel_title);
526         }
527
528         if ( (rssc->Cfg->ItemType == RSS_RSS) && 
529              (!strcasecmp(el, "guid")) && (ri->chardata != NULL) ) {
530                 if (ri->guid != NULL) free(ri->guid);
531                 striplt(ri->chardata);
532                 ri->guid = strdup(ri->chardata);
533         }
534         else if ( (rssc->Cfg->ItemType == RSS_ATOM) && 
535                   (!strcasecmp(el, "id")) && (ri->chardata != NULL) ) {
536                 if (ri->guid != NULL) free(ri->guid);
537                 striplt(ri->chardata);
538                 ri->guid = strdup(ri->chardata);
539         }
540
541
542         else if ( (!strcasecmp(el, "title")) && (ri->chardata != NULL) ) {
543                 if (ri->title != NULL) free(ri->title);
544                 striplt(ri->chardata);
545                 ri->title = strdup(ri->chardata);
546         }
547
548         else if ((rssc->Cfg->ItemType == RSS_ATOM) && 
549                  (!strcasecmp(el, "content")) && 
550                  (ri->chardata != NULL) ) {
551                 if (ri->description != NULL) free(ri->description);
552                 ri->description = strdup(ri->chardata);
553         }
554         else if ( (rssc->Cfg->ItemType == RSS_RSS) && 
555                   (!strcasecmp(el, "description")) &&
556                   (ri->chardata != NULL) ) {
557                 if (ri->description != NULL) free(ri->description);
558                 ri->description = strdup(ri->chardata);
559         }
560                   
561         else if ((rssc->Cfg->ItemType == RSS_ATOM) && 
562                  ((!strcasecmp(el, "published")) ||
563                   (!strcasecmp(el, "updated"))) &&
564                  (ri->chardata != NULL) ) {
565                 striplt(ri->chardata);
566                 ri->pubdate = rdf_parsedate(ri->chardata);
567         }
568
569
570         else if ((rssc->Cfg->ItemType == RSS_RSS) && 
571                  ((!strcasecmp(el, "pubdate")) || 
572                   (!strcasecmp(el, "date"))) && 
573                  (ri->chardata != NULL) ) {
574                 striplt(ri->chardata);
575                 ri->pubdate = rdf_parsedate(ri->chardata);
576         }
577
578         else if ((rssc->Cfg->ItemType == RSS_ATOM) && 
579                  ((!strcasecmp(el, "author")) || 
580                   (!strcasecmp(el, "creator"))) && 
581                  (ri->chardata != NULL) ) {
582                 if (ri->author_or_creator != NULL) free(ri->author_or_creator);
583                 striplt(ri->chardata);
584                 ri->author_or_creator = strdup(ri->chardata);
585         }
586
587         else if ((rssc->Cfg->ItemType == RSS_RSS) && 
588                  !strcasecmp(el, "item")) {
589                 --ri->item_tag_nesting;
590                 rss_save_item(rssc);
591         }
592         else if ((rssc->Cfg->ItemType == RSS_ATOM) && 
593                  !strcasecmp(el, "entry")) {
594                 --ri->item_tag_nesting;
595                 rss_save_item(rssc);
596         }
597
598         else if ( (!strcasecmp(el, "rss")) || 
599                   (!strcasecmp(el, "rdf")) ) {
600 //              CtdlLogPrintf(CTDL_DEBUG, "End of feed detected.  Closing parser.\n");
601                 ri->done_parsing = 1;
602         }
603
604         if (ri->chardata_len > 0) {
605                 free(ri->chardata);
606                 ri->chardata = 0;
607                 ri->chardata_len = 0;
608         }
609
610 }
611
612
613 /*
614  * This callback stores up the data which appears in between tags.
615  */
616 void rss_xml_chardata(void *data, const XML_Char *s, int len) {
617         rsscollection *rssc = (rsscollection*) data;
618         rss_item *ri = rssc->Item;
619         int old_len;
620         int new_len;
621         char *new_buffer;
622
623         old_len = ri->chardata_len;
624         new_len = old_len + len;
625         new_buffer = realloc(ri->chardata, new_len + 1);
626         if (new_buffer != NULL) {
627                 memcpy(&new_buffer[old_len], s, len);
628                 new_buffer[new_len] = 0;
629                 ri->chardata = new_buffer;
630                 ri->chardata_len = new_len;
631         }
632 }
633
634
635
636 /*
637  * Callback function for passing libcurl's output to expat for parsing
638  */
639 size_t rss_libcurl_callback(void *ptr, size_t size, size_t nmemb, void *stream)
640 {
641         XML_Parse((XML_Parser)stream, ptr, (size * nmemb), 0);
642         return (size*nmemb);
643 }
644
645
646
647 /*
648  * Begin a feed parse
649  */
650 void rss_do_fetching(rssnetcfg *Cfg) {
651         rsscollection rssc;
652         rss_item ri;
653         XML_Parser xp;
654
655         CURL *curl;
656         CURLcode res;
657         char errmsg[1024] = "";
658
659         rssc.Item = &ri;
660         rssc.Cfg = Cfg;
661
662         CtdlLogPrintf(CTDL_DEBUG, "Fetching RSS feed <%s>\n", Cfg->url);
663
664         curl = curl_easy_init();
665         if (!curl) {
666                 CtdlLogPrintf(CTDL_ALERT, "Unable to initialize libcurl.\n");
667                 return;
668         }
669
670         xp = XML_ParserCreateNS("UTF-8", ':');
671         if (!xp) {
672                 CtdlLogPrintf(CTDL_ALERT, "Cannot create XML parser!\n");
673                 curl_easy_cleanup(curl);
674                 return;
675         }
676
677         curl_easy_setopt(curl, CURLOPT_URL, Cfg->url);
678         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
679         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
680         curl_easy_setopt(curl, CURLOPT_WRITEDATA, xp);
681         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, rss_libcurl_callback);
682         curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
683         curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
684 #ifdef CURLOPT_HTTP_CONTENT_DECODING
685         curl_easy_setopt(curl, CURLOPT_HTTP_CONTENT_DECODING, 1);
686         curl_easy_setopt(curl, CURLOPT_ENCODING, "");
687 #endif
688         curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
689         curl_easy_setopt(curl, CURLOPT_TIMEOUT, 180);           /* die after 180 seconds */
690         if (!IsEmptyStr(config.c_ip_addr)) {
691                 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
692         }
693
694         memset(&ri, 0, sizeof(rss_item));
695         ri.roomlist = Cfg->rooms;
696 #ifdef HAVE_ICONV
697 #if 0
698         XML_SetUnknownEncodingHandler(xp,
699                                       handle_unknown_xml_encoding,
700                                       NULL);
701 #endif
702 #endif
703         XML_SetElementHandler(xp, rss_xml_start, rss_xml_end);
704         XML_SetCharacterDataHandler(xp, rss_xml_chardata);
705         XML_SetUserData(xp, &rssc);
706         if (CtdlThreadCheckStop())
707         {
708                 XML_ParserFree(xp);
709                 curl_easy_cleanup(curl);
710                 return;
711         }
712         
713         if (CtdlThreadCheckStop())
714                 goto shutdown ;
715
716         res = curl_easy_perform(curl);
717         if (res) {
718                 CtdlLogPrintf(CTDL_ALERT, "libcurl error %d: %s\n", res, errmsg);
719         }
720
721         if (CtdlThreadCheckStop())
722                 goto shutdown ;
723
724         if (ri.done_parsing == 0)
725                 XML_Parse(xp, "", 0, 1);
726
727
728         CtdlLogPrintf(CTDL_ALERT, "RSS: XML Status [%s] \n", 
729                       XML_ErrorString(
730                               XML_GetErrorCode(xp)));
731
732 shutdown:
733         curl_easy_cleanup(curl);
734         XML_ParserFree(xp);
735
736         flush_rss_ite(&ri);
737 }
738
739
740 /*
741  * Scan a room's netconfig to determine whether it is requesting any RSS feeds
742  */
743 void rssclient_scan_room(struct ctdlroom *qrbuf, void *data)
744 {
745         char filename[PATH_MAX];
746         char buf[1024];
747         char instr[32];
748         FILE *fp;
749         char feedurl[256];
750         rssnetcfg *rncptr = NULL;
751         rssnetcfg *use_this_rncptr = NULL;
752         int len = 0;
753         char *ptr = NULL;
754
755         assoc_file_name(filename, sizeof filename, qrbuf, ctdl_netcfg_dir);
756
757         if (CtdlThreadCheckStop())
758                 return;
759                 
760         /* Only do net processing for rooms that have netconfigs */
761         fp = fopen(filename, "r");
762         if (fp == NULL) {
763                 return;
764         }
765
766         while (fgets(buf, sizeof buf, fp) != NULL && !CtdlThreadCheckStop()) {
767                 buf[strlen(buf)-1] = 0;
768
769                 extract_token(instr, buf, 0, '|', sizeof instr);
770                 if (!strcasecmp(instr, "rssclient")) {
771
772                         use_this_rncptr = NULL;
773
774                         extract_token(feedurl, buf, 1, '|', sizeof feedurl);
775
776                         /* If any other rooms have requested the same feed, then we will just add this
777                          * room to the target list for that client request.
778                          */
779                         for (rncptr=rnclist; rncptr!=NULL; rncptr=rncptr->next) {
780                                 if (!strcmp(rncptr->url, feedurl)) {
781                                         use_this_rncptr = rncptr;
782                                 }
783                         }
784
785                         /* Otherwise create a new client request */
786                         if (use_this_rncptr == NULL) {
787                                 rncptr = (rssnetcfg *) malloc(sizeof(rssnetcfg));
788                                 rncptr->ItemType = RSS_UNSET;
789                                 if (rncptr != NULL) {
790                                         rncptr->next = rnclist;
791                                         safestrncpy(rncptr->url, feedurl, sizeof rncptr->url);
792                                         rncptr->rooms = NULL;
793                                         rnclist = rncptr;
794                                         use_this_rncptr = rncptr;
795                                 }
796                         }
797
798                         /* Add the room name to the request */
799                         if (use_this_rncptr != NULL) {
800                                 if (use_this_rncptr->rooms == NULL) {
801                                         rncptr->rooms = strdup(qrbuf->QRname);
802                                 }
803                                 else {
804                                         len = strlen(use_this_rncptr->rooms) + strlen(qrbuf->QRname) + 5;
805                                         ptr = realloc(use_this_rncptr->rooms, len);
806                                         if (ptr != NULL) {
807                                                 strcat(ptr, "|");
808                                                 strcat(ptr, qrbuf->QRname);
809                                                 use_this_rncptr->rooms = ptr;
810                                         }
811                                 }
812                         }
813                 }
814
815         }
816
817         fclose(fp);
818
819 }
820
821 /*
822  * Scan for rooms that have RSS client requests configured
823  */
824 void *rssclient_scan(void *args) {
825         static time_t last_run = 0L;
826         static int doing_rssclient = 0;
827         rssnetcfg *rptr = NULL;
828         CitContext rssclientCC;
829
830         /* Give this thread its own private CitContext */
831         CtdlFillSystemContext(&rssclientCC, "rssclient");
832         citthread_setspecific(MyConKey, (void *)&rssclientCC );
833
834         CtdlThreadAllocTSD();
835
836         /*
837          * This is a simple concurrency check to make sure only one rssclient run
838          * is done at a time.  We could do this with a mutex, but since we
839          * don't really require extremely fine granularity here, we'll do it
840          * with a static variable instead.
841          */
842         if (doing_rssclient) return NULL;
843         doing_rssclient = 1;
844
845         CtdlLogPrintf(CTDL_DEBUG, "rssclient started\n");
846         CtdlForEachRoom(rssclient_scan_room, NULL);
847
848         while (rnclist != NULL && !CtdlThreadCheckStop()) {
849                 rss_do_fetching(rnclist);
850                 rptr = rnclist;
851                 rnclist = rnclist->next;
852                 if (rptr->rooms != NULL) free(rptr->rooms);
853                 free(rptr);
854         }
855
856         CtdlLogPrintf(CTDL_DEBUG, "rssclient ended\n");
857         last_run = time(NULL);
858         doing_rssclient = 0;
859         if (!CtdlThreadCheckStop())
860                 CtdlThreadSchedule ("RSS Client", CTDLTHREAD_BIGSTACK, rssclient_scan, NULL, last_run + config.c_net_freq);
861         else
862                 CtdlLogPrintf(CTDL_DEBUG, "rssclient: Task STOPPED.\n");
863         return NULL;
864 }
865
866
867 CTDL_MODULE_INIT(rssclient)
868 {
869         if (threading)
870         {
871                 CtdlLogPrintf(CTDL_INFO, "%s\n", curl_version());
872                 CtdlThreadSchedule ("RSS Client", CTDLTHREAD_BIGSTACK, rssclient_scan, NULL, 0);
873         }
874         /* return our Subversion id for the Log */
875         return "$Id$";
876 }