Memleak: when expanding shorter URLs we need to free the reply buffer.
[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
60 typedef struct rssnetcfg rssnetcfg;
61 struct rssnetcfg {
62         rssnetcfg *next;
63         char url[256];
64         char *rooms;
65         time_t last_error_when;
66         int ItemType;
67         time_t next_poll;
68 };
69
70 #define RSS_UNSET       (1<<0)
71 #define RSS_RSS         (1<<1)
72 #define RSS_ATOM        (1<<2)
73 #define RSS_REQUIRE_BUF (1<<3)
74
75 typedef struct _rss_item {
76         char *roomlist;
77         int done_parsing;
78         StrBuf *guid;
79         StrBuf *title;
80         StrBuf *link;
81         StrBuf *linkTitle;
82         StrBuf *reLink;
83         StrBuf *reLinkTitle;
84         StrBuf *description;
85         time_t pubdate;
86         StrBuf *channel_title;
87         int item_tag_nesting;
88         StrBuf *author_or_creator;
89         StrBuf *author_url;
90         StrBuf *author_email;
91 }rss_item;
92
93
94 typedef void (*rss_handler_func)(StrBuf *CData, 
95                                  rss_item *ri, 
96                                  rssnetcfg *Cfg, 
97                                  const char** Attr);
98
99 typedef struct __rss_xml_handler {
100         int Flags;
101         rss_handler_func Handler;
102 }rss_xml_handler;
103
104
105 typedef struct _rsscollection {
106         StrBuf *CData;
107         StrBuf *Key;
108
109         rss_item *Item;
110         rssnetcfg *Cfg;
111         
112         rss_xml_handler *Current;
113 } rsscollection;
114
115 struct rssnetcfg *rnclist = NULL;
116 HashList *StartHandlers = NULL;
117 HashList *EndHandlers = NULL;
118 HashList *KnownNameSpaces = NULL;
119 HashList *UrlShorteners = NULL;
120 void AddRSSStartHandler(rss_handler_func Handler, int Flags, const char *key, long len)
121 {
122         rss_xml_handler *h;
123         h = (rss_xml_handler*) malloc(sizeof (rss_xml_handler));
124         h->Flags = Flags;
125         h->Handler = Handler;
126         Put(StartHandlers, key, len, h, NULL);
127 }
128 void AddRSSEndHandler(rss_handler_func Handler, int Flags, const char *key, long len)
129 {
130         rss_xml_handler *h;
131         h = (rss_xml_handler*) malloc(sizeof (rss_xml_handler));
132         h->Flags = Flags;
133         h->Handler = Handler;
134         Put(EndHandlers, key, len, h, NULL);
135 }
136
137 #if 0
138 //#ifdef HAVE_ICONV
139 #include <iconv.h>
140
141
142 /* 
143  * dug this out of the trashcan of the midgard project, lets see if it works for us.
144  * original code by Alexander Bokovoy <bokovoy@avilink.ne> distributed under GPL V2 or later
145  */
146
147 /* Returns: 
148  >= 0 - successfull, 0 means conversion doesn't use multibyte sequences 
149    -1 - error during iconv_open call 
150    -2 - error during iconv_close call 
151    ---------------------------------- 
152    This function expects that multibyte encoding in 'charset' wouldn't have 
153    characters with more than 3 bytes. It is not intended to convert UTF-8 because 
154    we'll never receive UTF-8 in our handler (it is handled by Exat itself). 
155 */ 
156 static int 
157 fill_encoding_info (const char *charset, XML_Encoding * info) 
158
159   iconv_t cd = (iconv_t)(-1); 
160   int flag; 
161         syslog(LOG_EMERG, "RSS: fill encoding info ...\n");
162  
163 #if G_BYTE_ORDER == G_LITTLE_ENDIAN 
164   cd = iconv_open ("UCS-2LE", charset); 
165 #else 
166   cd = iconv_open ("UCS-2BE", charset); 
167 #endif 
168  
169   if (cd == (iconv_t) (-1)) 
170     { 
171       return -1; 
172     } 
173  
174   { 
175     unsigned short out = 0; 
176     unsigned char buf[4]; 
177     unsigned int i0, i1, i2; 
178     int result = 0; 
179     flag = 0; 
180     for (i0 = 0; i0 < 0x100; i0++) 
181       { 
182         buf[0] = i0; 
183         info->map[i0] = 0; 
184         //result = try (cd, buf, 1, &out); 
185         if (result < 0) 
186           { 
187           } 
188         else if (result > 0) 
189           { 
190             info->map[i0] = out; 
191           } 
192         else 
193           { 
194             for (i1 = 0; i1 < 0x100; i1++) 
195               { 
196                 buf[1] = i1; 
197                 ///result = try (cd, buf, 2, &out); 
198                 if (result < 0) 
199                   { 
200                   } 
201                 else if (result > 0) 
202                   { 
203                     flag++; 
204                     info->map[i0] = -2; 
205                   } 
206                 else 
207                   { 
208                     for (i2 = 0; i2 < 0x100; i2++) 
209                       { 
210                         buf[2] = i2; 
211                         ////result = try (cd, buf, 3, &out); 
212                         if (result < 0) 
213                           { 
214                           } 
215                         else if (result > 0) 
216                           { 
217                             flag++; 
218                             info->map[i0] = -3; 
219                           } 
220                       } 
221                   } 
222               } 
223           } 
224       } 
225   } 
226  
227   if (iconv_close (cd) < 0) 
228     { 
229       return -2; 
230     } 
231   return flag; 
232
233
234 static int 
235 iconv_convertor (void *data, const char *s) 
236
237   XML_Encoding *info = data; 
238   int res; 
239         syslog(LOG_EMERG, "RSS: Converting ...\n");
240
241   if (s == NULL) 
242     return -1; 
243 /*
244   GByteArray *result; 
245   result = g_byte_array_new (); 
246   if (process_block (info->data, (char *) s, strlen (s), result) == 0) 
247     { 
248       res = *(result->data); 
249       g_byte_array_free (result, TRUE); 
250       return res; 
251     } 
252   g_byte_array_free (result, TRUE); 
253 */
254   return -1; 
255
256
257 static void 
258 my_release (void *data) 
259
260   iconv_t cd = (iconv_t) data; 
261   if (iconv_close (cd) != 0) 
262     { 
263 /// TODO: uh no.      exit (1); 
264     } 
265
266 int 
267 handle_unknown_xml_encoding (void *encodingHandleData, 
268                              const XML_Char * name, 
269                              XML_Encoding * info) 
270
271   int result; 
272   syslog(LOG_EMERG, "RSS: unknown encoding ...\n");
273   result = fill_encoding_info (name, info); 
274   if (result >= 0) 
275     { 
276       /*  
277         Special case: client asked for reverse conversion, we'll provide him with 
278         iconv descriptor which handles it. Client should release it by himself. 
279       */ 
280       if(encodingHandleData != NULL) 
281             *((iconv_t *)encodingHandleData) = iconv_open(name, "UTF-8"); 
282       /*  
283          Optimization: we do not need conversion function if encoding is one-to-one,  
284          info->map table will be enough  
285        */ 
286       if (result == 0) 
287         { 
288           info->data = NULL; 
289           info->convert = NULL; 
290           info->release = NULL; 
291           return 1; 
292         } 
293       /*  
294          We do need conversion function because this encoding uses multibyte sequences 
295        */ 
296       info->data = (void *) iconv_open ("UTF-8", name); 
297       if ((int)info->data == -1) 
298         return -1; 
299       info->convert = iconv_convertor; 
300       info->release = my_release; 
301       return 1; 
302     } 
303   if(encodingHandleData != NULL)  
304     *(iconv_t *)encodingHandleData = NULL; 
305   return 0; 
306
307
308 ///#endif
309 #endif
310 size_t GetLocationString( void *ptr, size_t size, size_t nmemb, void *userdata)
311 {
312 #define LOCATION "location"
313         if (strncasecmp((char*)ptr, LOCATION, sizeof(LOCATION) - 1) == 0)
314         {
315                 StrBuf *pURL = (StrBuf*) userdata;
316                 char *pch = (char*) ptr;
317                 char *pche;
318                 
319                 pche = pch + (size * nmemb);
320                 pch += sizeof(LOCATION);
321                 
322                 while (isspace(*pch) || (*pch == ':'))
323                         pch ++;
324
325                 while (isspace(*pche) || (*pche == '\0'))
326                         pche--;
327                 
328                 FlushStrBuf(pURL);
329                 StrBufPlain(pURL, pch, pche - pch + 1); 
330         }
331         return size * nmemb;
332 }
333
334 int LookupUrl(StrBuf *ShorterUrlStr)
335 {
336         CURL *curl;
337         char errmsg[1024] = "";
338         StrBuf *Answer;
339         int rc = 0;
340
341         curl = curl_easy_init();
342         if (!curl) {
343                 syslog(LOG_ALERT, "Unable to initialize libcurl.\n");
344                 return 0;
345         }
346         Answer = NewStrBufPlain(NULL, SIZ);
347
348         curl_easy_setopt(curl, CURLOPT_URL, ChrPtr(ShorterUrlStr));
349         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
350         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
351         curl_easy_setopt(curl, CURLOPT_WRITEDATA, Answer);
352 //      curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, rss_libcurl_callback);
353         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlFillStrBuf_callback);
354         curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
355         curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
356 #ifdef CURLOPT_HTTP_CONTENT_DECODING
357         curl_easy_setopt(curl, CURLOPT_HTTP_CONTENT_DECODING, 1);
358         curl_easy_setopt(curl, CURLOPT_ENCODING, "");
359 #endif
360         curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
361         curl_easy_setopt(curl, CURLOPT_TIMEOUT, 180);           /* die after 180 seconds */
362         curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 0);
363
364         curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION , GetLocationString);
365         curl_easy_setopt(curl, CURLOPT_WRITEHEADER, ShorterUrlStr);
366
367
368         if (
369                 (!IsEmptyStr(config.c_ip_addr))
370                 && (strcmp(config.c_ip_addr, "*"))
371                 && (strcmp(config.c_ip_addr, "::"))
372                 && (strcmp(config.c_ip_addr, "0.0.0.0"))
373         ) {
374                 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
375         }
376
377         if (server_shutting_down)
378                 goto shutdown ;
379
380         rc = curl_easy_perform(curl);
381         if (rc) {
382                 syslog(LOG_ALERT, "libcurl error %d: %s\n", rc, errmsg);
383                 rc = 0;
384         }
385         else 
386                 rc = 1;
387
388 shutdown:
389         FreeStrBuf(&Answer);
390         curl_easy_cleanup(curl);
391
392         return rc;
393
394 }
395
396
397
398 void CrawlMessageForShorterUrls(HashList *pUrls, StrBuf *Message)
399 {
400         int nHits = 0;
401         void *pv;
402         int nShorter = 0;
403         const char *pch;
404         const char *pUrl;
405         ConstStr *pCUrl;
406
407         while (GetHash(UrlShorteners, IKEY(nShorter), &pv))
408         {
409                 nShorter++;
410                 pch = ChrPtr(Message);
411                 pUrl = strstr(pch, ChrPtr((StrBuf*)pv));
412                 while ((pUrl != NULL) && (nHits < 99))
413                 {
414                         pCUrl = malloc(sizeof(ConstStr));
415
416                         pCUrl->Key = pUrl;
417                         pch = pUrl + StrLength((StrBuf*)pv);
418                         while (isalnum(*pch)||(*pch == '-')||(*pch == '/'))
419                                 pch++;
420                         pCUrl->len = pch - pCUrl->Key;
421
422                         Put(pUrls, IKEY(nHits), pCUrl, NULL);
423                         nHits ++;
424                         pUrl = strstr(pch, ChrPtr((StrBuf*)pv));
425                 }
426         }
427 }
428
429 int SortConstStrByPosition(const void *Item1, const void *Item2)
430 {
431         const ConstStr *p1, *p2;
432         p1 = (const ConstStr*) Item1;
433         p2 = (const ConstStr*) Item2;
434         if (p1->Key == p2->Key)
435                 return 0;
436         if (p1->Key > p2->Key)
437                 return 1;
438         return -1;
439 }
440
441 void ExpandShortUrls(StrBuf *Message)
442 {
443         StrBuf *Shadow;
444         HashList *pUrls;
445         ConstStr *pCUrl;
446         const char *pch;
447         const char *pche;
448
449         /* we just suspect URL shorteners to be inside of feeds from twitter
450          * or other short content messages, so don't crawl through real blogs.
451          */
452         if (StrLength(Message) > 500)
453                 return;
454
455         pUrls = NewHash(1, Flathash);
456         CrawlMessageForShorterUrls(pUrls, Message);
457
458         if (GetCount(pUrls) > 0)
459         {
460                 StrBuf *ShorterUrlStr;
461                 HashPos *Pos;
462                 const char *RetrKey;
463                 void *pv;
464                 long len;
465
466                 Shadow = NewStrBufPlain(NULL, StrLength(Message));
467                 SortByPayload (pUrls, SortConstStrByPosition);
468
469                 ShorterUrlStr = NewStrBufPlain(NULL, StrLength(Message));
470
471                 pch = ChrPtr(Message);
472                 pche = pch + StrLength(Message);
473                 Pos = GetNewHashPos(pUrls, 1);
474                 while (GetNextHashPos(pUrls, Pos, &len, &RetrKey, &pv))
475                 {
476                         pCUrl = (ConstStr*) pv;
477
478                         if (pch != pCUrl->Key)
479                                 StrBufAppendBufPlain(Shadow, pch, pCUrl->Key - pch, 0);
480                         
481                         StrBufPlain(ShorterUrlStr, CKEY(*pCUrl));
482                         if (LookupUrl(ShorterUrlStr))
483                         {
484                                 StrBufAppendBufPlain(Shadow, HKEY("<a href=\""), 0);
485                                 StrBufAppendBuf(Shadow, ShorterUrlStr, 0);
486                                 StrBufAppendBufPlain(Shadow, HKEY("\">"), 0);
487                                 StrBufAppendBuf(Shadow, ShorterUrlStr, 0);
488                                 StrBufAppendBufPlain(Shadow, HKEY("["), 0);
489                                 StrBufAppendBufPlain(Shadow, pCUrl->Key, pCUrl->len, 0);
490                                 StrBufAppendBufPlain(Shadow, HKEY("]</a>"), 0);
491                         }
492                         else
493                         {
494                                 StrBufAppendBufPlain(Shadow, HKEY("<a href=\""), 0);
495                                 StrBufAppendBufPlain(Shadow, pCUrl->Key, pCUrl->len, 0);
496                                 StrBufAppendBufPlain(Shadow, HKEY("\">"), 0);
497                                 StrBufAppendBufPlain(Shadow, pCUrl->Key, pCUrl->len, 0);
498                                 StrBufAppendBufPlain(Shadow, HKEY("</a>"), 0);
499                         }
500                         pch = pCUrl->Key + pCUrl->len + 1;
501
502                 }
503                 if (pch < pche)
504                         StrBufAppendBufPlain(Shadow, pch, pche - pch, 0);
505                 FlushStrBuf(Message);
506                 StrBufAppendBuf(Message, Shadow, 0);
507
508                 FreeStrBuf(&ShorterUrlStr);
509                 FreeStrBuf(&Shadow);
510                 DeleteHashPos(&Pos);
511         }
512
513         DeleteHash(&pUrls);
514 }
515
516
517 void AppendLink(StrBuf *Message, StrBuf *link, StrBuf *LinkTitle, const char *Title)
518 {
519         if (StrLength(link) > 0)
520         {
521                 StrBufAppendBufPlain(Message, HKEY("<a href=\""), 0);
522                 StrBufAppendBuf(Message, link, 0);
523                 StrBufAppendBufPlain(Message, HKEY("\">"), 0);
524                 if (StrLength(LinkTitle) > 0)
525                         StrBufAppendBuf(Message, LinkTitle, 0);
526                 else if ((Title != NULL) && !IsEmptyStr(Title))
527                         StrBufAppendBufPlain(Message, Title, -1, 0);
528                 else
529                         StrBufAppendBuf(Message, link, 0);
530                 StrBufAppendBufPlain(Message, HKEY("</a><br>\n"), 0);
531         }
532 }
533 /*
534  * Commit a fetched and parsed RSS item to disk
535  */
536 void rss_save_item(rss_item *ri)
537 {
538
539         struct MD5Context md5context;
540         u_char rawdigest[MD5_DIGEST_LEN];
541         int i;
542         char utmsgid[SIZ];
543         struct cdbdata *cdbut;
544         struct UseTable ut;
545         struct CtdlMessage *msg;
546         struct recptypes *recp = NULL;
547         int msglen = 0;
548         StrBuf *Message;
549
550         recp = (struct recptypes *) malloc(sizeof(struct recptypes));
551         if (recp == NULL) return;
552         memset(recp, 0, sizeof(struct recptypes));
553         memset(&ut, 0, sizeof(struct UseTable));
554         recp->recp_room = strdup(ri->roomlist);
555         recp->num_room = num_tokens(ri->roomlist, '|');
556         recp->recptypes_magic = RECPTYPES_MAGIC;
557    
558         /* Construct a GUID to use in the S_USETABLE table.
559          * If one is not present in the item itself, make one up.
560          */
561         if (ri->guid != NULL) {
562                 StrBufSpaceToBlank(ri->guid);
563                 StrBufTrim(ri->guid);
564                 snprintf(utmsgid, sizeof utmsgid, "rss/%s", ChrPtr(ri->guid));
565         }
566         else {
567                 MD5Init(&md5context);
568                 if (ri->title != NULL) {
569                         MD5Update(&md5context, (const unsigned char*)ChrPtr(ri->title), StrLength(ri->title));
570                 }
571                 if (ri->link != NULL) {
572                         MD5Update(&md5context, (const unsigned char*)ChrPtr(ri->link), StrLength(ri->link));
573                 }
574                 MD5Final(rawdigest, &md5context);
575                 for (i=0; i<MD5_DIGEST_LEN; i++) {
576                         sprintf(&utmsgid[i*2], "%02X", (unsigned char) (rawdigest[i] & 0xff));
577                         utmsgid[i*2] = tolower(utmsgid[i*2]);
578                         utmsgid[(i*2)+1] = tolower(utmsgid[(i*2)+1]);
579                 }
580                 strcat(utmsgid, "_rss2ctdl");
581         }
582
583         /* Find out if we've already seen this item */
584
585         cdbut = cdb_fetch(CDB_USETABLE, utmsgid, strlen(utmsgid));
586 #ifndef DEBUG_RSS
587         if (cdbut != NULL) {
588                 /* Item has already been seen */
589                 syslog(LOG_DEBUG, "%s has already been seen\n", utmsgid);
590                 cdb_free(cdbut);
591
592                 /* rewrite the record anyway, to update the timestamp */
593                 strcpy(ut.ut_msgid, utmsgid);
594                 ut.ut_timestamp = time(NULL);
595                 cdb_store(CDB_USETABLE, utmsgid, strlen(utmsgid), &ut, sizeof(struct UseTable) );
596         }
597         else
598 #endif
599 {
600                 /* Item has not been seen, so save it. */
601                 syslog(LOG_DEBUG, "RSS: saving item...\n");
602                 if (ri->description == NULL) ri->description = NewStrBufPlain(HKEY(""));
603                 StrBufSpaceToBlank(ri->description);
604                 msg = malloc(sizeof(struct CtdlMessage));
605                 memset(msg, 0, sizeof(struct CtdlMessage));
606                 msg->cm_magic = CTDLMESSAGE_MAGIC;
607                 msg->cm_anon_type = MES_NORMAL;
608                 msg->cm_format_type = FMT_RFC822;
609
610                 if (ri->guid != NULL) {
611                         msg->cm_fields['E'] = strdup(ChrPtr(ri->guid));
612                 }
613
614                 if (ri->author_or_creator != NULL) {
615                         char *From;
616                         StrBuf *Encoded = NULL;
617                         int FromAt;
618                         
619                         From = html_to_ascii(ChrPtr(ri->author_or_creator),
620                                              StrLength(ri->author_or_creator), 
621                                              512, 0);
622                         StrBufPlain(ri->author_or_creator, From, -1);
623                         StrBufTrim(ri->author_or_creator);
624                         free(From);
625
626                         FromAt = strchr(ChrPtr(ri->author_or_creator), '@') != NULL;
627                         if (!FromAt && StrLength (ri->author_email) > 0)
628                         {
629                                 StrBufRFC2047encode(&Encoded, ri->author_or_creator);
630                                 msg->cm_fields['A'] = SmashStrBuf(&Encoded);
631                                 msg->cm_fields['P'] = SmashStrBuf(&ri->author_email);
632                         }
633                         else
634                         {
635                                 if (FromAt)
636                                 {
637                                         msg->cm_fields['A'] = SmashStrBuf(&ri->author_or_creator);
638                                         msg->cm_fields['P'] = strdup(msg->cm_fields['A']);
639                                 }
640                                 else 
641                                 {
642                                         StrBufRFC2047encode(&Encoded, ri->author_or_creator);
643                                         msg->cm_fields['A'] = SmashStrBuf(&Encoded);
644                                         msg->cm_fields['P'] = strdup("rss@localhost");
645                                 }
646                         }
647                 }
648                 else {
649                         msg->cm_fields['A'] = strdup("rss");
650                 }
651
652                 msg->cm_fields['N'] = strdup(NODENAME);
653                 if (ri->title != NULL) {
654                         long len;
655                         char *Sbj;
656                         StrBuf *Encoded, *QPEncoded;
657
658                         QPEncoded = NULL;
659                         StrBufSpaceToBlank(ri->title);
660                         len = StrLength(ri->title);
661                         Sbj = html_to_ascii(ChrPtr(ri->title), len, 512, 0);
662                         len = strlen(Sbj);
663                         if (Sbj[len - 1] == '\n')
664                         {
665                                 len --;
666                                 Sbj[len] = '\0';
667                         }
668                         Encoded = NewStrBufPlain(Sbj, len);
669                         free(Sbj);
670
671                         StrBufTrim(Encoded);
672                         StrBufRFC2047encode(&QPEncoded, Encoded);
673
674                         msg->cm_fields['U'] = SmashStrBuf(&QPEncoded);
675                         FreeStrBuf(&Encoded);
676                 }
677
678                 if (ri->pubdate <= 0) {
679                         ri->pubdate = time(NULL);
680                 }
681                 msg->cm_fields['T'] = malloc(64);
682                 snprintf(msg->cm_fields['T'], 64, "%ld", ri->pubdate);
683
684                 if (ri->channel_title != NULL) {
685                         if (StrLength(ri->channel_title) > 0) {
686                                 msg->cm_fields['O'] = strdup(ChrPtr(ri->channel_title));
687                         }
688                 }
689                 if (ri->link == NULL) 
690                         ri->link = NewStrBufPlain(HKEY(""));
691                 ExpandShortUrls(ri->description);
692                 msglen += 1024 + StrLength(ri->link) + StrLength(ri->description) ;
693
694                 Message = NewStrBufPlain(NULL, StrLength(ri->description));
695
696                 StrBufPlain(Message, HKEY(
697                          "Content-type: text/html; charset=\"UTF-8\"\r\n\r\n"
698                          "<html><body>\n"));
699
700                 StrBufAppendBuf(Message, ri->description, 0);
701                 StrBufAppendBufPlain(Message, HKEY("<br><br>\n"), 0);
702
703                 AppendLink(Message, ri->link, ri->linkTitle, NULL);
704                 AppendLink(Message, ri->reLink, ri->reLinkTitle, "Reply to this");
705                 StrBufAppendBufPlain(Message, HKEY("</body></html>\n"), 0);
706
707                 msg->cm_fields['M'] = SmashStrBuf(&Message);
708
709                 CtdlSubmitMsg(msg, recp, NULL, 0);
710                 CtdlFreeMessage(msg);
711
712                 /* write the uidl to the use table so we don't store this item again */
713                 strcpy(ut.ut_msgid, utmsgid);
714                 ut.ut_timestamp = time(NULL);
715                 cdb_store(CDB_USETABLE, utmsgid, strlen(utmsgid), &ut, sizeof(struct UseTable) );
716         }
717         free_recipients(recp);
718 }
719
720
721
722 /*
723  * Convert an RDF/RSS datestamp into a time_t
724  */
725 time_t rdf_parsedate(const char *p)
726 {
727         struct tm tm;
728         time_t t = 0;
729
730         if (!p) return 0L;
731         if (strlen(p) < 10) return 0L;
732
733         memset(&tm, 0, sizeof tm);
734
735         /*
736          * If the timestamp appears to be in W3C datetime format, try to
737          * parse it.  See also: http://www.w3.org/TR/NOTE-datetime
738          *
739          * This code, along with parsedate.c, is a potential candidate for
740          * moving into libcitadel.
741          */
742         if ( (p[4] == '-') && (p[7] == '-') ) {
743                 tm.tm_year = atoi(&p[0]) - 1900;
744                 tm.tm_mon = atoi(&p[5]) - 1;
745                 tm.tm_mday = atoi(&p[8]);
746                 if ( (p[10] == 'T') && (p[13] == ':') ) {
747                         tm.tm_hour = atoi(&p[11]);
748                         tm.tm_min = atoi(&p[14]);
749                 }
750                 return mktime(&tm);
751         }
752
753         /* hmm... try RFC822 date stamp format */
754
755         t = parsedate(p);
756         if (t > 0) return(t);
757
758         /* yeesh.  ok, just return the current date and time. */
759         return(time(NULL));
760 }
761
762 void flush_rss_item(rss_item *ri)
763 {
764         /* Initialize the feed item data structure */
765         FreeStrBuf(&ri->guid);
766         FreeStrBuf(&ri->title);
767         FreeStrBuf(&ri->link);
768         FreeStrBuf(&ri->linkTitle);
769         FreeStrBuf(&ri->reLink);
770         FreeStrBuf(&ri->reLinkTitle);
771         FreeStrBuf(&ri->description);
772         FreeStrBuf(&ri->channel_title);
773         FreeStrBuf(&ri->author_or_creator);
774         FreeStrBuf(&ri->author_url);
775         FreeStrBuf(&ri->author_email);
776 }
777
778 void rss_xml_start(void *data, const char *supplied_el, const char **attr)
779 {
780         rss_xml_handler *h;
781         rsscollection   *rssc = (rsscollection*) data;
782         rssnetcfg       *Cfg = rssc->Cfg;
783         rss_item        *ri = rssc->Item;
784         void            *pv;
785         const char      *pel;
786         char            *sep = NULL;
787
788         /* Axe the namespace, we don't care about it */
789 ///     syslog(LOG_EMERG, "RSS: supplied el %d: %s...\n", rssc->Cfg->ItemType, supplied_el);
790         pel = supplied_el;
791         while (sep = strchr(pel, ':'), sep) {
792                 pel = sep + 1;
793         }
794
795         if (pel != supplied_el)
796         {
797                 void *v;
798                 
799                 if (!GetHash(KnownNameSpaces, 
800                              supplied_el, 
801                              pel - supplied_el - 1,
802                              &v))
803                 {
804 #ifdef DEBUG_RSS
805                         syslog(LOG_EMERG, "RSS: START ignoring because of wrong namespace [%s] = [%s]\n", 
806                                       supplied_el);
807 #endif
808                         return;
809                 }
810         }
811
812         StrBufPlain(rssc->Key, pel, -1);
813         StrBufLowerCase(rssc->Key);
814         if (GetHash(StartHandlers, SKEY(rssc->Key), &pv))
815         {
816                 rssc->Current = h = (rss_xml_handler*) pv;
817
818                 if (((h->Flags & RSS_UNSET) != 0) && 
819                     (Cfg->ItemType == RSS_UNSET))
820                 {
821                         h->Handler(rssc->CData, ri, Cfg, attr);
822                 }
823                 else if (((h->Flags & RSS_RSS) != 0) &&
824                     (Cfg->ItemType == RSS_RSS))
825                 {
826                         h->Handler(rssc->CData, ri, Cfg, attr);
827                 }
828                 else if (((h->Flags & RSS_ATOM) != 0) &&
829                          (Cfg->ItemType == RSS_ATOM))
830                 {
831                         h->Handler(rssc->CData, ri, Cfg, attr);                 
832                 }
833 #ifdef DEBUG_RSS
834                 else 
835                         syslog(LOG_EMERG, "RSS: START unhandled: [%s] [%s]...\n", pel, supplied_el);
836 #endif
837         }
838 #ifdef DEBUG_RSS
839         else 
840                 syslog(LOG_EMERG, "RSS: START unhandled: [%s] [%s]...\n", pel,  supplied_el);
841 #endif
842 }
843
844 void rss_xml_end(void *data, const char *supplied_el)
845 {
846         rss_xml_handler *h;
847         rsscollection   *rssc = (rsscollection*) data;
848         rssnetcfg       *Cfg = rssc->Cfg;
849         rss_item        *ri = rssc->Item;
850         const char      *pel;
851         char            *sep = NULL;
852         void            *pv;
853
854         /* Axe the namespace, we don't care about it */
855         pel = supplied_el;
856         while (sep = strchr(pel, ':'), sep) {
857                 pel = sep + 1;
858         }
859 //      syslog(LOG_EMERG, "RSS: END %s...\n", el);
860         if (pel != supplied_el)
861         {
862                 void *v;
863                 
864                 if (!GetHash(KnownNameSpaces, 
865                              supplied_el, 
866                              pel - supplied_el - 1,
867                              &v))
868                 {
869 #ifdef DEBUG_RSS
870                         syslog(LOG_EMERG, "RSS: END ignoring because of wrong namespace [%s] = [%s]\n", 
871                                       supplied_el, ChrPtr(rssc->CData));
872 #endif
873                         FlushStrBuf(rssc->CData);
874                         return;
875                 }
876         }
877
878         StrBufPlain(rssc->Key, pel, -1);
879         StrBufLowerCase(rssc->Key);
880         if (GetHash(EndHandlers, SKEY(rssc->Key), &pv))
881         {
882                 h = (rss_xml_handler*) pv;
883
884                 if (((h->Flags & RSS_UNSET) != 0) && 
885                     (Cfg->ItemType == RSS_UNSET))
886                 {
887                         h->Handler(rssc->CData, ri, Cfg, NULL);
888                 }
889                 else if (((h->Flags & RSS_RSS) != 0) &&
890                     (Cfg->ItemType == RSS_RSS))
891                 {
892                         h->Handler(rssc->CData, ri, Cfg, NULL);
893                 }
894                 else if (((h->Flags & RSS_ATOM) != 0) &&
895                          (Cfg->ItemType == RSS_ATOM))
896                 {
897                         h->Handler(rssc->CData, ri, Cfg, NULL);
898                 }
899 #ifdef DEBUG_RSS
900                 else 
901                         syslog(LOG_EMERG, "RSS: END   unhandled: [%s]  [%s] = [%s]...\n", pel, supplied_el, ChrPtr(rssc->CData));
902 #endif
903         }
904 #ifdef DEBUG_RSS
905         else 
906                 syslog(LOG_EMERG, "RSS: END   unhandled: [%s]  [%s] = [%s]...\n", pel, supplied_el, ChrPtr(rssc->CData));
907 #endif
908         FlushStrBuf(rssc->CData);
909         rssc->Current = NULL;
910 }
911
912
913
914
915
916 void RSS_item_rss_start (StrBuf *CData, rss_item *ri, rssnetcfg *Cfg, const char** Attr)
917 {
918         syslog(LOG_DEBUG, "RSS: This is an RSS feed.\n");
919         Cfg->ItemType = RSS_RSS;
920 }
921
922 void RSS_item_rdf_start(StrBuf *CData, rss_item *ri, rssnetcfg *Cfg, const char** Attr)
923 {
924         syslog(LOG_DEBUG, "RSS: This is an RDF feed.\n");
925         Cfg->ItemType = RSS_RSS;
926 }
927
928 void ATOM_item_feed_start(StrBuf *CData, rss_item *ri, rssnetcfg *Cfg, const char** Attr)
929 {
930         syslog(LOG_DEBUG, "RSS: This is an ATOM feed.\n");
931         Cfg->ItemType = RSS_ATOM;
932 }
933
934
935 void RSS_item_item_start(StrBuf *CData, rss_item *ri, rssnetcfg *Cfg, const char** Attr)
936 {
937         ri->item_tag_nesting ++;
938         flush_rss_item(ri);
939 }
940
941 void ATOM_item_entry_start(StrBuf *CData, rss_item *ri, rssnetcfg *Cfg, const char** Attr)
942 {
943 /* Atom feed... */
944         ri->item_tag_nesting ++;
945         flush_rss_item(ri);
946 }
947
948 void ATOM_item_link_start (StrBuf *CData, rss_item *ri, rssnetcfg *Cfg, const char** Attr)
949 {
950         int i;
951         const char *pHref = NULL;
952         const char *pType = NULL;
953         const char *pRel = NULL;
954         const char *pTitle = NULL;
955
956         for (i = 0; Attr[i] != NULL; i+=2)
957         {
958                 if (!strcmp(Attr[i], "href"))
959                 {
960                         pHref = Attr[i+1];
961                 }
962                 else if (!strcmp(Attr[i], "rel"))
963                 {
964                         pRel = Attr[i+1];
965                 }
966                 else if (!strcmp(Attr[i], "type"))
967                 {
968                         pType = Attr[i+1];
969                 }
970                 else if (!strcmp(Attr[i], "title"))
971                 {
972                         pTitle = Attr[i+1];
973                 }
974         }
975         if (pHref == NULL)
976                 return; /* WHUT? Pointing... where? */
977         if ((pType != NULL) && !strcasecmp(pType, "application/atom+xml"))
978                 return; /* these just point to other rss resources, we're not interested in them. */
979         if (pRel != NULL)
980         {
981                 if (!strcasecmp (pRel, "replies"))
982                 {
983                         NewStrBufDupAppendFlush(&ri->reLink, NULL, pHref, -1);
984                         StrBufTrim(ri->link);
985                         NewStrBufDupAppendFlush(&ri->reLinkTitle, NULL, pTitle, -1);
986                 }
987                 else if (!strcasecmp(pRel, "alternate")) /* Alternative representation of this Item... */
988                 {
989                         NewStrBufDupAppendFlush(&ri->link, NULL, pHref, -1);
990                         StrBufTrim(ri->link);
991                         NewStrBufDupAppendFlush(&ri->linkTitle, NULL, pTitle, -1);
992
993                 }
994 #if 0 /* these are also defined, but dunno what to do with them.. */
995                 else if (!strcasecmp(pRel, "related"))
996                 {
997                 }
998                 else if (!strcasecmp(pRel, "self"))
999                 {
1000                 }
1001                 else if (!strcasecmp(pRel, "enclosure"))
1002                 {/* this reference can get big, and is probably the full article... */
1003                 }
1004                 else if (!strcasecmp(pRel, "via"))
1005                 {/* this article was provided via... */
1006                 }
1007 #endif
1008         }
1009         else if (StrLength(ri->link) == 0)
1010         {
1011                 NewStrBufDupAppendFlush(&ri->link, NULL, pHref, -1);
1012                 StrBufTrim(ri->link);
1013                 NewStrBufDupAppendFlush(&ri->linkTitle, NULL, pTitle, -1);
1014         }
1015 }
1016
1017
1018
1019
1020 void ATOMRSS_item_title_end(StrBuf *CData, rss_item *ri, rssnetcfg *Cfg, const char** Attr)
1021 {
1022         if ((ri->item_tag_nesting == 0) && (StrLength(CData) > 0)) {
1023                 NewStrBufDupAppendFlush(&ri->channel_title, CData, NULL, 0);
1024                 StrBufTrim(ri->channel_title);
1025         }
1026 }
1027
1028 void RSS_item_guid_end(StrBuf *CData, rss_item *ri, rssnetcfg *Cfg, const char** Attr)
1029 {
1030         if (StrLength(CData) > 0) {
1031                 NewStrBufDupAppendFlush(&ri->guid, CData, NULL, 0);
1032         }
1033 }
1034
1035 void ATOM_item_id_end(StrBuf *CData, rss_item *ri, rssnetcfg *Cfg, const char** Attr)
1036 {
1037         if (StrLength(CData) > 0) {
1038                 NewStrBufDupAppendFlush(&ri->guid, CData, NULL, 0);
1039         }
1040 }
1041
1042
1043 void RSS_item_link_end (StrBuf *CData, rss_item *ri, rssnetcfg *Cfg, const char** Attr)
1044 {
1045         if (StrLength(CData) > 0) {
1046                 NewStrBufDupAppendFlush(&ri->link, CData, NULL, 0);
1047                 StrBufTrim(ri->link);
1048         }
1049 }
1050 void RSS_item_relink_end(StrBuf *CData, rss_item *ri, rssnetcfg *Cfg, const char** Attr)
1051 {
1052         if (StrLength(CData) > 0) {
1053                 NewStrBufDupAppendFlush(&ri->reLink, CData, NULL, 0);
1054                 StrBufTrim(ri->reLink);
1055         }
1056 }
1057
1058 void RSSATOM_item_title_end (StrBuf *CData, rss_item *ri, rssnetcfg *Cfg, const char** Attr)
1059 {
1060         if (StrLength(CData) > 0) {
1061                 NewStrBufDupAppendFlush(&ri->title, CData, NULL, 0);
1062                 StrBufTrim(ri->title);
1063         }
1064 }
1065
1066 void ATOM_item_content_end (StrBuf *CData, rss_item *ri, rssnetcfg *Cfg, const char** Attr)
1067 {
1068         long olen = StrLength (ri->description);
1069         long clen = StrLength (CData);
1070         if (clen > 0) 
1071         {
1072                 if (olen == 0) {
1073                         NewStrBufDupAppendFlush(&ri->description, CData, NULL, 0);
1074                         StrBufTrim(ri->description);
1075                 }
1076                 else if (olen < clen) {
1077                         FlushStrBuf(ri->description);
1078                         NewStrBufDupAppendFlush(&ri->description, CData, NULL, 0);
1079                         StrBufTrim(ri->description);
1080                 }
1081         }
1082 }
1083 void ATOM_item_summary_end (StrBuf *CData, rss_item *ri, rssnetcfg *Cfg, const char** Attr)
1084 {
1085         /* this can contain an abstract of the article. but we don't want to verwrite a full document if we already have it. */
1086         if ((StrLength(CData) > 0) && (StrLength(ri->description) == 0))
1087         {
1088                 NewStrBufDupAppendFlush(&ri->description, CData, NULL, 0);
1089                 StrBufTrim(ri->description);
1090         }
1091 }
1092
1093 void RSS_item_description_end (StrBuf *CData, rss_item *ri, rssnetcfg *Cfg, const char** Attr)
1094 {
1095         long olen = StrLength (ri->description);
1096         long clen = StrLength (CData);
1097         if (clen > 0) 
1098         {
1099                 if (olen == 0) {
1100                         NewStrBufDupAppendFlush(&ri->description, CData, NULL, 0);
1101                         StrBufTrim(ri->description);
1102                 }
1103                 else if (olen < clen) {
1104                         FlushStrBuf(ri->description);
1105                         NewStrBufDupAppendFlush(&ri->description, CData, NULL, 0);
1106                         StrBufTrim(ri->description);
1107                 }
1108         }
1109 }
1110
1111 void ATOM_item_published_end (StrBuf *CData, rss_item *ri, rssnetcfg *Cfg, const char** Attr)
1112 {                 
1113         if (StrLength(CData) > 0) {
1114                 StrBufTrim(CData);
1115                 ri->pubdate = rdf_parsedate(ChrPtr(CData));
1116         }
1117 }
1118
1119 void ATOM_item_updated_end (StrBuf *CData, rss_item *ri, rssnetcfg *Cfg, const char** Attr)
1120 {
1121         if (StrLength(CData) > 0) {
1122                 StrBufTrim(CData);
1123                 ri->pubdate = rdf_parsedate(ChrPtr(CData));
1124         }
1125 }
1126
1127 void RSS_item_pubdate_end (StrBuf *CData, rss_item *ri, rssnetcfg *Cfg, const char** Attr)
1128 {
1129         if (StrLength(CData) > 0) {
1130                 StrBufTrim(CData);
1131                 ri->pubdate = rdf_parsedate(ChrPtr(CData));
1132         }
1133 }
1134
1135
1136 void RSS_item_date_end (StrBuf *CData, rss_item *ri, rssnetcfg *Cfg, const char** Attr)
1137 {
1138         if (StrLength(CData) > 0) {
1139                 StrBufTrim(CData);
1140                 ri->pubdate = rdf_parsedate(ChrPtr(CData));
1141         }
1142 }
1143
1144
1145
1146 void RSS_item_author_end(StrBuf *CData, rss_item *ri, rssnetcfg *Cfg, const char** Attr)
1147 {
1148         if (StrLength(CData) > 0) {
1149                 NewStrBufDupAppendFlush(&ri->author_or_creator, CData, NULL, 0);
1150                 StrBufTrim(ri->author_or_creator);
1151         }
1152 }
1153
1154
1155 void ATOM_item_name_end(StrBuf *CData, rss_item *ri, rssnetcfg *Cfg, const char** Attr)
1156 {
1157         if (StrLength(CData) > 0) {
1158                 NewStrBufDupAppendFlush(&ri->author_or_creator, CData, NULL, 0);
1159                 StrBufTrim(ri->author_or_creator);
1160         }
1161 }
1162
1163 void ATOM_item_email_end(StrBuf *CData, rss_item *ri, rssnetcfg *Cfg, const char** Attr)
1164 {
1165         if (StrLength(CData) > 0) {
1166                 NewStrBufDupAppendFlush(&ri->author_email, CData, NULL, 0);
1167                 StrBufTrim(ri->author_email);
1168         }
1169 }
1170
1171 void RSS_item_creator_end(StrBuf *CData, rss_item *ri, rssnetcfg *Cfg, const char** Attr)
1172 {
1173         if ((StrLength(CData) > 0) && 
1174             (StrLength(ri->author_or_creator) == 0))
1175         {
1176                 NewStrBufDupAppendFlush(&ri->author_or_creator, CData, NULL, 0);
1177                 StrBufTrim(ri->author_or_creator);
1178         }
1179 }
1180
1181
1182 void ATOM_item_uri_end(StrBuf *CData, rss_item *ri, rssnetcfg *Cfg, const char** Attr)
1183 {
1184         if (StrLength(CData) > 0) {
1185                 NewStrBufDupAppendFlush(&ri->author_url, CData, NULL, 0);
1186                 StrBufTrim(ri->author_url);
1187         }
1188 }
1189
1190 void RSS_item_item_end(StrBuf *CData, rss_item *ri, rssnetcfg *Cfg, const char** Attr)
1191 {
1192         --ri->item_tag_nesting;
1193         rss_save_item(ri);
1194 }
1195
1196
1197 void ATOM_item_entry_end(StrBuf *CData, rss_item *ri, rssnetcfg *Cfg, const char** Attr)
1198 {
1199         --ri->item_tag_nesting;
1200         rss_save_item(ri);
1201 }
1202
1203 void RSS_item_rss_end(StrBuf *CData, rss_item *ri, rssnetcfg *Cfg, const char** Attr)
1204 {
1205 //              syslog(LOG_DEBUG, "End of feed detected.  Closing parser.\n");
1206         ri->done_parsing = 1;
1207         
1208 }
1209 void RSS_item_rdf_end(StrBuf *CData, rss_item *ri, rssnetcfg *Cfg, const char** Attr)
1210 {
1211 //              syslog(LOG_DEBUG, "End of feed detected.  Closing parser.\n");
1212         ri->done_parsing = 1;
1213 }
1214
1215
1216 void RSSATOM_item_ignore(StrBuf *CData, rss_item *ri, rssnetcfg *Cfg, const char** Attr)
1217 {
1218 }
1219
1220
1221
1222 /*
1223  * This callback stores up the data which appears in between tags.
1224  */
1225 void rss_xml_cdata_start(void *data) 
1226 {
1227         rsscollection *rssc = (rsscollection*) data;
1228
1229         FlushStrBuf(rssc->CData);
1230 }
1231
1232 void rss_xml_cdata_end(void *data) 
1233 {
1234 }
1235 void rss_xml_chardata(void *data, const XML_Char *s, int len) 
1236 {
1237         rsscollection *rssc = (rsscollection*) data;
1238
1239         StrBufAppendBufPlain (rssc->CData, s, len, 0);
1240 }
1241
1242 /*
1243  * Callback function for passing libcurl's output to expat for parsing
1244  */
1245 size_t rss_libcurl_callback(void *ptr, size_t size, size_t nmemb, void *stream)
1246 {
1247         XML_Parse((XML_Parser)stream, ptr, (size * nmemb), 0);
1248         return (size*nmemb);
1249 }
1250
1251
1252
1253 /*
1254  * Begin a feed parse
1255  */
1256 void rss_do_fetching(rssnetcfg *Cfg) {
1257         rsscollection rssc;
1258         rss_item ri;
1259         XML_Parser xp = NULL;
1260         StrBuf *Answer;
1261
1262         CURL *curl;
1263         CURLcode res;
1264         char errmsg[1024] = "";
1265         char *ptr;
1266         const char *at;
1267         long len;
1268
1269         time_t now;
1270
1271         now = time(NULL);
1272
1273         if ((Cfg->next_poll != 0) && (now < Cfg->next_poll))
1274                 return;
1275         memset(&ri, 0, sizeof(rss_item));
1276         rssc.Item = &ri;
1277         rssc.Cfg = Cfg;
1278
1279         syslog(LOG_DEBUG, "Fetching RSS feed <%s>\n", Cfg->url);
1280
1281         curl = curl_easy_init();
1282         if (!curl) {
1283                 syslog(LOG_ALERT, "Unable to initialize libcurl.\n");
1284                 return;
1285         }
1286         Answer = NewStrBufPlain(NULL, SIZ);
1287
1288         curl_easy_setopt(curl, CURLOPT_URL, Cfg->url);
1289         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
1290         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
1291         curl_easy_setopt(curl, CURLOPT_WRITEDATA, Answer);
1292 //      curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, rss_libcurl_callback);
1293         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlFillStrBuf_callback);
1294         curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
1295         curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
1296 #ifdef CURLOPT_HTTP_CONTENT_DECODING
1297         curl_easy_setopt(curl, CURLOPT_HTTP_CONTENT_DECODING, 1);
1298         curl_easy_setopt(curl, CURLOPT_ENCODING, "");
1299 #endif
1300         curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
1301         curl_easy_setopt(curl, CURLOPT_TIMEOUT, 180);           /* die after 180 seconds */
1302         if (
1303                 (!IsEmptyStr(config.c_ip_addr))
1304                 && (strcmp(config.c_ip_addr, "*"))
1305                 && (strcmp(config.c_ip_addr, "::"))
1306                 && (strcmp(config.c_ip_addr, "0.0.0.0"))
1307         ) {
1308                 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
1309         }
1310
1311         if (server_shutting_down)
1312         {
1313                 curl_easy_cleanup(curl);
1314                 return;
1315         }
1316         
1317         if (server_shutting_down)
1318                 goto shutdown ;
1319
1320         res = curl_easy_perform(curl);
1321         if (res) {
1322                 syslog(LOG_ALERT, "libcurl error %d: %s\n", res, errmsg);
1323         }
1324
1325         if (server_shutting_down)
1326                 goto shutdown ;
1327
1328
1329
1330
1331         memset(&ri, 0, sizeof(rss_item));
1332         ri.roomlist = Cfg->rooms;
1333         rssc.CData = NewStrBufPlain(NULL, SIZ);
1334         rssc.Key = NewStrBuf();
1335         at = NULL;
1336         StrBufSipLine(rssc.Key, Answer, &at);
1337         ptr = NULL;
1338
1339 #define encoding "encoding=\""
1340         ptr = strstr(ChrPtr(rssc.Key), encoding);
1341         if (ptr != NULL)
1342         {
1343                 char *pche;
1344
1345                 ptr += sizeof (encoding) - 1;
1346                 pche = strchr(ptr, '"');
1347                 if (pche != NULL)
1348                         StrBufCutAt(rssc.Key, -1, pche);
1349                 else 
1350                         ptr = "UTF-8";
1351         }
1352         else
1353                 ptr = "UTF-8";
1354
1355
1356         xp = XML_ParserCreateNS(ptr, ':');
1357         if (!xp) {
1358                 syslog(LOG_ALERT, "Cannot create XML parser!\n");
1359                 goto shutdown;
1360         }
1361         FlushStrBuf(rssc.Key);
1362 //#ifdef HAVE_ICONV
1363 #if 0
1364         XML_SetUnknownEncodingHandler(xp,
1365                                       handle_unknown_xml_encoding,
1366                                       &rssc);
1367 #endif
1368 //#endif
1369         XML_SetElementHandler(xp, rss_xml_start, rss_xml_end);
1370         XML_SetCharacterDataHandler(xp, rss_xml_chardata);
1371         XML_SetUserData(xp, &rssc);
1372         XML_SetCdataSectionHandler(xp,
1373                                    rss_xml_cdata_start,
1374                                    rss_xml_cdata_end);
1375
1376
1377         len = StrLength(Answer);
1378         ptr = SmashStrBuf(&Answer);
1379         XML_Parse(xp, ptr, len, 0);
1380         free (ptr);
1381         if (ri.done_parsing == 0)
1382                 XML_Parse(xp, "", 0, 1);
1383
1384
1385         syslog(LOG_ALERT, "RSS: XML Status [%s] \n", 
1386                       XML_ErrorString(
1387                               XML_GetErrorCode(xp)));
1388
1389 shutdown:
1390         FreeStrBuf(&Answer);
1391         curl_easy_cleanup(curl);
1392         XML_ParserFree(xp);
1393
1394         flush_rss_item(&ri);
1395         FreeStrBuf(&rssc.CData);
1396         FreeStrBuf(&rssc.Key);
1397
1398         Cfg->next_poll = time(NULL) + config.c_net_freq; 
1399 }
1400
1401
1402 /*
1403  * Scan a room's netconfig to determine whether it is requesting any RSS feeds
1404  */
1405 void rssclient_scan_room(struct ctdlroom *qrbuf, void *data)
1406 {
1407         char filename[PATH_MAX];
1408         char buf[1024];
1409         char instr[32];
1410         FILE *fp;
1411         char feedurl[256];
1412         rssnetcfg *rncptr = NULL;
1413         rssnetcfg *use_this_rncptr = NULL;
1414         int len = 0;
1415         char *ptr = NULL;
1416
1417         assoc_file_name(filename, sizeof filename, qrbuf, ctdl_netcfg_dir);
1418
1419         if (server_shutting_down)
1420                 return;
1421                 
1422         /* Only do net processing for rooms that have netconfigs */
1423         fp = fopen(filename, "r");
1424         if (fp == NULL) {
1425                 return;
1426         }
1427
1428         while (fgets(buf, sizeof buf, fp) != NULL && !server_shutting_down) {
1429                 buf[strlen(buf)-1] = 0;
1430
1431                 extract_token(instr, buf, 0, '|', sizeof instr);
1432                 if (!strcasecmp(instr, "rssclient")) {
1433
1434                         use_this_rncptr = NULL;
1435
1436                         extract_token(feedurl, buf, 1, '|', sizeof feedurl);
1437
1438                         /* If any other rooms have requested the same feed, then we will just add this
1439                          * room to the target list for that client request.
1440                          */
1441                         for (rncptr=rnclist; rncptr!=NULL; rncptr=rncptr->next) {
1442                                 if (!strcmp(rncptr->url, feedurl)) {
1443                                         use_this_rncptr = rncptr;
1444                                 }
1445                         }
1446
1447                         /* Otherwise create a new client request */
1448                         if (use_this_rncptr == NULL) {
1449                                 rncptr = (rssnetcfg *) malloc(sizeof(rssnetcfg));
1450                                 memset(rncptr, 0, sizeof(rssnetcfg));
1451                                 rncptr->ItemType = RSS_UNSET;
1452                                 if (rncptr != NULL) {
1453                                         rncptr->next = rnclist;
1454                                         safestrncpy(rncptr->url, feedurl, sizeof rncptr->url);
1455                                         rncptr->rooms = NULL;
1456                                         rnclist = rncptr;
1457                                         use_this_rncptr = rncptr;
1458                                 }
1459                         }
1460
1461                         /* Add the room name to the request */
1462                         if (use_this_rncptr != NULL) {
1463                                 if (use_this_rncptr->rooms == NULL) {
1464                                         rncptr->rooms = strdup(qrbuf->QRname);
1465                                 }
1466                                 else {
1467                                         len = strlen(use_this_rncptr->rooms) + strlen(qrbuf->QRname) + 5;
1468                                         ptr = realloc(use_this_rncptr->rooms, len);
1469                                         if (ptr != NULL) {
1470                                                 strcat(ptr, "|");
1471                                                 strcat(ptr, qrbuf->QRname);
1472                                                 use_this_rncptr->rooms = ptr;
1473                                         }
1474                                 }
1475                         }
1476                 }
1477
1478         }
1479
1480         fclose(fp);
1481
1482 }
1483
1484 /*
1485  * Scan for rooms that have RSS client requests configured
1486  */
1487 void rssclient_scan(void) {
1488         static time_t last_run = 0L;
1489         static int doing_rssclient = 0;
1490         rssnetcfg *rptr = NULL;
1491
1492         /* Run no more than once every 15 minutes. */
1493         if ((time(NULL) - last_run) < 900) {
1494                 return;
1495         }
1496
1497         /*
1498          * This is a simple concurrency check to make sure only one rssclient run
1499          * is done at a time.  We could do this with a mutex, but since we
1500          * don't really require extremely fine granularity here, we'll do it
1501          * with a static variable instead.
1502          */
1503         if (doing_rssclient) return;
1504         doing_rssclient = 1;
1505
1506         syslog(LOG_DEBUG, "rssclient started\n");
1507         CtdlForEachRoom(rssclient_scan_room, NULL);
1508
1509         while (rnclist != NULL && !server_shutting_down) {
1510                 rss_do_fetching(rnclist);
1511                 rptr = rnclist;
1512                 rnclist = rnclist->next;
1513                 if (rptr->rooms != NULL) free(rptr->rooms);
1514                 free(rptr);
1515         }
1516
1517         syslog(LOG_DEBUG, "rssclient ended\n");
1518         last_run = time(NULL);
1519         doing_rssclient = 0;
1520         return;
1521 }
1522
1523 void LoadUrlShorteners(void)
1524 {
1525         int i = 0;
1526         int fd;
1527         const char *POS = NULL;
1528         const char *Err = NULL;
1529         StrBuf *Content, *Line;
1530
1531
1532         UrlShorteners = NewHash(0, Flathash);
1533
1534         fd = open(file_citadel_urlshorteners, 0);
1535
1536         if (fd != 0)
1537         {
1538                 Content = NewStrBufPlain(NULL, SIZ);
1539                 Line = NewStrBuf();
1540                 while (POS != StrBufNOTNULL)
1541                 {
1542                         StrBufTCP_read_buffered_line_fast (Line, Content, &POS, &fd, 1, 1, &Err);
1543                         StrBufTrim(Line);
1544                         if ((*ChrPtr(Line) != '#') && (StrLength(Line) > 0))
1545                         {
1546                                 Put(UrlShorteners, IKEY(i), Line, HFreeStrBuf);
1547                                 i++;
1548                                 Line = NewStrBuf();
1549                         }
1550                         else
1551                                 FlushStrBuf(Line);
1552                         if (POS == NULL)
1553                                 POS = StrBufNOTNULL;
1554                 }
1555                 FreeStrBuf(&Line);
1556                 FreeStrBuf(&Content);
1557         }
1558         close(fd);
1559 }
1560
1561 void rss_cleanup(void)
1562 {
1563         DeleteHash(&StartHandlers);
1564         DeleteHash(&EndHandlers);
1565         DeleteHash(&UrlShorteners);
1566         DeleteHash(&KnownNameSpaces);
1567 }
1568
1569 CTDL_MODULE_INIT(rssclient)
1570 {
1571         if (threading)
1572         {
1573                 syslog(LOG_INFO, "%s\n", curl_version());
1574                 CtdlRegisterSessionHook(rssclient_scan, EVT_TIMER);
1575         }
1576         else 
1577         {
1578                 LoadUrlShorteners ();
1579
1580                 StartHandlers = NewHash(1, NULL);
1581                 EndHandlers = NewHash(1, NULL);
1582
1583                 AddRSSStartHandler(RSS_item_rss_start,     RSS_UNSET, HKEY("rss"));
1584                 AddRSSStartHandler(RSS_item_rdf_start,     RSS_UNSET, HKEY("rdf"));
1585                 AddRSSStartHandler(ATOM_item_feed_start,    RSS_UNSET, HKEY("feed"));
1586                 AddRSSStartHandler(RSS_item_item_start,    RSS_RSS, HKEY("item"));
1587                 AddRSSStartHandler(ATOM_item_entry_start,  RSS_ATOM, HKEY("entry"));
1588                 AddRSSStartHandler(ATOM_item_link_start,   RSS_ATOM, HKEY("link"));
1589
1590                 AddRSSEndHandler(ATOMRSS_item_title_end,   RSS_ATOM|RSS_RSS|RSS_REQUIRE_BUF, HKEY("title"));
1591                 AddRSSEndHandler(RSS_item_guid_end,        RSS_RSS|RSS_REQUIRE_BUF, HKEY("guid"));
1592                 AddRSSEndHandler(ATOM_item_id_end,         RSS_ATOM|RSS_REQUIRE_BUF, HKEY("id"));
1593                 AddRSSEndHandler(RSS_item_link_end,        RSS_RSS|RSS_REQUIRE_BUF, HKEY("link"));
1594 #if 0 
1595 // hm, rss to the comments of that blog, might be interesting in future, but... 
1596                 AddRSSEndHandler(RSS_item_relink_end,      RSS_RSS|RSS_REQUIRE_BUF, HKEY("commentrss"));
1597 // comment count...
1598                 AddRSSEndHandler(RSS_item_relink_end,      RSS_RSS|RSS_REQUIRE_BUF, HKEY("comments"));
1599 #endif
1600                 AddRSSEndHandler(RSSATOM_item_title_end,   RSS_ATOM|RSS_RSS|RSS_REQUIRE_BUF, HKEY("title"));
1601                 AddRSSEndHandler(ATOM_item_content_end,    RSS_ATOM|RSS_REQUIRE_BUF, HKEY("content"));
1602                 AddRSSEndHandler(RSS_item_description_end, RSS_RSS|RSS_ATOM|RSS_REQUIRE_BUF, HKEY("encoded"));
1603                 AddRSSEndHandler(ATOM_item_summary_end,    RSS_ATOM|RSS_REQUIRE_BUF, HKEY("summary"));
1604                 AddRSSEndHandler(RSS_item_description_end, RSS_RSS|RSS_REQUIRE_BUF, HKEY("description"));
1605                 AddRSSEndHandler(ATOM_item_published_end,  RSS_ATOM|RSS_REQUIRE_BUF, HKEY("published"));
1606                 AddRSSEndHandler(ATOM_item_updated_end,    RSS_ATOM|RSS_REQUIRE_BUF, HKEY("updated"));
1607                 AddRSSEndHandler(RSS_item_pubdate_end,     RSS_RSS|RSS_REQUIRE_BUF, HKEY("pubdate"));
1608                 AddRSSEndHandler(RSS_item_date_end,        RSS_RSS|RSS_REQUIRE_BUF, HKEY("date"));
1609                 AddRSSEndHandler(RSS_item_author_end,      RSS_RSS|RSS_REQUIRE_BUF, HKEY("author"));
1610                 AddRSSEndHandler(RSS_item_creator_end,     RSS_RSS|RSS_REQUIRE_BUF, HKEY("creator"));
1611 /* <author> */
1612                 AddRSSEndHandler(ATOM_item_email_end,      RSS_ATOM|RSS_REQUIRE_BUF, HKEY("email"));
1613                 AddRSSEndHandler(ATOM_item_name_end,       RSS_ATOM|RSS_REQUIRE_BUF, HKEY("name"));
1614                 AddRSSEndHandler(ATOM_item_uri_end,        RSS_ATOM|RSS_REQUIRE_BUF, HKEY("uri"));
1615 /* </author> */
1616                 AddRSSEndHandler(RSS_item_item_end,        RSS_RSS, HKEY("item"));
1617                 AddRSSEndHandler(RSS_item_rss_end,         RSS_RSS, HKEY("rss"));
1618                 AddRSSEndHandler(RSS_item_rdf_end,         RSS_RSS, HKEY("rdf"));
1619                 AddRSSEndHandler(ATOM_item_entry_end,      RSS_ATOM, HKEY("entry"));
1620
1621
1622 /* at the start of atoms: <seq> <li>link to resource</li></seq> ignore them. */
1623                 AddRSSStartHandler(RSSATOM_item_ignore,      RSS_RSS|RSS_ATOM, HKEY("seq"));
1624                 AddRSSEndHandler  (RSSATOM_item_ignore,      RSS_RSS|RSS_ATOM, HKEY("seq"));
1625                 AddRSSStartHandler(RSSATOM_item_ignore,      RSS_RSS|RSS_ATOM, HKEY("li"));
1626                 AddRSSEndHandler  (RSSATOM_item_ignore,      RSS_RSS|RSS_ATOM, HKEY("li"));
1627
1628 /* links to other feed generators... */
1629                 AddRSSStartHandler(RSSATOM_item_ignore,      RSS_RSS|RSS_ATOM, HKEY("feedflare"));
1630                 AddRSSEndHandler  (RSSATOM_item_ignore,      RSS_RSS|RSS_ATOM, HKEY("feedflare"));
1631                 AddRSSStartHandler(RSSATOM_item_ignore,      RSS_RSS|RSS_ATOM, HKEY("browserfriendly"));
1632                 AddRSSEndHandler  (RSSATOM_item_ignore,      RSS_RSS|RSS_ATOM, HKEY("browserfriendly"));
1633
1634                 KnownNameSpaces = NewHash(1, NULL);
1635                 Put(KnownNameSpaces, HKEY("http://a9.com/-/spec/opensearch/1.1/"), NULL, reference_free_handler);
1636                 Put(KnownNameSpaces, HKEY("http://a9.com/-/spec/opensearchrss/1.0/"), NULL, reference_free_handler);
1637                 Put(KnownNameSpaces, HKEY("http://backend.userland.com/creativeCommonsRssModule"), NULL, reference_free_handler);
1638                 Put(KnownNameSpaces, HKEY("http://purl.org/atom/ns#"), NULL, reference_free_handler);
1639                 Put(KnownNameSpaces, HKEY("http://purl.org/dc/elements/1.1/"), NULL, reference_free_handler);
1640                 Put(KnownNameSpaces, HKEY("http://purl.org/rss/1.0/"), NULL, reference_free_handler);
1641                 Put(KnownNameSpaces, HKEY("http://purl.org/rss/1.0/modules/content/"), NULL, reference_free_handler);
1642                 Put(KnownNameSpaces, HKEY("http://purl.org/rss/1.0/modules/slash/"), NULL, reference_free_handler);
1643                 Put(KnownNameSpaces, HKEY("http://purl.org/rss/1.0/modules/syndication/"), NULL, reference_free_handler);
1644                 Put(KnownNameSpaces, HKEY("http://purl.org/rss/1.0/"), NULL, reference_free_handler);
1645                 Put(KnownNameSpaces, HKEY("http://purl.org/syndication/thread/1.0"), NULL, reference_free_handler);
1646                 Put(KnownNameSpaces, HKEY("http://rssnamespace.org/feedburner/ext/1.0"), NULL, reference_free_handler);
1647                 Put(KnownNameSpaces, HKEY("http://schemas.google.com/g/2005"), NULL, reference_free_handler);
1648                 Put(KnownNameSpaces, HKEY("http://webns.net/mvcb/"), NULL, reference_free_handler);
1649                 Put(KnownNameSpaces, HKEY("http://web.resource.org/cc/"), NULL, reference_free_handler);
1650                 Put(KnownNameSpaces, HKEY("http://wellformedweb.org/CommentAPI/"), NULL, reference_free_handler);
1651                 Put(KnownNameSpaces, HKEY("http://www.georss.org/georss"), NULL, reference_free_handler);
1652                 Put(KnownNameSpaces, HKEY("http://www.w3.org/1999/xhtml"), NULL, reference_free_handler);
1653                 Put(KnownNameSpaces, HKEY("http://www.w3.org/1999/02/22-rdf-syntax-ns#"), NULL, reference_free_handler);
1654                 Put(KnownNameSpaces, HKEY("http://www.w3.org/1999/02/22-rdf-syntax-ns#"), NULL, reference_free_handler);
1655                 Put(KnownNameSpaces, HKEY("http://www.w3.org/2003/01/geo/wgs84_pos#"), NULL, reference_free_handler);
1656                 Put(KnownNameSpaces, HKEY("http://www.w3.org/2005/Atom"), NULL, reference_free_handler);
1657                 Put(KnownNameSpaces, HKEY("urn:flickr:"), NULL, reference_free_handler);
1658 #if 0
1659                 /* we don't like these namespaces because of they shadow our usefull parameters. */
1660                 Put(KnownNameSpaces, HKEY("http://search.yahoo.com/mrss/"), NULL, reference_free_handler);
1661 #endif
1662                 CtdlRegisterCleanupHook(rss_cleanup);
1663         }
1664         return "rssclient";
1665 }