ups, more places to reset the time we ran last time.
[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 "msgbase.h"
52 #include "parsedate.h"
53 #include "database.h"
54 #include "citadel_dirs.h"
55 #include "md5.h"
56 #include "context.h"
57 #include "event_client.h"
58 #include "rss_atom_parser.h"
59
60
61 #define TMP_MSGDATA 0xFF
62 #define TMP_SHORTER_URL_OFFSET 0xFE
63 #define TMP_SHORTER_URLS 0xFD
64
65 time_t last_run = 0L;
66
67 pthread_mutex_t RSSQueueMutex; /* locks the access to the following vars: */
68 HashList *RSSQueueRooms = NULL; /* rss_room_counter */
69 HashList *RSSFetchUrls = NULL; /* -> rss_aggregator; ->RefCount access to be locked too. */
70
71 eNextState RSSAggregatorTerminate(AsyncIO *IO);
72
73 struct CitContext rss_CC;
74
75 struct rssnetcfg *rnclist = NULL;
76 void AppendLink(StrBuf *Message, StrBuf *link, StrBuf *LinkTitle, const char *Title)
77 {
78         if (StrLength(link) > 0)
79         {
80                 StrBufAppendBufPlain(Message, HKEY("<a href=\""), 0);
81                 StrBufAppendBuf(Message, link, 0);
82                 StrBufAppendBufPlain(Message, HKEY("\">"), 0);
83                 if (StrLength(LinkTitle) > 0)
84                         StrBufAppendBuf(Message, LinkTitle, 0);
85                 else if ((Title != NULL) && !IsEmptyStr(Title))
86                         StrBufAppendBufPlain(Message, Title, -1, 0);
87                 else
88                         StrBufAppendBuf(Message, link, 0);
89                 StrBufAppendBufPlain(Message, HKEY("</a><br>\n"), 0);
90         }
91 }
92 typedef struct __networker_save_message {
93         AsyncIO IO;
94         struct CtdlMessage *Msg;
95         struct recptypes *recp;
96         rss_aggregator *Cfg;
97         StrBuf *MsgGUID;
98         StrBuf *Message;
99         struct UseTable ut;
100 } networker_save_message;
101
102
103 void DeleteRoomReference(long QRnumber)
104 {
105         HashPos *At;
106         long HKLen;
107         const char *HK;
108         void *vData = NULL;
109         rss_room_counter *pRoomC;
110
111         At = GetNewHashPos(RSSQueueRooms, 0);
112
113         GetHashPosFromKey(RSSQueueRooms, LKEY(QRnumber), At);
114         GetHashPos(RSSQueueRooms, At, &HKLen, &HK, &vData);
115         if (vData != NULL)
116         {
117                 pRoomC = (rss_room_counter *) vData;
118                 pRoomC->count --;
119                 if (pRoomC->count == 0)
120                         DeleteEntryFromHash(RSSQueueRooms, At);
121         }
122         DeleteHashPos(&At);
123 }
124
125 void UnlinkRooms(rss_aggregator *Cfg)
126 {
127         
128         DeleteRoomReference(Cfg->QRnumber);
129         if (Cfg->OtherQRnumbers != NULL)
130         {
131                 long HKLen;
132                 const char *HK;
133                 HashPos *At;
134                 void *vData;
135
136                 At = GetNewHashPos(Cfg->OtherQRnumbers, 0);
137                 while (GetNextHashPos(Cfg->OtherQRnumbers, At, &HKLen, &HK, &vData) && 
138                        (vData != NULL))
139                 {
140                         long *lData = (long*) vData;
141                         DeleteRoomReference(*lData);
142                 }
143 /*
144                 if (server_shutting_down)
145                         break; / * TODO */
146
147                 DeleteHashPos(&At);
148         }
149 }
150
151 void UnlinkRSSAggregator(rss_aggregator *Cfg)
152 {
153         HashPos *At;
154
155         UnlinkRooms(Cfg);
156
157         At = GetNewHashPos(RSSFetchUrls, 0);
158         if (GetHashPosFromKey(RSSFetchUrls, SKEY(Cfg->Url), At) == 0)
159         {
160                 DeleteEntryFromHash(RSSFetchUrls, At);
161         }
162         DeleteHashPos(&At);
163         last_run = time(NULL);
164 }
165
166 eNextState FreeNetworkSaveMessage (AsyncIO *IO)
167 {
168         networker_save_message *Ctx = (networker_save_message *) IO->Data;
169
170         pthread_mutex_lock(&RSSQueueMutex);
171         Ctx->Cfg->RefCount --;
172
173         if (Ctx->Cfg->RefCount == 0)
174         {
175                 UnlinkRSSAggregator(Ctx->Cfg);
176
177         }
178         pthread_mutex_unlock(&RSSQueueMutex);
179
180         CtdlFreeMessage(Ctx->Msg);
181         free_recipients(Ctx->recp);
182         FreeStrBuf(&Ctx->Message);
183         FreeStrBuf(&Ctx->MsgGUID);
184         free(Ctx);
185         last_run = time(NULL);
186         return eAbort;
187 }
188
189 eNextState AbortNetworkSaveMessage (AsyncIO *IO)
190 {
191         return eAbort; ///TODO
192 }
193
194 eNextState RSSSaveMessage(AsyncIO *IO)
195 {
196         networker_save_message *Ctx = (networker_save_message *) IO->Data;
197
198         Ctx->Msg->cm_fields['M'] = SmashStrBuf(&Ctx->Message);
199
200         CtdlSubmitMsg(Ctx->Msg, Ctx->recp, NULL, 0);
201
202         /* write the uidl to the use table so we don't store this item again */
203         cdb_store(CDB_USETABLE, SKEY(Ctx->MsgGUID), &Ctx->ut, sizeof(struct UseTable) );
204
205         return eTerminateConnection;
206 }
207
208 eNextState RSS_FetchNetworkUsetableEntry(AsyncIO *IO)
209 {
210         struct cdbdata *cdbut;
211         networker_save_message *Ctx = (networker_save_message *) IO->Data;
212
213         /* Find out if we've already seen this item */
214         strcpy(Ctx->ut.ut_msgid, ChrPtr(Ctx->MsgGUID)); /// TODO
215         Ctx->ut.ut_timestamp = time(NULL);
216
217         cdbut = cdb_fetch(CDB_USETABLE, SKEY(Ctx->MsgGUID));
218 #ifndef DEBUG_RSS
219         if (cdbut != NULL) {
220                 /* Item has already been seen */
221                 syslog(LOG_DEBUG, "%s has already been seen\n", ChrPtr(Ctx->MsgGUID));
222                 cdb_free(cdbut);
223
224                 /* rewrite the record anyway, to update the timestamp */
225                 cdb_store(CDB_USETABLE, 
226                           SKEY(Ctx->MsgGUID), 
227                           &Ctx->ut, sizeof(struct UseTable) );
228                 return eAbort;
229         }
230         else
231 #endif
232         {
233                 NextDBOperation(IO, RSSSaveMessage);
234                 return eSendMore;
235         }
236 }
237 void RSSQueueSaveMessage(struct CtdlMessage *Msg, struct recptypes *recp, StrBuf *MsgGUID, StrBuf *MessageBody, rss_aggregator *Cfg)
238 {
239         networker_save_message *Ctx;
240
241         Ctx = (networker_save_message *) malloc(sizeof(networker_save_message));
242         memset(Ctx, 0, sizeof(networker_save_message));
243         
244         Ctx->MsgGUID = MsgGUID;
245         Ctx->Message = MessageBody;
246         Ctx->Msg = Msg;
247         Ctx->Cfg = Cfg;
248         Ctx->recp = recp;
249         Ctx->IO.Data = Ctx;
250         Ctx->IO.CitContext = CloneContext(&rss_CC);
251         Ctx->IO.Terminate = FreeNetworkSaveMessage;
252         Ctx->IO.ShutdownAbort = AbortNetworkSaveMessage;
253         QueueDBOperation(&Ctx->IO, RSS_FetchNetworkUsetableEntry);
254 }
255
256
257 /*
258  * Commit a fetched and parsed RSS item to disk
259  */
260 void rss_save_item(rss_item *ri, rss_aggregator *Cfg)
261 {
262
263         struct MD5Context md5context;
264         u_char rawdigest[MD5_DIGEST_LEN];
265         struct CtdlMessage *msg;
266         struct recptypes *recp = NULL;
267         int msglen = 0;
268         StrBuf *Message;
269         StrBuf *guid;
270         StrBuf *Buf;
271
272         recp = (struct recptypes *) malloc(sizeof(struct recptypes));
273         if (recp == NULL) return;
274         memset(recp, 0, sizeof(struct recptypes));
275         Buf = NewStrBufDup(Cfg->rooms);
276         recp->recp_room = SmashStrBuf(&Buf);
277         recp->num_room = Cfg->roomlist_parts;
278         recp->recptypes_magic = RECPTYPES_MAGIC;
279    
280         Cfg->RefCount ++;
281         /* Construct a GUID to use in the S_USETABLE table.
282          * If one is not present in the item itself, make one up.
283          */
284         if (ri->guid != NULL) {
285                 StrBufSpaceToBlank(ri->guid);
286                 StrBufTrim(ri->guid);
287                 guid = NewStrBufPlain(HKEY("rss/"));
288                 StrBufAppendBuf(guid, ri->guid, 0);
289         }
290         else {
291                 MD5Init(&md5context);
292                 if (ri->title != NULL) {
293                         MD5Update(&md5context, (const unsigned char*)ChrPtr(ri->title), StrLength(ri->title));
294                 }
295                 if (ri->link != NULL) {
296                         MD5Update(&md5context, (const unsigned char*)ChrPtr(ri->link), StrLength(ri->link));
297                 }
298                 MD5Final(rawdigest, &md5context);
299                 guid = NewStrBufPlain(NULL, MD5_DIGEST_LEN * 2 + 12 /* _rss2ctdl*/);
300                 StrBufHexEscAppend(guid, NULL, rawdigest, MD5_DIGEST_LEN);
301                 StrBufAppendBufPlain(guid, HKEY("_rss2ctdl"), 0);
302         }
303
304         /* translate Item into message. */
305         syslog(LOG_DEBUG, "RSS: translating item...\n");
306         if (ri->description == NULL) ri->description = NewStrBufPlain(HKEY(""));
307         StrBufSpaceToBlank(ri->description);
308         msg = malloc(sizeof(struct CtdlMessage));
309         memset(msg, 0, sizeof(struct CtdlMessage));
310         msg->cm_magic = CTDLMESSAGE_MAGIC;
311         msg->cm_anon_type = MES_NORMAL;
312         msg->cm_format_type = FMT_RFC822;
313
314         if (ri->guid != NULL) {
315                 msg->cm_fields['E'] = strdup(ChrPtr(ri->guid));
316         }
317
318         if (ri->author_or_creator != NULL) {
319                 char *From;
320                 StrBuf *Encoded = NULL;
321                 int FromAt;
322                         
323                 From = html_to_ascii(ChrPtr(ri->author_or_creator),
324                                      StrLength(ri->author_or_creator), 
325                                      512, 0);
326                 StrBufPlain(ri->author_or_creator, From, -1);
327                 StrBufTrim(ri->author_or_creator);
328                 free(From);
329
330                 FromAt = strchr(ChrPtr(ri->author_or_creator), '@') != NULL;
331                 if (!FromAt && StrLength (ri->author_email) > 0)
332                 {
333                         StrBufRFC2047encode(&Encoded, ri->author_or_creator);
334                         msg->cm_fields['A'] = SmashStrBuf(&Encoded);
335                         msg->cm_fields['P'] = SmashStrBuf(&ri->author_email);
336                 }
337                 else
338                 {
339                         if (FromAt)
340                         {
341                                 msg->cm_fields['A'] = SmashStrBuf(&ri->author_or_creator);
342                                 msg->cm_fields['P'] = strdup(msg->cm_fields['A']);
343                         }
344                         else 
345                         {
346                                 StrBufRFC2047encode(&Encoded, ri->author_or_creator);
347                                 msg->cm_fields['A'] = SmashStrBuf(&Encoded);
348                                 msg->cm_fields['P'] = strdup("rss@localhost");
349
350                         }
351                         if (ri->pubdate <= 0) {
352                                 ri->pubdate = time(NULL);
353                         }
354                 }
355         }
356         else {
357                 msg->cm_fields['A'] = strdup("rss");
358         }
359
360         msg->cm_fields['N'] = strdup(NODENAME);
361         if (ri->title != NULL) {
362                 long len;
363                 char *Sbj;
364                 StrBuf *Encoded, *QPEncoded;
365
366                 QPEncoded = NULL;
367                 StrBufSpaceToBlank(ri->title);
368                 len = StrLength(ri->title);
369                 Sbj = html_to_ascii(ChrPtr(ri->title), len, 512, 0);
370                 len = strlen(Sbj);
371                 if (Sbj[len - 1] == '\n')
372                 {
373                         len --;
374                         Sbj[len] = '\0';
375                 }
376                 Encoded = NewStrBufPlain(Sbj, len);
377                 free(Sbj);
378
379                 StrBufTrim(Encoded);
380                 StrBufRFC2047encode(&QPEncoded, Encoded);
381
382                 msg->cm_fields['U'] = SmashStrBuf(&QPEncoded);
383                 FreeStrBuf(&Encoded);
384         }
385         msg->cm_fields['T'] = malloc(64);
386         snprintf(msg->cm_fields['T'], 64, "%ld", ri->pubdate);
387         if (ri->channel_title != NULL) {
388                 if (StrLength(ri->channel_title) > 0) {
389                         msg->cm_fields['O'] = strdup(ChrPtr(ri->channel_title));
390                 }
391         }
392         if (ri->link == NULL) 
393                 ri->link = NewStrBufPlain(HKEY(""));
394
395 #if 0 /* temporarily disable shorter urls. */
396         msg->cm_fields[TMP_SHORTER_URLS] = GetShorterUrls(ri->description);
397 #endif
398
399         msglen += 1024 + StrLength(ri->link) + StrLength(ri->description) ;
400
401         Message = NewStrBufPlain(NULL, StrLength(ri->description));
402
403         StrBufPlain(Message, HKEY(
404                             "Content-type: text/html; charset=\"UTF-8\"\r\n\r\n"
405                             "<html><body>\n"));
406 #if 0 /* disable shorter url for now. */
407         msg->cm_fields[TMP_SHORTER_URL_OFFSET] = StrLength(Message);
408 #endif
409         StrBufAppendBuf(Message, ri->description, 0);
410         StrBufAppendBufPlain(Message, HKEY("<br><br>\n"), 0);
411
412         AppendLink(Message, ri->link, ri->linkTitle, NULL);
413         AppendLink(Message, ri->reLink, ri->reLinkTitle, "Reply to this");
414         StrBufAppendBufPlain(Message, HKEY("</body></html>\n"), 0);
415
416         RSSQueueSaveMessage(msg, recp, guid, Message, Cfg);
417 }
418
419
420
421 /*
422  * Begin a feed parse
423  */
424 int rss_do_fetching(rss_aggregator *Cfg)
425 {
426         rss_item *ri;
427                 
428         time_t now;
429         AsyncIO *IO;
430
431         now = time(NULL);
432
433         if ((Cfg->next_poll != 0) && (now < Cfg->next_poll))
434                 return 0;
435         Cfg->RefCount = 1;
436
437         ri = (rss_item*) malloc(sizeof(rss_item));
438         memset(ri, 0, sizeof(rss_item));
439         Cfg->Item = ri;
440         IO = &Cfg->IO;
441         IO->CitContext = CloneContext(&rss_CC);
442         IO->Data = Cfg;
443
444
445         syslog(LOG_DEBUG, "Fetching RSS feed <%s>\n", ChrPtr(Cfg->Url));
446         ParseURL(&IO->ConnectMe, Cfg->Url, 80);
447         CurlPrepareURL(IO->ConnectMe);
448
449         if (! evcurl_init(IO, 
450 //                        Ctx, 
451                           NULL,
452                           "Citadel RSS Client",
453                           ParseRSSReply, 
454                           RSSAggregatorTerminate))
455         {
456                 syslog(LOG_DEBUG, "Unable to initialize libcurl.\n");
457                 return 0;
458         }
459
460         evcurl_handle_start(IO);
461         return 1;
462 }
463
464
465 void DeleteRssCfg(void *vptr)
466 {
467         rss_aggregator *rncptr = (rss_aggregator *)vptr;
468
469         FreeStrBuf(&rncptr->Url);
470         FreeStrBuf(&rncptr->rooms);
471         FreeStrBuf(&rncptr->CData);
472         FreeStrBuf(&rncptr->Key);
473         FreeStrBuf(&rncptr->IO.HttpReq.ReplyData);
474         DeleteHash(&rncptr->OtherQRnumbers);
475         FreeURL(&rncptr->IO.ConnectMe);
476
477         if (rncptr->Item != NULL)
478         {
479                 FreeStrBuf(&rncptr->Item->guid);
480                 FreeStrBuf(&rncptr->Item->title);
481                 FreeStrBuf(&rncptr->Item->link);
482                 FreeStrBuf(&rncptr->Item->linkTitle);
483                 FreeStrBuf(&rncptr->Item->reLink);
484                 FreeStrBuf(&rncptr->Item->reLinkTitle);
485                 FreeStrBuf(&rncptr->Item->description);
486                 FreeStrBuf(&rncptr->Item->channel_title);
487                 FreeStrBuf(&rncptr->Item->author_or_creator);
488                 FreeStrBuf(&rncptr->Item->author_url);
489                 FreeStrBuf(&rncptr->Item->author_email);
490
491                 free(rncptr->Item);
492         }
493         free(rncptr);
494 }
495
496 eNextState RSSAggregatorTerminate(AsyncIO *IO)
497 {
498         rss_aggregator *rncptr = (rss_aggregator *)IO->Data;
499         /*
500           HashPos *At;
501           long HKLen;
502           const char *HK;
503           void *vData;
504         */
505         pthread_mutex_lock(&RSSQueueMutex);
506         rncptr->RefCount --;
507         if (rncptr->RefCount == 0)
508         {
509                 UnlinkRSSAggregator(rncptr);
510
511         }
512         pthread_mutex_unlock(&RSSQueueMutex);
513 /*
514         At = GetNewHashPos(RSSFetchUrls, 0);
515
516         pthread_mutex_lock(&RSSQueueMutex);
517         GetHashPosFromKey(RSSFetchUrls, SKEY(rncptr->Url), At);
518         GetHashPos(RSSFetchUrls, At, &HKLen, &HK, &vData);
519         DeleteEntryFromHash(RSSFetchUrls, At);
520         pthread_mutex_unlock(&RSSQueueMutex);
521
522         DeleteHashPos(&At);
523 */
524         return eAbort;
525 }
526
527 /*
528  * Scan a room's netconfig to determine whether it is requesting any RSS feeds
529  */
530 void rssclient_scan_room(struct ctdlroom *qrbuf, void *data)
531 {
532         StrBuf *CfgData=NULL;
533         StrBuf *CfgType;
534         StrBuf *Line;
535         rss_room_counter *Count = NULL;
536         struct stat statbuf;
537         char filename[PATH_MAX];
538         int  fd;
539         int Done;
540         rss_aggregator *rncptr = NULL;
541         rss_aggregator *use_this_rncptr = NULL;
542         void *vptr;
543         const char *CfgPtr, *lPtr;
544         const char *Err;
545
546         pthread_mutex_lock(&RSSQueueMutex);
547         if (GetHash(RSSQueueRooms, LKEY(qrbuf->QRnumber), &vptr))
548         {
549                 syslog(LOG_DEBUG, 
550                               "rssclient: [%ld] %s already in progress.\n", 
551                               qrbuf->QRnumber, 
552                               qrbuf->QRname);
553                 pthread_mutex_unlock(&RSSQueueMutex);
554                 return;
555         }
556         pthread_mutex_unlock(&RSSQueueMutex);
557
558         assoc_file_name(filename, sizeof filename, qrbuf, ctdl_netcfg_dir);
559
560         if (server_shutting_down)
561                 return;
562                 
563         /* Only do net processing for rooms that have netconfigs */
564         fd = open(filename, 0);
565         if (fd <= 0) {
566                 //syslog(LOG_DEBUG, "rssclient: %s no config.\n", qrbuf->QRname);
567                 return;
568         }
569
570         if (server_shutting_down)
571                 return;
572
573         if (fstat(fd, &statbuf) == -1) {
574                 syslog(LOG_DEBUG, "ERROR: could not stat configfile '%s' - %s\n",
575                        filename, strerror(errno));
576                 return;
577         }
578
579         if (server_shutting_down)
580                 return;
581
582         CfgData = NewStrBufPlain(NULL, statbuf.st_size + 1);
583
584         if (StrBufReadBLOB(CfgData, &fd, 1, statbuf.st_size, &Err) < 0) {
585                 close(fd);
586                 FreeStrBuf(&CfgData);
587                 syslog(LOG_DEBUG, "ERROR: reading config '%s' - %s<br>\n",
588                         filename, strerror(errno));
589                 return;
590         }
591         close(fd);
592         if (server_shutting_down)
593                 return;
594         
595         CfgPtr = NULL;
596         CfgType = NewStrBuf();
597         Line = NewStrBufPlain(NULL, StrLength(CfgData));
598         Done = 0;
599         while (!Done)
600         {
601             Done = StrBufSipLine(Line, CfgData, &CfgPtr) == 0;
602             if (StrLength(Line) > 0)
603             {
604                 lPtr = NULL;
605                 StrBufExtract_NextToken(CfgType, Line, &lPtr, '|');
606                 if (!strcasecmp("rssclient", ChrPtr(CfgType)))
607                 {
608                     if (Count == NULL)
609                     {
610                         Count = malloc(sizeof(rss_room_counter));
611                         Count->count = 0;
612                     }
613                     Count->count ++;
614                     rncptr = (rss_aggregator *) malloc(sizeof(rss_aggregator));
615                     memset (rncptr, 0, sizeof(rss_aggregator));
616                     rncptr->roomlist_parts = 1;
617                     rncptr->Url = NewStrBuf();
618                     StrBufExtract_NextToken(rncptr->Url, Line, &lPtr, '|');
619
620                     pthread_mutex_lock(&RSSQueueMutex);
621                     GetHash(RSSFetchUrls, SKEY(rncptr->Url), &vptr);
622                     use_this_rncptr = (rss_aggregator *)vptr;
623                     if (use_this_rncptr != NULL)
624                     {
625                             /* mustn't attach to an active session */
626                             if (use_this_rncptr->RefCount > 0)
627                             {
628                                     DeleteRssCfg(rncptr);
629                                     Count->count--;
630                             }
631                             else 
632                             {
633                                     long *QRnumber;
634                                     StrBufAppendBufPlain(use_this_rncptr->rooms, 
635                                                          qrbuf->QRname, 
636                                                          -1, 0);
637                                     if (use_this_rncptr->roomlist_parts == 1)
638                                     {
639                                             use_this_rncptr->OtherQRnumbers = NewHash(1, lFlathash);
640                                     }
641                                     QRnumber = (long*)malloc(sizeof(long));
642                                     *QRnumber = qrbuf->QRnumber;
643                                     Put(use_this_rncptr->OtherQRnumbers, LKEY(qrbuf->QRnumber), QRnumber, NULL);
644                                     use_this_rncptr->roomlist_parts++;
645                             }
646                             pthread_mutex_unlock(&RSSQueueMutex);
647
648
649                             FreeStrBuf(&rncptr->Url);       
650                             free(rncptr);
651                             rncptr = NULL;
652                             continue;
653                     }
654                     pthread_mutex_unlock(&RSSQueueMutex);
655
656                     rncptr->ItemType = RSS_UNSET;
657                                 
658                     rncptr->rooms = NewStrBufPlain(qrbuf->QRname, -1);
659
660                     pthread_mutex_lock(&RSSQueueMutex);
661                     Put(RSSFetchUrls, SKEY(rncptr->Url), rncptr, DeleteRssCfg);
662                     pthread_mutex_unlock(&RSSQueueMutex);
663                 }
664             }
665         }
666         if (Count != NULL)
667         {
668                 Count->QRnumber = qrbuf->QRnumber;
669                 pthread_mutex_lock(&RSSQueueMutex);
670                 syslog(LOG_DEBUG, "rssclient: [%ld] %s now starting.\n", 
671                               qrbuf->QRnumber, qrbuf->QRname);
672                 Put(RSSQueueRooms, LKEY(qrbuf->QRnumber), Count, NULL);
673                 pthread_mutex_unlock(&RSSQueueMutex);
674         }
675         FreeStrBuf(&CfgData);
676         FreeStrBuf(&CfgType);
677         FreeStrBuf(&Line);
678 }
679
680 /*
681  * Scan for rooms that have RSS client requests configured
682  */
683 void rssclient_scan(void) {
684         static int doing_rssclient = 0;
685         rss_aggregator *rptr = NULL;
686         void *vrptr = NULL;
687         HashPos  *it;
688         long len;
689         const char *Key;
690
691         /* Run no more than once every 15 minutes. */
692         if ((time(NULL) - last_run) < 900) {
693                 return;
694         }
695
696         /*
697          * This is a simple concurrency check to make sure only one rssclient run
698          * is done at a time.  We could do this with a mutex, but since we
699          * don't really require extremely fine granularity here, we'll do it
700          * with a static variable instead.
701          */
702         if (doing_rssclient) return;
703         doing_rssclient = 1;
704
705         syslog(LOG_DEBUG, "rssclient started\n");
706         CtdlForEachRoom(rssclient_scan_room, NULL);
707
708         pthread_mutex_lock(&RSSQueueMutex);
709
710         it = GetNewHashPos(RSSFetchUrls, 0);
711         while (!server_shutting_down &&
712                GetNextHashPos(RSSFetchUrls, it, &len, &Key, &vrptr) && 
713                (vrptr != NULL)) {
714                 rptr = (rss_aggregator *)vrptr;
715                 if (rptr->RefCount == 0) 
716                         if (!rss_do_fetching(rptr))
717                                 UnlinkRSSAggregator(rptr);
718         }
719         DeleteHashPos(&it);
720         pthread_mutex_unlock(&RSSQueueMutex);
721
722         syslog(LOG_DEBUG, "rssclient ended\n");
723         doing_rssclient = 0;
724         return;
725 }
726
727 void rss_cleanup(void)
728 {
729         /* citthread_mutex_destroy(&RSSQueueMutex); TODO */
730         DeleteHash(&RSSFetchUrls);
731         DeleteHash(&RSSQueueRooms);
732 }
733
734
735 CTDL_MODULE_INIT(rssclient)
736 {
737         if (threading)
738         {
739                 CtdlFillSystemContext(&rss_CC, "rssclient");
740                 pthread_mutex_init(&RSSQueueMutex, NULL);
741                 RSSQueueRooms = NewHash(1, lFlathash);
742                 RSSFetchUrls = NewHash(1, NULL);
743                 syslog(LOG_INFO, "%s\n", curl_version());
744                 CtdlRegisterSessionHook(rssclient_scan, EVT_TIMER);
745                 CtdlRegisterCleanupHook(rss_cleanup);
746         }
747         return "rssclient";
748 }