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