fffe6d8e1f81201642bae63af3c8da55212a1cd9
[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['A'] = SmashStrBuf(&Encoded);
311                         SaveMsg->Msg.cm_fields['P'] =
312                                 SmashStrBuf(&SaveMsg->author_email);
313                 }
314                 else
315                 {
316                         if (FromAt)
317                         {
318                                 SaveMsg->Msg.cm_fields['A'] =
319                                         SmashStrBuf(&SaveMsg->author_or_creator);
320                                 SaveMsg->Msg.cm_fields['P'] =
321                                         strdup(SaveMsg->Msg.cm_fields['A']);
322                         }
323                         else
324                         {
325                                 StrBufRFC2047encode(&Encoded,
326                                                     SaveMsg->author_or_creator);
327                                 SaveMsg->Msg.cm_fields['A'] =
328                                         SmashStrBuf(&Encoded);
329                                 SaveMsg->Msg.cm_fields['P'] =
330                                         strdup("rss@localhost");
331
332                         }
333                 }
334         }
335         else {
336                 SaveMsg->Msg.cm_fields['A'] = strdup("rss");
337         }
338
339         SaveMsg->Msg.cm_fields['N'] = 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['U'] = 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['M'] =
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         const char *Key;
423         long len;
424         rss_aggregator *Ctx = (rss_aggregator *) IO->Data;
425
426         /* Find out if we've already seen this item */
427 // todo: expiry?
428 #ifndef DEBUG_RSS
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                 StrBufPrintf(ErrMsg,
519                              "Error while RSS-Aggregation Run of %s\n"
520                              " need a 200, got a %ld !\n"
521                              " Response text was: \n"
522                              " \n %s\n",
523                              ChrPtr(Ctx->Url),
524                              IO->HttpReq.httpcode,
525                              ChrPtr(IO->HttpReq.ReplyData));
526                 CtdlAideFPMessage(
527                         ChrPtr(ErrMsg),
528                         "RSS Aggregation run failure",
529                         2, strs, (long*) &lens,
530                         IO->Now,
531                         IO->ID, CCID);
532                 
533                 FreeStrBuf(&ErrMsg);
534                 EVRSSC_syslog(LOG_DEBUG,
535                               "RSS feed returned an invalid http status code. <%s><HTTP %ld>\n",
536                               ChrPtr(Ctx->Url),
537                               IO->HttpReq.httpcode);
538                 return eAbort;
539         }
540
541         pCfg = &Ctx->Cfg;
542
543         while (pCfg != NULL)
544         {
545                 UpdateLastKnownGood (pCfg, IO->Now);
546                 if ((Ctx->roomlist_parts > 1) && 
547                     (it == NULL))
548                 {
549                         it = GetNewHashPos(RSSFetchUrls, 0);
550                 }
551                 if (it != NULL)
552                 {
553                         void *vptr;
554                         if (GetNextHashPos(Ctx->OtherQRnumbers, it, &len, &Key, &vptr))
555                                 pCfg = vptr;
556                         else
557                                 pCfg = NULL;
558                 }
559                 else 
560                         pCfg = NULL;
561         }
562         DeleteHashPos (&it);
563
564         SetRSSState(IO, eRSSUT);
565
566         MD5Init(&md5context);
567
568         MD5Update(&md5context,
569                   (const unsigned char*)SKEY(IO->HttpReq.ReplyData));
570
571         MD5Update(&md5context,
572                   (const unsigned char*)SKEY(Ctx->Url));
573
574         MD5Final(rawdigest, &md5context);
575         guid = NewStrBufPlain(NULL,
576                               MD5_DIGEST_LEN * 2 + 12 /* _rss2ctdl*/);
577         StrBufHexEscAppend(guid, NULL, rawdigest, MD5_DIGEST_LEN);
578         StrBufAppendBufPlain(guid, HKEY("_rssFM"), 0);
579         if (StrLength(guid) > 40)
580                 StrBufCutAt(guid, 40, NULL);
581         /* Find out if we've already seen this item */
582
583 #ifndef DEBUG_RSS
584
585         if (CheckIfAlreadySeen("RSS Whole",
586                                guid,
587                                IO->Now,
588                                IO->Now - USETABLE_ANTIEXPIRE,
589                                eCheckUpdate,
590                                CCID, IO->ID)
591             != 0)
592         {
593                 FreeStrBuf(&guid);
594
595                 EVRSSC_syslog(LOG_DEBUG, "RSS feed already seen. <%s>\n", ChrPtr(Ctx->Url));
596                 return eAbort;
597         }
598         FreeStrBuf(&guid);
599 #endif
600         SetRSSState(IO, eRSSParsing);
601         return RSSAggregator_ParseReply(IO);
602 }
603
604 eNextState RSSAggregator_FinishHttp(AsyncIO *IO)
605 {
606         return CurlQueueDBOperation(IO, RSSAggregator_AnalyseReply);
607 }
608
609 /*
610  * Begin a feed parse
611  */
612 int rss_do_fetching(rss_aggregator *RSSAggr)
613 {
614         AsyncIO         *IO = &RSSAggr->IO;
615         rss_item *ri;
616         time_t now;
617
618         now = time(NULL);
619
620         if ((RSSAggr->next_poll != 0) && (now < RSSAggr->next_poll))
621                 return 0;
622
623         ri = (rss_item*) malloc(sizeof(rss_item));
624         memset(ri, 0, sizeof(rss_item));
625         RSSAggr->Item = ri;
626
627         if (! InitcURLIOStruct(&RSSAggr->IO,
628                                RSSAggr,
629                                "Citadel RSS Client",
630                                RSSAggregator_FinishHttp,
631                                RSSAggregator_Terminate,
632                                RSSAggregator_TerminateDB,
633                                RSSAggregator_ShutdownAbort))
634         {
635                 EVRSSCM_syslog(LOG_ALERT, "Unable to initialize libcurl.\n");
636                 return 0;
637         }
638         SetRSSState(IO, eRSSCreated);
639
640         safestrncpy(((CitContext*)RSSAggr->IO.CitContext)->cs_host,
641                     ChrPtr(RSSAggr->Url),
642                     sizeof(((CitContext*)RSSAggr->IO.CitContext)->cs_host));
643
644         EVRSSC_syslog(LOG_DEBUG, "Fetching RSS feed <%s>\n", ChrPtr(RSSAggr->Url));
645         ParseURL(&RSSAggr->IO.ConnectMe, RSSAggr->Url, 80);
646         CurlPrepareURL(RSSAggr->IO.ConnectMe);
647
648         SetRSSState(IO, eRSSFetching);
649         QueueCurlContext(&RSSAggr->IO);
650         return 1;
651 }
652
653 /*
654  * Scan a room's netconfig to determine whether it is requesting any RSS feeds
655  */
656 void rssclient_scan_room(struct ctdlroom *qrbuf, void *data, OneRoomNetCfg *OneRNCFG)
657 {
658         const RSSCfgLine *RSSCfg = (RSSCfgLine *)OneRNCFG->NetConfigs[rssclient];
659         rss_aggregator *RSSAggr = NULL;
660         rss_aggregator *use_this_RSSAggr = NULL;
661         void *vptr;
662
663         pthread_mutex_lock(&RSSQueueMutex);
664         if (GetHash(RSSQueueRooms, LKEY(qrbuf->QRnumber), &vptr))
665         {
666                 EVRSSQ_syslog(LOG_DEBUG,
667                               "rssclient: [%ld] %s already in progress.\n",
668                               qrbuf->QRnumber,
669                               qrbuf->QRname);
670                 pthread_mutex_unlock(&RSSQueueMutex);
671                 return;
672         }
673         pthread_mutex_unlock(&RSSQueueMutex);
674
675         if (server_shutting_down) return;
676
677         while (RSSCfg != NULL)
678         {
679                 pthread_mutex_lock(&RSSQueueMutex);
680                 GetHash(RSSFetchUrls,
681                         SKEY(RSSCfg->Url),
682                         &vptr);
683
684                 use_this_RSSAggr = (rss_aggregator *)vptr;
685                 if (use_this_RSSAggr != NULL)
686                 {
687                         pRSSConfig *pRSSCfg;
688
689                         StrBufAppendBufPlain(
690                                 use_this_RSSAggr->rooms,
691                                 qrbuf->QRname,
692                                 -1, 0);
693                         if (use_this_RSSAggr->roomlist_parts==1)
694                         {
695                                 use_this_RSSAggr->OtherQRnumbers
696                                         = NewHash(1, lFlathash);
697                         }
698
699                         pRSSCfg = (pRSSConfig *) malloc(sizeof(pRSSConfig));
700
701                         pRSSCfg->QRnumber = qrbuf->QRnumber;
702                         pRSSCfg->pCfg = RSSCfg;
703
704                         Put(use_this_RSSAggr->OtherQRnumbers,
705                             LKEY(qrbuf->QRnumber),
706                             pRSSCfg,
707                             NULL);
708                         use_this_RSSAggr->roomlist_parts++;
709
710                         pthread_mutex_unlock(&RSSQueueMutex);
711
712                         RSSCfg = RSSCfg->next;
713                         continue;
714                 }
715                 pthread_mutex_unlock(&RSSQueueMutex);
716
717                 RSSAggr = (rss_aggregator *) malloc(
718                         sizeof(rss_aggregator));
719
720                 memset (RSSAggr, 0, sizeof(rss_aggregator));
721                 RSSAggr->Cfg.QRnumber = qrbuf->QRnumber;
722                 RSSAggr->Cfg.pCfg = RSSCfg;
723                 RSSAggr->roomlist_parts = 1;
724                 RSSAggr->Url = NewStrBufDup(RSSCfg->Url);
725
726                 RSSAggr->ItemType = RSS_UNSET;
727
728                 RSSAggr->rooms = NewStrBufPlain(
729                         qrbuf->QRname, -1);
730
731                 pthread_mutex_lock(&RSSQueueMutex);
732
733                 Put(RSSFetchUrls,
734                     SKEY(RSSAggr->Url),
735                     RSSAggr,
736                     DeleteRssCfg);
737
738                 pthread_mutex_unlock(&RSSQueueMutex);
739                 RSSCfg = RSSCfg->next;
740         }
741 }
742
743 /*
744  * Scan for rooms that have RSS client requests configured
745  */
746 void rssclient_scan(void) {
747         int RSSRoomCount, RSSCount;
748         rss_aggregator *rptr = NULL;
749         void *vrptr = NULL;
750         HashPos *it;
751         long len;
752         const char *Key;
753         time_t now = time(NULL);
754
755         /* Run no more than once every 15 minutes. */
756         if ((now - last_run) < 900) {
757                 EVRSSQ_syslog(LOG_DEBUG,
758                               "Client: polling interval not yet reached; last run was %ldm%lds ago",
759                               ((now - last_run) / 60),
760                               ((now - last_run) % 60)
761                 );
762                 return;
763         }
764
765         /*
766          * This is a simple concurrency check to make sure only one rssclient
767          * run is done at a time.
768          */
769         pthread_mutex_lock(&RSSQueueMutex);
770         RSSCount = GetCount(RSSFetchUrls);
771         RSSRoomCount = GetCount(RSSQueueRooms);
772         pthread_mutex_unlock(&RSSQueueMutex);
773
774         if ((RSSRoomCount > 0) || (RSSCount > 0)) {
775                 EVRSSQ_syslog(LOG_DEBUG,
776                               "rssclient: concurrency check failed; %d rooms and %d url's are queued",
777                               RSSRoomCount, RSSCount
778                         );
779                 return;
780         }
781
782         become_session(&rss_CC);
783         EVRSSQM_syslog(LOG_DEBUG, "rssclient started");
784         CtdlForEachNetCfgRoom(rssclient_scan_room, NULL, rssclient);
785
786         if (GetCount(RSSFetchUrls) > 0)
787         {
788                 pthread_mutex_lock(&RSSQueueMutex);
789                 EVRSSQ_syslog(LOG_DEBUG,
790                                "rssclient starting %d Clients",
791                                GetCount(RSSFetchUrls));
792                 
793                 it = GetNewHashPos(RSSFetchUrls, 0);
794                 while (!server_shutting_down &&
795                        GetNextHashPos(RSSFetchUrls, it, &len, &Key, &vrptr) &&
796                        (vrptr != NULL)) {
797                         rptr = (rss_aggregator *)vrptr;
798                         if (!rss_do_fetching(rptr))
799                                 UnlinkRSSAggregator(rptr);
800                 }
801                 DeleteHashPos(&it);
802                 pthread_mutex_unlock(&RSSQueueMutex);
803         }
804         else
805                 EVRSSQM_syslog(LOG_DEBUG, "Nothing to do.");
806
807         EVRSSQM_syslog(LOG_DEBUG, "rssclient ended\n");
808         return;
809 }
810
811 void rss_cleanup(void)
812 {
813         /* citthread_mutex_destroy(&RSSQueueMutex); TODO */
814         DeleteHash(&RSSFetchUrls);
815         DeleteHash(&RSSQueueRooms);
816 }
817
818 void LogDebugEnableRSSClient(const int n)
819 {
820         RSSClientDebugEnabled = n;
821 }
822
823
824 typedef struct __RSSVetoInfo {
825         StrBuf *ErrMsg;
826         time_t Now;
827         int Veto;
828 }RSSVetoInfo;
829
830 void rssclient_veto_scan_room(struct ctdlroom *qrbuf, void *data, OneRoomNetCfg *OneRNCFG)
831 {
832         RSSVetoInfo *Info = (RSSVetoInfo *) data;
833         const RSSCfgLine *RSSCfg = (RSSCfgLine *)OneRNCFG->NetConfigs[rssclient];
834
835         while (RSSCfg != NULL)
836         {
837                 if ((RSSCfg->last_known_good != 0) &&
838                     (RSSCfg->last_known_good + USETABLE_ANTIEXPIRE < Info->Now))
839                 {
840                         StrBufAppendPrintf(Info->ErrMsg,
841                                            "RSS feed not seen for a %d days:: <",
842                                            (Info->Now - RSSCfg->last_known_good) / (24 * 60 * 60));
843
844                         StrBufAppendBuf(Info->ErrMsg, RSSCfg->Url, 0);
845                         StrBufAppendBufPlain(Info->ErrMsg, HKEY(">\n"), 0);
846                 }
847                 RSSCfg = RSSCfg->next;
848         }
849 }
850
851 int RSSCheckUsetableVeto(StrBuf *ErrMsg)
852 {
853         RSSVetoInfo Info;
854
855         Info.ErrMsg = ErrMsg;
856         Info.Now = time (NULL);
857         Info.Veto = 0;
858
859         CtdlForEachNetCfgRoom(rssclient_veto_scan_room, &Info, rssclient);
860
861         return Info.Veto;;
862 }
863
864
865
866
867 void ParseRSSClientCfgLine(const CfgLineType *ThisOne, StrBuf *Line, const char *LinePos, OneRoomNetCfg *OneRNCFG)
868 {
869         RSSCfgLine *RSSCfg;
870
871         RSSCfg = (RSSCfgLine *) malloc (sizeof(RSSCfgLine));
872         RSSCfg->Url = NewStrBufPlain (NULL, StrLength (Line));
873         
874
875         StrBufExtract_NextToken(RSSCfg->Url, Line, &LinePos, '|');
876         RSSCfg->last_known_good = StrBufExtractNext_long(Line, &LinePos, '|');
877
878
879         RSSCfg->next = (RSSCfgLine *)OneRNCFG->NetConfigs[ThisOne->C];
880         OneRNCFG->NetConfigs[ThisOne->C] = (RoomNetCfgLine*) RSSCfg;
881 }
882
883 void SerializeRSSClientCfgLine(const CfgLineType *ThisOne, StrBuf *OutputBuffer, OneRoomNetCfg *RNCfg, RoomNetCfgLine *data)
884 {
885         RSSCfgLine *RSSCfg = (RSSCfgLine*) data;
886
887         StrBufAppendBufPlain(OutputBuffer, CKEY(ThisOne->Str), 0);
888         StrBufAppendBufPlain(OutputBuffer, HKEY("|"), 0);
889         StrBufAppendBufPlain(OutputBuffer, SKEY(RSSCfg->Url), 0);
890         StrBufAppendPrintf(OutputBuffer, "|%ld\n", RSSCfg->last_known_good);
891 }
892
893 void DeleteRSSClientCfgLine(const CfgLineType *ThisOne, RoomNetCfgLine **data)
894 {
895         RSSCfgLine *RSSCfg = (RSSCfgLine*) *data;
896
897         FreeStrBuf(&RSSCfg->Url);
898         free(*data);
899         *data = NULL;
900 }
901
902
903 CTDL_MODULE_INIT(rssclient)
904 {
905         if (!threading)
906         {
907                 CtdlRegisterTDAPVetoHook (RSSCheckUsetableVeto, CDB_USETABLE, 0);
908
909                 CtdlREGISTERRoomCfgType(rssclient, ParseRSSClientCfgLine, 0, 1, SerializeRSSClientCfgLine, DeleteRSSClientCfgLine);
910                 pthread_mutex_init(&RSSQueueMutex, NULL);
911                 RSSQueueRooms = NewHash(1, lFlathash);
912                 RSSFetchUrls = NewHash(1, NULL);
913                 syslog(LOG_INFO, "%s\n", curl_version());
914                 CtdlRegisterSessionHook(rssclient_scan, EVT_TIMER, PRIO_AGGR + 300);
915                 CtdlRegisterEVCleanupHook(rss_cleanup);
916                 CtdlRegisterDebugFlagHook(HKEY("rssclient"), LogDebugEnableRSSClient, &RSSClientDebugEnabled);
917         }
918         else
919         {
920                 CtdlFillSystemContext(&rss_CC, "rssclient");
921         }
922         return "rssclient";
923 }