Now we name all the private contexts.
[citadel.git] / citadel / modules / rssclient / serv_rssclient.c
1 /*
2  * $Id: serv_rssclient.c 5652 2007-10-29 20:14:48Z ajc $
3  *
4  * Bring external RSS feeds into rooms.
5  *
6  */
7
8 #include <stdlib.h>
9 #include <unistd.h>
10 #include <stdio.h>
11
12 #if TIME_WITH_SYS_TIME
13 # include <sys/time.h>
14 # include <time.h>
15 #else
16 # if HAVE_SYS_TIME_H
17 #  include <sys/time.h>
18 # else
19 #  include <time.h>
20 # endif
21 #endif
22
23 #include <ctype.h>
24 #include <string.h>
25 #include <errno.h>
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <expat.h>
29 #include <curl/curl.h>
30 #include <libcitadel.h>
31 #include "citadel.h"
32 #include "server.h"
33 #include "citserver.h"
34 #include "support.h"
35 #include "config.h"
36 #include "threads.h"
37 #include "room_ops.h"
38 #include "ctdl_module.h"
39 #include "clientsocket.h"
40 #include "msgbase.h"
41 #include "parsedate.h"
42 #include "database.h"
43 #include "citadel_dirs.h"
44 #include "md5.h"
45
46
47 struct rssnetcfg {
48         struct rssnetcfg *next;
49         char url[256];
50         char *rooms;
51 };
52
53 struct rss_item {
54         char *chardata;
55         int chardata_len;
56         char *roomlist;
57         int done_parsing;
58         char *guid;
59         char *title;
60         char *link;
61         char *description;
62         time_t pubdate;
63         char channel_title[256];
64         int item_tag_nesting;
65 };
66
67 struct rssnetcfg *rnclist = NULL;
68
69
70 /*
71  * Commit a fetched and parsed RSS item to disk
72  */
73 void rss_save_item(struct rss_item *ri) {
74
75         struct MD5Context md5context;
76         u_char rawdigest[MD5_DIGEST_LEN];
77         int i;
78         char utmsgid[SIZ];
79         struct cdbdata *cdbut;
80         struct UseTable ut;
81         struct CtdlMessage *msg;
82         struct recptypes *recp = NULL;
83         int msglen = 0;
84
85         recp = (struct recptypes *) malloc(sizeof(struct recptypes));
86         if (recp == NULL) return;
87         memset(recp, 0, sizeof(struct recptypes));
88         recp->recp_room = strdup(ri->roomlist);
89         recp->num_room = num_tokens(ri->roomlist, '|');
90         recp->recptypes_magic = RECPTYPES_MAGIC;
91    
92         /* Construct a GUID to use in the S_USETABLE table.
93          * If one is not present in the item itself, make one up.
94          */
95         if (ri->guid != NULL) {
96                 snprintf(utmsgid, sizeof utmsgid, "rss/%s", ri->guid);
97         }
98         else {
99                 MD5Init(&md5context);
100                 if (ri->title != NULL) {
101                         MD5Update(&md5context, (unsigned char*)ri->title, strlen(ri->title));
102                 }
103                 if (ri->link != NULL) {
104                         MD5Update(&md5context, (unsigned char*)ri->link, strlen(ri->link));
105                 }
106                 MD5Final(rawdigest, &md5context);
107                 for (i=0; i<MD5_DIGEST_LEN; i++) {
108                         sprintf(&utmsgid[i*2], "%02X", (unsigned char) (rawdigest[i] & 0xff));
109                         utmsgid[i*2] = tolower(utmsgid[i*2]);
110                         utmsgid[(i*2)+1] = tolower(utmsgid[(i*2)+1]);
111                 }
112                 strcat(utmsgid, "_rss2ctdl");
113         }
114
115         /* Find out if we've already seen this item */
116         cdbut = cdb_fetch(CDB_USETABLE, utmsgid, strlen(utmsgid));
117         if (cdbut != NULL) {
118                 /* Item has already been seen */
119                 CtdlLogPrintf(CTDL_DEBUG, "%s has already been seen\n", utmsgid);
120                 cdb_free(cdbut);
121
122                 /* rewrite the record anyway, to update the timestamp */
123                 strcpy(ut.ut_msgid, utmsgid);
124                 ut.ut_timestamp = time(NULL);
125                 cdb_store(CDB_USETABLE, utmsgid, strlen(utmsgid), &ut, sizeof(struct UseTable) );
126         }
127         else {
128                 /* Item has not been seen, so save it. */
129
130                 if (ri->description == NULL) ri->description = strdup("");
131                 for (i=strlen(ri->description); i>=0; --i) {
132                         if (isspace(ri->description[i])) {
133                                 ri->description[i] = ' ';
134                         }
135                 }
136
137                 msg = malloc(sizeof(struct CtdlMessage));
138                 memset(msg, 0, sizeof(struct CtdlMessage));
139                 msg->cm_magic = CTDLMESSAGE_MAGIC;
140                 msg->cm_anon_type = MES_NORMAL;
141                 msg->cm_format_type = FMT_RFC822;
142                 msg->cm_fields['A'] = strdup("rss");
143                 msg->cm_fields['N'] = strdup(NODENAME);
144                 msg->cm_fields['U'] = strdup(ri->title);
145                 msg->cm_fields['T'] = malloc(64);
146                 snprintf(msg->cm_fields['T'], 64, "%ld", ri->pubdate);
147                 if (!IsEmptyStr(ri->channel_title)) {
148                         msg->cm_fields['O'] = strdup(ri->channel_title);
149                 }
150
151                 msglen = 1024 + strlen(ri->link) + strlen(ri->description) ;
152                 msg->cm_fields['M'] = malloc(msglen);
153                 snprintf(msg->cm_fields['M'], msglen,
154                         "Content-type: text/html\r\n\r\n"
155                         "<html><body>\n"
156                         "%s<br><br>\n"
157                         "<a href=\"%s\">%s</a>\n"
158                         "</body></html>\n"
159                         ,
160                         ri->description,
161                         ri->link, ri->link
162                 );
163
164                 CtdlSubmitMsg(msg, recp, NULL, 0);
165                 CtdlFreeMessage(msg);
166
167                 /* write the uidl to the use table so we don't store this item again */
168                 strcpy(ut.ut_msgid, utmsgid);
169                 ut.ut_timestamp = time(NULL);
170                 cdb_store(CDB_USETABLE, utmsgid, strlen(utmsgid), &ut, sizeof(struct UseTable) );
171         }
172         free_recipients(recp);
173 }
174
175
176
177 /*
178  * Convert an RDF/RSS datestamp into a time_t
179  */
180 time_t rdf_parsedate(char *p)
181 {
182         struct tm tm;
183         time_t t = 0;
184
185         if (!p) return 0L;
186         if (strlen(p) < 10) return 0L;
187
188         memset(&tm, 0, sizeof tm);
189
190         /* YYYY-MM-DDTHH:MM format...
191          */
192         if ( (p[4] == '-') && (p[7] == '-') ) {
193                 tm.tm_year = atoi(&p[0]) - 1900;
194                 tm.tm_mon = atoi(&p[5]) - 1;
195                 tm.tm_mday = atoi(&p[8]);
196                 if ( (p[10] == 'T') && (p[13] == ':') ) {
197                         tm.tm_hour = atoi(&p[11]);
198                         tm.tm_min = atoi(&p[14]);
199                 }
200                 return mktime(&tm);
201         }
202
203         /* hmm... try RFC822 date stamp format */
204
205         t = parsedate(p);
206         if (t > 0) return(t);
207
208         /* yeesh.  ok, just return the current date and time. */
209         return(time(NULL));
210 }
211
212
213
214 void rss_xml_start(void *data, const char *supplied_el, const char **attr) {
215         struct rss_item *ri = (struct rss_item *) data;
216         char el[256];
217         char *sep = NULL;
218
219         /* Axe the namespace, we don't care about it */
220         safestrncpy(el, supplied_el, sizeof el);
221         while (sep = strchr(el, ':'), sep) {
222                 strcpy(el, ++sep);
223         }
224
225         if (!strcasecmp(el, "item")) {
226                 ++ri->item_tag_nesting;
227
228                 /* Initialize the feed item data structure */
229                 if (ri->guid != NULL) free(ri->guid);
230                 ri->guid = NULL;
231                 if (ri->title != NULL) free(ri->title);
232                 ri->title = NULL;
233                 if (ri->link != NULL) free(ri->link);
234                 ri->link = NULL;
235                 if (ri->description != NULL) free(ri->description);
236                 ri->description = NULL;
237
238                 /* Throw away any existing character data */
239                 if (ri->chardata_len > 0) {
240                         free(ri->chardata);
241                         ri->chardata = 0;
242                         ri->chardata_len = 0;
243                 }
244         }
245
246
247
248 }
249
250 void rss_xml_end(void *data, const char *supplied_el) {
251         struct rss_item *ri = (struct rss_item *) data;
252         char el[256];
253         char *sep = NULL;
254
255         /* Axe the namespace, we don't care about it */
256         safestrncpy(el, supplied_el, sizeof el);
257         while (sep = strchr(el, ':'), sep) {
258                 strcpy(el, ++sep);
259         }
260
261         if ( (!strcasecmp(el, "title")) && (ri->item_tag_nesting == 0) && (ri->chardata != NULL) ) {
262                 safestrncpy(ri->channel_title, ri->chardata, sizeof ri->channel_title);
263                 striplt(ri->channel_title);
264         }
265
266         if ( (!strcasecmp(el, "guid")) && (ri->chardata != NULL) ) {
267                 if (ri->guid != NULL) free(ri->guid);
268                 striplt(ri->chardata);
269                 ri->guid = strdup(ri->chardata);
270         }
271
272         if ( (!strcasecmp(el, "title")) && (ri->chardata != NULL) ) {
273                 if (ri->title != NULL) free(ri->title);
274                 striplt(ri->chardata);
275                 ri->title = strdup(ri->chardata);
276         }
277
278         if ( (!strcasecmp(el, "link")) && (ri->chardata != NULL) ) {
279                 if (ri->link != NULL) free(ri->link);
280                 striplt(ri->chardata);
281                 ri->link = strdup(ri->chardata);
282         }
283
284         if ( (!strcasecmp(el, "description")) && (ri->chardata != NULL) ) {
285                 if (ri->description != NULL) free(ri->description);
286                 ri->description = strdup(ri->chardata);
287         }
288
289         if ( ((!strcasecmp(el, "pubdate")) || (!strcasecmp(el, "date"))) && (ri->chardata != NULL) ) {
290                 striplt(ri->chardata);
291                 ri->pubdate = rdf_parsedate(ri->chardata);
292         }
293
294         if (!strcasecmp(el, "item")) {
295                 --ri->item_tag_nesting;
296                 rss_save_item(ri);
297         }
298
299         if ( (!strcasecmp(el, "rss")) || (!strcasecmp(el, "rdf")) ) {
300                 CtdlLogPrintf(CTDL_DEBUG, "End of feed detected.  Closing parser.\n");
301                 ri->done_parsing = 1;
302         }
303
304         if (ri->chardata_len > 0) {
305                 free(ri->chardata);
306                 ri->chardata = 0;
307                 ri->chardata_len = 0;
308         }
309
310 }
311
312
313 /*
314  * This callback stores up the data which appears in between tags.
315  */
316 void rss_xml_chardata(void *data, const XML_Char *s, int len) {
317         struct rss_item *ri = (struct rss_item *) data;
318         int old_len;
319         int new_len;
320         char *new_buffer;
321
322         old_len = ri->chardata_len;
323         new_len = old_len + len;
324         new_buffer = realloc(ri->chardata, new_len + 1);
325         if (new_buffer != NULL) {
326                 memcpy(&new_buffer[old_len], s, len);
327                 new_buffer[new_len] = 0;
328                 ri->chardata = new_buffer;
329                 ri->chardata_len = new_len;
330         }
331 }
332
333
334
335 /*
336  * Callback function for passing libcurl's output to expat for parsing
337  */
338 size_t rss_libcurl_callback(void *ptr, size_t size, size_t nmemb, void *stream)
339 {
340         XML_Parse((XML_Parser)stream, ptr, (size * nmemb), 0);
341         return (size*nmemb);
342 }
343
344
345
346 /*
347  * Begin a feed parse
348  */
349 void rss_do_fetching(char *url, char *rooms) {
350         struct rss_item ri;
351         XML_Parser xp;
352
353         CURL *curl;
354         CURLcode res;
355         char errmsg[1024] = "";
356
357         CtdlLogPrintf(CTDL_DEBUG, "Fetching RSS feed <%s>\n", url);
358
359         curl = curl_easy_init();
360         if (!curl) {
361                 CtdlLogPrintf(CTDL_ALERT, "Unable to initialize libcurl.\n");
362                 return;
363         }
364
365         xp = XML_ParserCreateNS("UTF-8", ':');
366         if (!xp) {
367                 CtdlLogPrintf(CTDL_ALERT, "Cannot create XML parser!\n");
368                 curl_easy_cleanup(curl);
369                 return;
370         }
371
372         curl_easy_setopt(curl, CURLOPT_URL, url);
373         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
374         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
375         curl_easy_setopt(curl, CURLOPT_WRITEDATA, xp);
376         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, rss_libcurl_callback);
377         curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
378         curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
379         curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
380         if (!IsEmptyStr(config.c_ip_addr)) {
381                 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
382         }
383
384         memset(&ri, 0, sizeof(struct rss_item));
385         ri.roomlist = rooms;
386         XML_SetElementHandler(xp, rss_xml_start, rss_xml_end);
387         XML_SetCharacterDataHandler(xp, rss_xml_chardata);
388         XML_SetUserData(xp, &ri);
389
390         if (CtdlThreadCheckStop())
391         {
392                 XML_ParserFree(xp);
393                 curl_easy_cleanup(curl);
394                 return;
395         }
396         
397         if (CtdlThreadCheckStop())
398                 goto shutdown ;
399
400         res = curl_easy_perform(curl);
401         if (res) {
402                 CtdlLogPrintf(CTDL_ALERT, "libcurl error %d: %s\n", res, errmsg);
403         }
404
405         if (CtdlThreadCheckStop())
406                 goto shutdown ;
407
408         if (ri.done_parsing == 0) XML_Parse(xp, "", 0, 1);
409
410
411 shutdown:
412         curl_easy_cleanup(curl);
413         XML_ParserFree(xp);
414
415         /* Free the feed item data structure */
416         if (ri.guid != NULL) free(ri.guid);
417         ri.guid = NULL;
418         if (ri.title != NULL) free(ri.title);
419         ri.title = NULL;
420         if (ri.link != NULL) free(ri.link);
421         ri.link = NULL;
422         if (ri.description != NULL) free(ri.description);
423         ri.description = NULL;
424         if (ri.chardata_len > 0) {
425                 free(ri.chardata);
426                 ri.chardata = 0;
427                 ri.chardata_len = 0;
428         }
429 }
430
431
432 /*
433  * Scan a room's netconfig to determine whether it is requesting any RSS feeds
434  */
435 void rssclient_scan_room(struct ctdlroom *qrbuf, void *data)
436 {
437         char filename[PATH_MAX];
438         char buf[1024];
439         char instr[32];
440         FILE *fp;
441         char feedurl[256];
442         struct rssnetcfg *rncptr = NULL;
443         struct rssnetcfg *use_this_rncptr = NULL;
444         int len = 0;
445         char *ptr = NULL;
446
447         assoc_file_name(filename, sizeof filename, qrbuf, ctdl_netcfg_dir);
448
449         if (CtdlThreadCheckStop())
450                 return;
451                 
452         /* Only do net processing for rooms that have netconfigs */
453         fp = fopen(filename, "r");
454         if (fp == NULL) {
455                 return;
456         }
457
458         while (fgets(buf, sizeof buf, fp) != NULL && !CtdlThreadCheckStop()) {
459                 buf[strlen(buf)-1] = 0;
460
461                 extract_token(instr, buf, 0, '|', sizeof instr);
462                 if (!strcasecmp(instr, "rssclient")) {
463
464                         use_this_rncptr = NULL;
465
466                         extract_token(feedurl, buf, 1, '|', sizeof feedurl);
467
468                         /* If any other rooms have requested the same feed, then we will just add this
469                          * room to the target list for that client request.
470                          */
471                         for (rncptr=rnclist; rncptr!=NULL; rncptr=rncptr->next) {
472                                 if (!strcmp(rncptr->url, feedurl)) {
473                                         use_this_rncptr = rncptr;
474                                 }
475                         }
476
477                         /* Otherwise create a new client request */
478                         if (use_this_rncptr == NULL) {
479                                 rncptr = (struct rssnetcfg *) malloc(sizeof(struct rssnetcfg));
480                                 if (rncptr != NULL) {
481                                         rncptr->next = rnclist;
482                                         safestrncpy(rncptr->url, feedurl, sizeof rncptr->url);
483                                         rncptr->rooms = NULL;
484                                         rnclist = rncptr;
485                                         use_this_rncptr = rncptr;
486                                 }
487                         }
488
489                         /* Add the room name to the request */
490                         if (use_this_rncptr != NULL) {
491                                 if (use_this_rncptr->rooms == NULL) {
492                                         rncptr->rooms = strdup(qrbuf->QRname);
493                                 }
494                                 else {
495                                         len = strlen(use_this_rncptr->rooms) + strlen(qrbuf->QRname) + 5;
496                                         ptr = realloc(use_this_rncptr->rooms, len);
497                                         if (ptr != NULL) {
498                                                 strcat(ptr, "|");
499                                                 strcat(ptr, qrbuf->QRname);
500                                                 use_this_rncptr->rooms = ptr;
501                                         }
502                                 }
503                         }
504                 }
505
506         }
507
508         fclose(fp);
509
510 }
511
512 /*
513  * Scan for rooms that have RSS client requests configured
514  */
515 void *rssclient_scan(void *args) {
516         static time_t last_run = 0L;
517         static int doing_rssclient = 0;
518         struct rssnetcfg *rptr = NULL;
519         struct CitContext rssclientCC;
520
521         /* Give this thread its own private CitContext */
522         CtdlFillPrivateContext(&rssclientCC, "rssclient");
523         citthread_setspecific(MyConKey, (void *)&rssclientCC );
524
525         CtdlThreadAllocTSD();
526
527         /*
528          * This is a simple concurrency check to make sure only one rssclient run
529          * is done at a time.  We could do this with a mutex, but since we
530          * don't really require extremely fine granularity here, we'll do it
531          * with a static variable instead.
532          */
533         if (doing_rssclient) return NULL;
534         doing_rssclient = 1;
535
536         CtdlLogPrintf(CTDL_DEBUG, "rssclient started\n");
537         ForEachRoom(rssclient_scan_room, NULL);
538
539         while (rnclist != NULL && !CtdlThreadCheckStop()) {
540                 rss_do_fetching(rnclist->url, rnclist->rooms);
541                 rptr = rnclist;
542                 rnclist = rnclist->next;
543                 if (rptr->rooms != NULL) free(rptr->rooms);
544                 free(rptr);
545         }
546
547         CtdlLogPrintf(CTDL_DEBUG, "rssclient ended\n");
548         last_run = time(NULL);
549         doing_rssclient = 0;
550         if (!CtdlThreadCheckStop())
551                 CtdlThreadSchedule ("RSS Client", CTDLTHREAD_BIGSTACK, rssclient_scan, NULL, last_run + config.c_net_freq);
552         else
553                 CtdlLogPrintf(CTDL_DEBUG, "rssclient: Task STOPPED.\n");
554         return NULL;
555 }
556
557
558 CTDL_MODULE_INIT(rssclient)
559 {
560         if (threading)
561         {
562                 CtdlLogPrintf(CTDL_INFO, "%s\n", curl_version());
563                 CtdlThreadSchedule ("RSS Client", CTDLTHREAD_BIGSTACK, rssclient_scan, NULL, 0);
564         }
565         /* return our Subversion id for the Log */
566         return "$Id: serv_rssclient.c 5652 2007-10-29 20:14:48Z ajc $";
567 }