use an Enum for the cm_fields vector instead of nameless chars
[citadel.git] / citadel / modules / rssclient / serv_rssclient.c
1 /*
2  * Bring external RSS feeds into rooms.
3  *
4  * Copyright (c) 2007-2012 by the citadel.org team
5  *
6  * This program is open source software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 3.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
12  * GNU General Public License for more details.
13  */
14
15 #include <stdlib.h>
16 #include <unistd.h>
17 #include <stdio.h>
18
19 #if TIME_WITH_SYS_TIME
20 # include <sys/time.h>
21 # include <time.h>
22 #else
23 # if HAVE_SYS_TIME_H
24 #include <sys/time.h>
25 # else
26 #include <time.h>
27 # endif
28 #endif
29
30 #include <ctype.h>
31 #include <string.h>
32 #include <errno.h>
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #include <expat.h>
36 #include <curl/curl.h>
37 #include <libcitadel.h>
38 #include "citadel.h"
39 #include "server.h"
40 #include "citserver.h"
41 #include "support.h"
42 #include "config.h"
43 #include "threads.h"
44 #include "ctdl_module.h"
45 #include "msgbase.h"
46 #include "parsedate.h"
47 #include "database.h"
48 #include "citadel_dirs.h"
49 #include "md5.h"
50 #include "context.h"
51 #include "event_client.h"
52 #include "rss_atom_parser.h"
53
54
55 #define TMP_MSGDATA 0xFF
56 #define TMP_SHORTER_URL_OFFSET 0xFE
57 #define TMP_SHORTER_URLS 0xFD
58
59 time_t last_run = 0L;
60
61 pthread_mutex_t RSSQueueMutex; /* locks the access to the following vars: */
62 HashList *RSSQueueRooms = NULL; /* rss_room_counter */
63 HashList *RSSFetchUrls = NULL; /*->rss_aggregator;->RefCount access locked*/
64
65 eNextState RSSAggregator_Terminate(AsyncIO *IO);
66 eNextState RSSAggregator_TerminateDB(AsyncIO *IO);
67 eNextState RSSAggregator_ShutdownAbort(AsyncIO *IO);
68 struct CitContext rss_CC;
69
70 struct rssnetcfg *rnclist = NULL;
71 int RSSClientDebugEnabled = 0;
72 #define N ((rss_aggregator*)IO->Data)->Cfg.QRnumber
73
74 #define DBGLOG(LEVEL) if ((LEVEL != LOG_DEBUG) || (RSSClientDebugEnabled != 0))
75
76 #define EVRSSC_syslog(LEVEL, FORMAT, ...)                               \
77         DBGLOG(LEVEL) syslog(LEVEL,                                     \
78                              "IO[%ld]CC[%d][%ld]RSS" FORMAT,            \
79                              IO->ID, CCID, N, __VA_ARGS__)
80
81 #define EVRSSCM_syslog(LEVEL, FORMAT)                                   \
82         DBGLOG(LEVEL) syslog(LEVEL,                                     \
83                              "IO[%ld]CC[%d][%ld]RSS" FORMAT,            \
84                              IO->ID, CCID, N)
85
86 #define EVRSSQ_syslog(LEVEL, FORMAT, ...)                               \
87         DBGLOG(LEVEL) syslog(LEVEL, "RSS" FORMAT,                       \
88                              __VA_ARGS__)
89 #define EVRSSQM_syslog(LEVEL, FORMAT)                   \
90         DBGLOG(LEVEL) syslog(LEVEL, "RSS" FORMAT)
91
92 #define EVRSSCSM_syslog(LEVEL, FORMAT)                                  \
93         DBGLOG(LEVEL) syslog(LEVEL, "IO[%ld][%ld]RSS" FORMAT,           \
94                              IO->ID, N)
95
96 typedef enum _RSSState {
97         eRSSCreated,
98         eRSSFetching,
99         eRSSFailure,
100         eRSSParsing,
101         eRSSUT
102 } RSSState;
103 ConstStr RSSStates[] = {
104         {HKEY("Aggregator created")},
105         {HKEY("Fetching content")},
106         {HKEY("Failed")},
107         {HKEY("parsing content")},
108         {HKEY("checking usetable")}
109 };
110
111 static void SetRSSState(AsyncIO *IO, RSSState State)
112 {
113         CitContext* CCC = IO->CitContext;
114         if (CCC != NULL)
115                 memcpy(CCC->cs_clientname, RSSStates[State].Key, RSSStates[State].len + 1);
116 }
117
118 void DeleteRoomReference(long QRnumber)
119 {
120         HashPos *At;
121         long HKLen;
122         const char *HK;
123         void *vData = NULL;
124         rss_room_counter *pRoomC;
125
126         At = GetNewHashPos(RSSQueueRooms, 0);
127
128         if (GetHashPosFromKey(RSSQueueRooms, LKEY(QRnumber), At))
129         {
130                 GetHashPos(RSSQueueRooms, At, &HKLen, &HK, &vData);
131                 if (vData != NULL)
132                 {
133                         pRoomC = (rss_room_counter *) vData;
134                         pRoomC->count --;
135                         if (pRoomC->count == 0)
136                                 DeleteEntryFromHash(RSSQueueRooms, At);
137                 }
138         }
139         DeleteHashPos(&At);
140 }
141
142 void UnlinkRooms(rss_aggregator *RSSAggr)
143 {
144         DeleteRoomReference(RSSAggr->Cfg.QRnumber);
145         if (RSSAggr->OtherQRnumbers != NULL)
146         {
147                 long HKLen;
148                 const char *HK;
149                 HashPos *At;
150                 void *vData;
151
152                 At = GetNewHashPos(RSSAggr->OtherQRnumbers, 0);
153                 while (! server_shutting_down &&
154                        GetNextHashPos(RSSAggr->OtherQRnumbers,
155                                       At,
156                                       &HKLen, &HK,
157                                       &vData) &&
158                        (vData != NULL))
159                 {
160                         pRSSConfig *Data = (pRSSConfig*) vData;
161                         DeleteRoomReference(Data->QRnumber);
162                 }
163
164                 DeleteHashPos(&At);
165         }
166 }
167
168 void UnlinkRSSAggregator(rss_aggregator *RSSAggr)
169 {
170         HashPos *At;
171
172         pthread_mutex_lock(&RSSQueueMutex);
173         UnlinkRooms(RSSAggr);
174
175         At = GetNewHashPos(RSSFetchUrls, 0);
176         if (GetHashPosFromKey(RSSFetchUrls, SKEY(RSSAggr->Url), At))
177         {
178                 DeleteEntryFromHash(RSSFetchUrls, At);
179         }
180         DeleteHashPos(&At);
181         last_run = time(NULL);
182         pthread_mutex_unlock(&RSSQueueMutex);
183 }
184
185 void DeleteRssCfg(void *vptr)
186 {
187         rss_aggregator *RSSAggr = (rss_aggregator *)vptr;
188         AsyncIO *IO = &RSSAggr->IO;
189
190         if (IO->CitContext != NULL)
191                 EVRSSCM_syslog(LOG_DEBUG, "RSS: destroying\n");
192
193         FreeStrBuf(&RSSAggr->Url);
194         FreeStrBuf(&RSSAggr->rooms);
195         FreeStrBuf(&RSSAggr->CData);
196         FreeStrBuf(&RSSAggr->Key);
197         DeleteHash(&RSSAggr->OtherQRnumbers);
198
199         DeleteHashPos (&RSSAggr->Pos);
200         DeleteHash (&RSSAggr->Messages);
201         if (RSSAggr->recp.recp_room != NULL)
202                 free(RSSAggr->recp.recp_room);
203
204
205         if (RSSAggr->Item != NULL)
206         {
207                 flush_rss_item(RSSAggr->Item);
208
209                 free(RSSAggr->Item);
210         }
211
212         FreeAsyncIOContents(&RSSAggr->IO);
213         memset(RSSAggr, 0, sizeof(rss_aggregator));
214         free(RSSAggr);
215 }
216
217 eNextState RSSAggregator_Terminate(AsyncIO *IO)
218 {
219         rss_aggregator *RSSAggr = (rss_aggregator *)IO->Data;
220
221         EVRSSCM_syslog(LOG_DEBUG, "RSS: Terminating.\n");
222
223         StopCurlWatchers(IO);
224         UnlinkRSSAggregator(RSSAggr);
225         return eAbort;
226 }
227
228 eNextState RSSAggregator_TerminateDB(AsyncIO *IO)
229 {
230         rss_aggregator *RSSAggr = (rss_aggregator *)IO->Data;
231
232         EVRSSCM_syslog(LOG_DEBUG, "RSS: Terminating.\n");
233
234
235         StopDBWatchers(&RSSAggr->IO);
236         UnlinkRSSAggregator(RSSAggr);
237         return eAbort;
238 }
239
240 eNextState RSSAggregator_ShutdownAbort(AsyncIO *IO)
241 {
242         const char *pUrl;
243         rss_aggregator *RSSAggr = (rss_aggregator *)IO->Data;
244
245         pUrl = IO->ConnectMe->PlainUrl;
246         if (pUrl == NULL)
247                 pUrl = "";
248
249         EVRSSC_syslog(LOG_DEBUG, "RSS: Aborting by shutdown: %s.\n", pUrl);
250
251         StopCurlWatchers(IO);
252         UnlinkRSSAggregator(RSSAggr);
253         return eAbort;
254 }
255
256 void AppendLink(StrBuf *Message,
257                 StrBuf *link,
258                 StrBuf *LinkTitle,
259                 const char *Title)
260 {
261         if (StrLength(link) > 0)
262         {
263                 StrBufAppendBufPlain(Message, HKEY("<a href=\""), 0);
264                 StrBufAppendBuf(Message, link, 0);
265                 StrBufAppendBufPlain(Message, HKEY("\">"), 0);
266                 if (StrLength(LinkTitle) > 0)
267                         StrBufAppendBuf(Message, LinkTitle, 0);
268                 else if ((Title != NULL) && !IsEmptyStr(Title))
269                         StrBufAppendBufPlain(Message, Title, -1, 0);
270                 else
271                         StrBufAppendBuf(Message, link, 0);
272                 StrBufAppendBufPlain(Message, HKEY("</a><br>\n"), 0);
273         }
274 }
275
276
277 int rss_format_item(AsyncIO *IO, networker_save_message *SaveMsg)
278 {
279         StrBuf *Message;
280         int msglen = 0;
281
282         if (StrLength(SaveMsg->description) + 
283             StrLength(SaveMsg->link) + 
284             StrLength(SaveMsg->linkTitle) + 
285             StrLength(SaveMsg->reLink) +
286             StrLength(SaveMsg->reLinkTitle) +
287             StrLength(SaveMsg->title) == 0)
288         {
289                 EVRSSCM_syslog(LOG_INFO, "Refusing to save empty message.");
290                 return 0;
291         }
292
293         if (SaveMsg->author_or_creator != NULL) {
294
295                 char *From;
296                 StrBuf *Encoded = NULL;
297                 int FromAt;
298
299                 From = html_to_ascii(ChrPtr(SaveMsg->author_or_creator),
300                                      StrLength(SaveMsg->author_or_creator),
301                                      512, 0);
302                 StrBufPlain(SaveMsg->author_or_creator, From, -1);
303                 StrBufTrim(SaveMsg->author_or_creator);
304                 free(From);
305
306                 FromAt = strchr(ChrPtr(SaveMsg->author_or_creator), '@') != NULL;
307                 if (!FromAt && StrLength (SaveMsg->author_email) > 0)
308                 {
309                         StrBufRFC2047encode(&Encoded, SaveMsg->author_or_creator);
310                         SaveMsg->Msg.cm_fields[eAuthor] = SmashStrBuf(&Encoded);
311                         SaveMsg->Msg.cm_fields[eMessagePath] =
312                                 SmashStrBuf(&SaveMsg->author_email);
313                 }
314                 else
315                 {
316                         if (FromAt)
317                         {
318                                 SaveMsg->Msg.cm_fields[eAuthor] =
319                                         SmashStrBuf(&SaveMsg->author_or_creator);
320                                 SaveMsg->Msg.cm_fields[eMessagePath] =
321                                         strdup(SaveMsg->Msg.cm_fields[eAuthor]);
322                         }
323                         else
324                         {
325                                 StrBufRFC2047encode(&Encoded,
326                                                     SaveMsg->author_or_creator);
327                                 SaveMsg->Msg.cm_fields[eAuthor] =
328                                         SmashStrBuf(&Encoded);
329                                 SaveMsg->Msg.cm_fields[eMessagePath] =
330                                         strdup("rss@localhost");
331
332                         }
333                 }
334         }
335         else {
336                 SaveMsg->Msg.cm_fields[eAuthor] = strdup("rss");
337         }
338
339         SaveMsg->Msg.cm_fields[eNodeName] = strdup(NODENAME);
340         if (SaveMsg->title != NULL) {
341                 long len;
342                 char *Sbj;
343                 StrBuf *Encoded, *QPEncoded;
344
345                 QPEncoded = NULL;
346                 StrBufSpaceToBlank(SaveMsg->title);
347                 len = StrLength(SaveMsg->title);
348                 Sbj = html_to_ascii(ChrPtr(SaveMsg->title), len, 512, 0);
349                 len = strlen(Sbj);
350                 if ((len > 0) && (Sbj[len - 1] == '\n'))
351                 {
352                         len --;
353                         Sbj[len] = '\0';
354                 }
355                 Encoded = NewStrBufPlain(Sbj, len);
356                 free(Sbj);
357
358                 StrBufTrim(Encoded);
359                 StrBufRFC2047encode(&QPEncoded, Encoded);
360
361                 SaveMsg->Msg.cm_fields[eMsgSubject] = SmashStrBuf(&QPEncoded);
362                 FreeStrBuf(&Encoded);
363         }
364         if (SaveMsg->link == NULL)
365                 SaveMsg->link = NewStrBufPlain(HKEY(""));
366
367 #if 0 /* temporarily disable shorter urls. */
368         SaveMsg->Msg.cm_fields[TMP_SHORTER_URLS] =
369                 GetShorterUrls(SaveMsg->description);
370 #endif
371
372         msglen += 1024 + StrLength(SaveMsg->link) + StrLength(SaveMsg->description) ;
373
374         Message = NewStrBufPlain(NULL, msglen);
375
376         StrBufPlain(Message, HKEY(
377                             "Content-type: text/html; charset=\"UTF-8\"\r\n\r\n"
378                             "<html><body>\n"));
379 #if 0 /* disable shorter url for now. */
380         SaveMsg->Msg.cm_fields[TMP_SHORTER_URL_OFFSET] = StrLength(Message);
381 #endif
382         StrBufAppendBuf(Message, SaveMsg->description, 0);
383         StrBufAppendBufPlain(Message, HKEY("<br><br>\n"), 0);
384
385         AppendLink(Message, SaveMsg->link, SaveMsg->linkTitle, NULL);
386         AppendLink(Message, SaveMsg->reLink, SaveMsg->reLinkTitle, "Reply to this");
387         StrBufAppendBufPlain(Message, HKEY("</body></html>\n"), 0);
388
389         SaveMsg->Message = Message;
390         return 1;
391 }
392
393 eNextState RSSSaveMessage(AsyncIO *IO)
394 {
395         long len;
396         const char *Key;
397         rss_aggregator *RSSAggr = (rss_aggregator *) IO->Data;
398
399         if (rss_format_item(IO, RSSAggr->ThisMsg))
400         {
401                 RSSAggr->ThisMsg->Msg.cm_fields[eMesageText] =
402                         SmashStrBuf(&RSSAggr->ThisMsg->Message);
403
404                 CtdlSubmitMsg(&RSSAggr->ThisMsg->Msg, &RSSAggr->recp, NULL, 0);
405                 
406                 /* write the uidl to the use table so we don't store this item again */
407                 
408                 CheckIfAlreadySeen("RSS Item Insert", RSSAggr->ThisMsg->MsgGUID, IO->Now, 0, eWrite, CCID, IO->ID);
409         }
410
411         if (GetNextHashPos(RSSAggr->Messages,
412                            RSSAggr->Pos,
413                            &len, &Key,
414                            (void**) &RSSAggr->ThisMsg))
415                 return NextDBOperation(IO, RSS_FetchNetworkUsetableEntry);
416         else
417                 return eAbort;
418 }
419
420 eNextState RSS_FetchNetworkUsetableEntry(AsyncIO *IO)
421 {
422 #ifndef DEBUG_RSS
423         const char *Key;
424         long len;
425         rss_aggregator *Ctx = (rss_aggregator *) IO->Data;
426
427         /* Find out if we've already seen this item */
428 // todo: expiry?
429         SetRSSState(IO, eRSSUT);
430         if (CheckIfAlreadySeen("RSS Item Seen",
431                                Ctx->ThisMsg->MsgGUID,
432                                IO->Now,
433                                IO->Now - USETABLE_ANTIEXPIRE_HIRES,
434                                eCheckUpdate,
435                                CCID, IO->ID)
436             != 0)
437         {
438                 /* Item has already been seen */
439                 EVRSSC_syslog(LOG_DEBUG,
440                           "%s has already been seen\n",
441                           ChrPtr(Ctx->ThisMsg->MsgGUID));
442                 SetRSSState(IO, eRSSParsing);
443
444                 if (GetNextHashPos(Ctx->Messages,
445                                    Ctx->Pos,
446                                    &len, &Key,
447                                    (void**) &Ctx->ThisMsg))
448                         return NextDBOperation(
449                                 IO,
450                                 RSS_FetchNetworkUsetableEntry);
451                 else
452                         return eAbort;
453         }
454         else
455 #endif
456         {
457                 SetRSSState(IO, eRSSParsing);
458
459                 NextDBOperation(IO, RSSSaveMessage);
460                 return eSendMore;
461         }
462         return eSendMore;
463 }
464
465 void UpdateLastKnownGood(pRSSConfig *pCfg, time_t now)
466 {
467         OneRoomNetCfg* pRNCfg;
468         begin_critical_section(S_NETCONFIGS);
469         pRNCfg = CtdlGetNetCfgForRoom (pCfg->QRnumber);
470         if (pRNCfg != NULL)
471         {
472                 RSSCfgLine *RSSCfg = (RSSCfgLine *)pRNCfg->NetConfigs[rssclient];
473
474                 while (RSSCfg != NULL)
475                 {
476                         if (RSSCfg == pCfg->pCfg)
477                                 break;
478
479                         RSSCfg = RSSCfg->next;
480                 }
481                 if (RSSCfg != NULL)
482                 {
483                         pRNCfg->changed = 1;
484                         RSSCfg->last_known_good = now;
485                 }
486         }
487
488         end_critical_section(S_NETCONFIGS);
489 }
490
491 eNextState RSSAggregator_AnalyseReply(AsyncIO *IO)
492 {
493         HashPos *it = NULL;
494         long len;
495         const char *Key;
496         pRSSConfig *pCfg;
497         u_char rawdigest[MD5_DIGEST_LEN];
498         struct MD5Context md5context;
499         StrBuf *guid;
500         rss_aggregator *Ctx = (rss_aggregator *) IO->Data;
501
502         if (IO->HttpReq.httpcode != 200)
503         {
504                 StrBuf *ErrMsg;
505                 long lens[2];
506                 const char *strs[2];
507
508                 SetRSSState(IO, eRSSFailure);
509                 ErrMsg = NewStrBuf();
510                 EVRSSC_syslog(LOG_ALERT, "need a 200, got a %ld !\n",
511                               IO->HttpReq.httpcode);
512                 
513                 strs[0] = ChrPtr(Ctx->Url);
514                 lens[0] = StrLength(Ctx->Url);
515
516                 strs[1] = ChrPtr(Ctx->rooms);
517                 lens[1] = StrLength(Ctx->rooms);
518
519                 if (IO->HttpReq.CurlError == NULL)
520                         IO->HttpReq.CurlError = "";
521
522                 StrBufPrintf(ErrMsg,
523                              "Error while RSS-Aggregation Run of %s\n"
524                              " need a 200, got a %ld !\n"
525                              " Curl Error message: \n%s / %s\n"
526                              " Response text was: \n"
527                              " \n %s\n",
528                              ChrPtr(Ctx->Url),
529                              IO->HttpReq.httpcode,
530                              IO->HttpReq.errdesc,
531                              IO->HttpReq.CurlError,
532                              ChrPtr(IO->HttpReq.ReplyData)
533                         );
534
535                 CtdlAideFPMessage(
536                         ChrPtr(ErrMsg),
537                         "RSS Aggregation run failure",
538                         2, strs, (long*) &lens,
539                         IO->Now,
540                         IO->ID, CCID);
541                 
542                 FreeStrBuf(&ErrMsg);
543                 EVRSSC_syslog(LOG_DEBUG,
544                               "RSS feed returned an invalid http status code. <%s><HTTP %ld>\n",
545                               ChrPtr(Ctx->Url),
546                               IO->HttpReq.httpcode);
547                 return eAbort;
548         }
549
550         pCfg = &Ctx->Cfg;
551
552         while (pCfg != NULL)
553         {
554                 UpdateLastKnownGood (pCfg, IO->Now);
555                 if ((Ctx->roomlist_parts > 1) && 
556                     (it == NULL))
557                 {
558                         it = GetNewHashPos(RSSFetchUrls, 0);
559                 }
560                 if (it != NULL)
561                 {
562                         void *vptr;
563                         if (GetNextHashPos(Ctx->OtherQRnumbers, it, &len, &Key, &vptr))
564                                 pCfg = vptr;
565                         else
566                                 pCfg = NULL;
567                 }
568                 else 
569                         pCfg = NULL;
570         }
571         DeleteHashPos (&it);
572
573         SetRSSState(IO, eRSSUT);
574
575         MD5Init(&md5context);
576
577         MD5Update(&md5context,
578                   (const unsigned char*)SKEY(IO->HttpReq.ReplyData));
579
580         MD5Update(&md5context,
581                   (const unsigned char*)SKEY(Ctx->Url));
582
583         MD5Final(rawdigest, &md5context);
584         guid = NewStrBufPlain(NULL,
585                               MD5_DIGEST_LEN * 2 + 12 /* _rss2ctdl*/);
586         StrBufHexEscAppend(guid, NULL, rawdigest, MD5_DIGEST_LEN);
587         StrBufAppendBufPlain(guid, HKEY("_rssFM"), 0);
588         if (StrLength(guid) > 40)
589                 StrBufCutAt(guid, 40, NULL);
590         /* Find out if we've already seen this item */
591
592 #ifndef DEBUG_RSS
593
594         if (CheckIfAlreadySeen("RSS Whole",
595                                guid,
596                                IO->Now,
597                                IO->Now - USETABLE_ANTIEXPIRE,
598                                eCheckUpdate,
599                                CCID, IO->ID)
600             != 0)
601         {
602                 FreeStrBuf(&guid);
603
604                 EVRSSC_syslog(LOG_DEBUG, "RSS feed already seen. <%s>\n", ChrPtr(Ctx->Url));
605                 return eAbort;
606         }
607         FreeStrBuf(&guid);
608 #endif
609         SetRSSState(IO, eRSSParsing);
610         return RSSAggregator_ParseReply(IO);
611 }
612
613 eNextState RSSAggregator_FinishHttp(AsyncIO *IO)
614 {
615         return CurlQueueDBOperation(IO, RSSAggregator_AnalyseReply);
616 }
617
618 /*
619  * Begin a feed parse
620  */
621 int rss_do_fetching(rss_aggregator *RSSAggr)
622 {
623         AsyncIO         *IO = &RSSAggr->IO;
624         rss_item *ri;
625         time_t now;
626
627         now = time(NULL);
628
629         if ((RSSAggr->next_poll != 0) && (now < RSSAggr->next_poll))
630                 return 0;
631
632         ri = (rss_item*) malloc(sizeof(rss_item));
633         memset(ri, 0, sizeof(rss_item));
634         RSSAggr->Item = ri;
635
636         if (! InitcURLIOStruct(&RSSAggr->IO,
637                                RSSAggr,
638                                "Citadel RSS Client",
639                                RSSAggregator_FinishHttp,
640                                RSSAggregator_Terminate,
641                                RSSAggregator_TerminateDB,
642                                RSSAggregator_ShutdownAbort))
643         {
644                 EVRSSCM_syslog(LOG_ALERT, "Unable to initialize libcurl.\n");
645                 return 0;
646         }
647         SetRSSState(IO, eRSSCreated);
648
649         safestrncpy(((CitContext*)RSSAggr->IO.CitContext)->cs_host,
650                     ChrPtr(RSSAggr->Url),
651                     sizeof(((CitContext*)RSSAggr->IO.CitContext)->cs_host));
652
653         EVRSSC_syslog(LOG_DEBUG, "Fetching RSS feed <%s>\n", ChrPtr(RSSAggr->Url));
654         ParseURL(&RSSAggr->IO.ConnectMe, RSSAggr->Url, 80);
655         CurlPrepareURL(RSSAggr->IO.ConnectMe);
656
657         SetRSSState(IO, eRSSFetching);
658         QueueCurlContext(&RSSAggr->IO);
659         return 1;
660 }
661
662 /*
663  * Scan a room's netconfig to determine whether it is requesting any RSS feeds
664  */
665 void rssclient_scan_room(struct ctdlroom *qrbuf, void *data, OneRoomNetCfg *OneRNCFG)
666 {
667         const RSSCfgLine *RSSCfg = (RSSCfgLine *)OneRNCFG->NetConfigs[rssclient];
668         rss_aggregator *RSSAggr = NULL;
669         rss_aggregator *use_this_RSSAggr = NULL;
670         void *vptr;
671
672         pthread_mutex_lock(&RSSQueueMutex);
673         if (GetHash(RSSQueueRooms, LKEY(qrbuf->QRnumber), &vptr))
674         {
675                 EVRSSQ_syslog(LOG_DEBUG,
676                               "rssclient: [%ld] %s already in progress.\n",
677                               qrbuf->QRnumber,
678                               qrbuf->QRname);
679                 pthread_mutex_unlock(&RSSQueueMutex);
680                 return;
681         }
682         pthread_mutex_unlock(&RSSQueueMutex);
683
684         if (server_shutting_down) return;
685
686         while (RSSCfg != NULL)
687         {
688                 pthread_mutex_lock(&RSSQueueMutex);
689                 GetHash(RSSFetchUrls,
690                         SKEY(RSSCfg->Url),
691                         &vptr);
692
693                 use_this_RSSAggr = (rss_aggregator *)vptr;
694                 if (use_this_RSSAggr != NULL)
695                 {
696                         pRSSConfig *pRSSCfg;
697
698                         StrBufAppendBufPlain(
699                                 use_this_RSSAggr->rooms,
700                                 qrbuf->QRname,
701                                 -1, 0);
702                         if (use_this_RSSAggr->roomlist_parts==1)
703                         {
704                                 use_this_RSSAggr->OtherQRnumbers
705                                         = NewHash(1, lFlathash);
706                         }
707
708                         pRSSCfg = (pRSSConfig *) malloc(sizeof(pRSSConfig));
709
710                         pRSSCfg->QRnumber = qrbuf->QRnumber;
711                         pRSSCfg->pCfg = RSSCfg;
712
713                         Put(use_this_RSSAggr->OtherQRnumbers,
714                             LKEY(qrbuf->QRnumber),
715                             pRSSCfg,
716                             NULL);
717                         use_this_RSSAggr->roomlist_parts++;
718
719                         pthread_mutex_unlock(&RSSQueueMutex);
720
721                         RSSCfg = RSSCfg->next;
722                         continue;
723                 }
724                 pthread_mutex_unlock(&RSSQueueMutex);
725
726                 RSSAggr = (rss_aggregator *) malloc(
727                         sizeof(rss_aggregator));
728
729                 memset (RSSAggr, 0, sizeof(rss_aggregator));
730                 RSSAggr->Cfg.QRnumber = qrbuf->QRnumber;
731                 RSSAggr->Cfg.pCfg = RSSCfg;
732                 RSSAggr->roomlist_parts = 1;
733                 RSSAggr->Url = NewStrBufDup(RSSCfg->Url);
734
735                 RSSAggr->ItemType = RSS_UNSET;
736
737                 RSSAggr->rooms = NewStrBufPlain(
738                         qrbuf->QRname, -1);
739
740                 pthread_mutex_lock(&RSSQueueMutex);
741
742                 Put(RSSFetchUrls,
743                     SKEY(RSSAggr->Url),
744                     RSSAggr,
745                     DeleteRssCfg);
746
747                 pthread_mutex_unlock(&RSSQueueMutex);
748                 RSSCfg = RSSCfg->next;
749         }
750 }
751
752 /*
753  * Scan for rooms that have RSS client requests configured
754  */
755 void rssclient_scan(void) {
756         int RSSRoomCount, RSSCount;
757         rss_aggregator *rptr = NULL;
758         void *vrptr = NULL;
759         HashPos *it;
760         long len;
761         const char *Key;
762         time_t now = time(NULL);
763
764         /* Run no more than once every 15 minutes. */
765         if ((now - last_run) < 900) {
766                 EVRSSQ_syslog(LOG_DEBUG,
767                               "Client: polling interval not yet reached; last run was %ldm%lds ago",
768                               ((now - last_run) / 60),
769                               ((now - last_run) % 60)
770                 );
771                 return;
772         }
773
774         /*
775          * This is a simple concurrency check to make sure only one rssclient
776          * run is done at a time.
777          */
778         pthread_mutex_lock(&RSSQueueMutex);
779         RSSCount = GetCount(RSSFetchUrls);
780         RSSRoomCount = GetCount(RSSQueueRooms);
781         pthread_mutex_unlock(&RSSQueueMutex);
782
783         if ((RSSRoomCount > 0) || (RSSCount > 0)) {
784                 EVRSSQ_syslog(LOG_DEBUG,
785                               "rssclient: concurrency check failed; %d rooms and %d url's are queued",
786                               RSSRoomCount, RSSCount
787                         );
788                 return;
789         }
790
791         become_session(&rss_CC);
792         EVRSSQM_syslog(LOG_DEBUG, "rssclient started");
793         CtdlForEachNetCfgRoom(rssclient_scan_room, NULL, rssclient);
794
795         if (GetCount(RSSFetchUrls) > 0)
796         {
797                 pthread_mutex_lock(&RSSQueueMutex);
798                 EVRSSQ_syslog(LOG_DEBUG,
799                                "rssclient starting %d Clients",
800                                GetCount(RSSFetchUrls));
801                 
802                 it = GetNewHashPos(RSSFetchUrls, 0);
803                 while (!server_shutting_down &&
804                        GetNextHashPos(RSSFetchUrls, it, &len, &Key, &vrptr) &&
805                        (vrptr != NULL)) {
806                         rptr = (rss_aggregator *)vrptr;
807                         if (!rss_do_fetching(rptr))
808                                 UnlinkRSSAggregator(rptr);
809                 }
810                 DeleteHashPos(&it);
811                 pthread_mutex_unlock(&RSSQueueMutex);
812         }
813         else
814                 EVRSSQM_syslog(LOG_DEBUG, "Nothing to do.");
815
816         EVRSSQM_syslog(LOG_DEBUG, "rssclient ended\n");
817         return;
818 }
819
820 void rss_cleanup(void)
821 {
822         /* citthread_mutex_destroy(&RSSQueueMutex); TODO */
823         DeleteHash(&RSSFetchUrls);
824         DeleteHash(&RSSQueueRooms);
825 }
826
827 void LogDebugEnableRSSClient(const int n)
828 {
829         RSSClientDebugEnabled = n;
830 }
831
832
833 typedef struct __RSSVetoInfo {
834         StrBuf *ErrMsg;
835         time_t Now;
836         int Veto;
837 }RSSVetoInfo;
838
839 void rssclient_veto_scan_room(struct ctdlroom *qrbuf, void *data, OneRoomNetCfg *OneRNCFG)
840 {
841         RSSVetoInfo *Info = (RSSVetoInfo *) data;
842         const RSSCfgLine *RSSCfg = (RSSCfgLine *)OneRNCFG->NetConfigs[rssclient];
843
844         while (RSSCfg != NULL)
845         {
846                 if ((RSSCfg->last_known_good != 0) &&
847                     (RSSCfg->last_known_good + USETABLE_ANTIEXPIRE < Info->Now))
848                 {
849                         StrBufAppendPrintf(Info->ErrMsg,
850                                            "RSS feed not seen for a %d days:: <",
851                                            (Info->Now - RSSCfg->last_known_good) / (24 * 60 * 60));
852
853                         StrBufAppendBuf(Info->ErrMsg, RSSCfg->Url, 0);
854                         StrBufAppendBufPlain(Info->ErrMsg, HKEY(">\n"), 0);
855                 }
856                 RSSCfg = RSSCfg->next;
857         }
858 }
859
860 int RSSCheckUsetableVeto(StrBuf *ErrMsg)
861 {
862         RSSVetoInfo Info;
863
864         Info.ErrMsg = ErrMsg;
865         Info.Now = time (NULL);
866         Info.Veto = 0;
867
868         CtdlForEachNetCfgRoom(rssclient_veto_scan_room, &Info, rssclient);
869
870         return Info.Veto;;
871 }
872
873
874
875
876 void ParseRSSClientCfgLine(const CfgLineType *ThisOne, StrBuf *Line, const char *LinePos, OneRoomNetCfg *OneRNCFG)
877 {
878         RSSCfgLine *RSSCfg;
879
880         RSSCfg = (RSSCfgLine *) malloc (sizeof(RSSCfgLine));
881         RSSCfg->Url = NewStrBufPlain (NULL, StrLength (Line));
882         
883
884         StrBufExtract_NextToken(RSSCfg->Url, Line, &LinePos, '|');
885         RSSCfg->last_known_good = StrBufExtractNext_long(Line, &LinePos, '|');
886
887
888         RSSCfg->next = (RSSCfgLine *)OneRNCFG->NetConfigs[ThisOne->C];
889         OneRNCFG->NetConfigs[ThisOne->C] = (RoomNetCfgLine*) RSSCfg;
890 }
891
892 void SerializeRSSClientCfgLine(const CfgLineType *ThisOne, StrBuf *OutputBuffer, OneRoomNetCfg *RNCfg, RoomNetCfgLine *data)
893 {
894         RSSCfgLine *RSSCfg = (RSSCfgLine*) data;
895
896         StrBufAppendBufPlain(OutputBuffer, CKEY(ThisOne->Str), 0);
897         StrBufAppendBufPlain(OutputBuffer, HKEY("|"), 0);
898         StrBufAppendBufPlain(OutputBuffer, SKEY(RSSCfg->Url), 0);
899         StrBufAppendPrintf(OutputBuffer, "|%ld\n", RSSCfg->last_known_good);
900 }
901
902 void DeleteRSSClientCfgLine(const CfgLineType *ThisOne, RoomNetCfgLine **data)
903 {
904         RSSCfgLine *RSSCfg = (RSSCfgLine*) *data;
905
906         FreeStrBuf(&RSSCfg->Url);
907         free(*data);
908         *data = NULL;
909 }
910
911
912 CTDL_MODULE_INIT(rssclient)
913 {
914         if (!threading)
915         {
916                 CtdlRegisterTDAPVetoHook (RSSCheckUsetableVeto, CDB_USETABLE, 0);
917
918                 CtdlREGISTERRoomCfgType(rssclient, ParseRSSClientCfgLine, 0, 1, SerializeRSSClientCfgLine, DeleteRSSClientCfgLine);
919                 pthread_mutex_init(&RSSQueueMutex, NULL);
920                 RSSQueueRooms = NewHash(1, lFlathash);
921                 RSSFetchUrls = NewHash(1, NULL);
922                 syslog(LOG_INFO, "%s\n", curl_version());
923                 CtdlRegisterSessionHook(rssclient_scan, EVT_TIMER, PRIO_AGGR + 300);
924                 CtdlRegisterEVCleanupHook(rss_cleanup);
925                 CtdlRegisterDebugFlagHook(HKEY("rssclient"), LogDebugEnableRSSClient, &RSSClientDebugEnabled);
926         }
927         else
928         {
929                 CtdlFillSystemContext(&rss_CC, "rssclient");
930         }
931         return "rssclient";
932 }