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