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