eeaf361a4f23b9f1fe80c2753f9929dfee608ce0
[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                 if (ri->title != NULL) {
145                         msg->cm_fields['U'] = html_to_ascii(ri->title, strlen(ri->title), 512, 0);
146                 }
147                 msg->cm_fields['T'] = malloc(64);
148                 snprintf(msg->cm_fields['T'], 64, "%ld", ri->pubdate);
149                 if (ri->channel_title != NULL) {
150                         if (!IsEmptyStr(ri->channel_title)) {
151                                 msg->cm_fields['O'] = strdup(ri->channel_title);
152                         }
153                 }
154
155                 msglen = 1024 + strlen(ri->link) + strlen(ri->description) ;
156                 msg->cm_fields['M'] = malloc(msglen);
157                 snprintf(msg->cm_fields['M'], msglen,
158                         "Content-type: text/html\r\n\r\n"
159                         "<html><body>\n"
160                         "%s<br><br>\n"
161                         "<a href=\"%s\">%s</a>\n"
162                         "</body></html>\n"
163                         ,
164                         ri->description,
165                         ri->link, ri->link
166                 );
167
168                 CtdlSubmitMsg(msg, recp, NULL, 0);
169                 CtdlFreeMessage(msg);
170
171                 /* write the uidl to the use table so we don't store this item again */
172                 strcpy(ut.ut_msgid, utmsgid);
173                 ut.ut_timestamp = time(NULL);
174                 cdb_store(CDB_USETABLE, utmsgid, strlen(utmsgid), &ut, sizeof(struct UseTable) );
175         }
176         free_recipients(recp);
177 }
178
179
180
181 /*
182  * Convert an RDF/RSS datestamp into a time_t
183  */
184 time_t rdf_parsedate(char *p)
185 {
186         struct tm tm;
187         time_t t = 0;
188
189         if (!p) return 0L;
190         if (strlen(p) < 10) return 0L;
191
192         memset(&tm, 0, sizeof tm);
193
194         /* YYYY-MM-DDTHH:MM format...
195          */
196         if ( (p[4] == '-') && (p[7] == '-') ) {
197                 tm.tm_year = atoi(&p[0]) - 1900;
198                 tm.tm_mon = atoi(&p[5]) - 1;
199                 tm.tm_mday = atoi(&p[8]);
200                 if ( (p[10] == 'T') && (p[13] == ':') ) {
201                         tm.tm_hour = atoi(&p[11]);
202                         tm.tm_min = atoi(&p[14]);
203                 }
204                 return mktime(&tm);
205         }
206
207         /* hmm... try RFC822 date stamp format */
208
209         t = parsedate(p);
210         if (t > 0) return(t);
211
212         /* yeesh.  ok, just return the current date and time. */
213         return(time(NULL));
214 }
215
216
217
218 void rss_xml_start(void *data, const char *supplied_el, const char **attr) {
219         struct rss_item *ri = (struct rss_item *) data;
220         char el[256];
221         char *sep = NULL;
222
223         /* Axe the namespace, we don't care about it */
224         safestrncpy(el, supplied_el, sizeof el);
225         while (sep = strchr(el, ':'), sep) {
226                 strcpy(el, ++sep);
227         }
228
229         if (!strcasecmp(el, "item")) {
230                 ++ri->item_tag_nesting;
231
232                 /* Initialize the feed item data structure */
233                 if (ri->guid != NULL) free(ri->guid);
234                 ri->guid = NULL;
235                 if (ri->title != NULL) free(ri->title);
236                 ri->title = NULL;
237                 if (ri->link != NULL) free(ri->link);
238                 ri->link = NULL;
239                 if (ri->description != NULL) free(ri->description);
240                 ri->description = NULL;
241
242                 /* Throw away any existing character data */
243                 if (ri->chardata_len > 0) {
244                         free(ri->chardata);
245                         ri->chardata = 0;
246                         ri->chardata_len = 0;
247                 }
248         }
249
250
251
252 }
253
254 void rss_xml_end(void *data, const char *supplied_el) {
255         struct rss_item *ri = (struct rss_item *) data;
256         char el[256];
257         char *sep = NULL;
258
259         /* Axe the namespace, we don't care about it */
260         safestrncpy(el, supplied_el, sizeof el);
261         while (sep = strchr(el, ':'), sep) {
262                 strcpy(el, ++sep);
263         }
264
265         if ( (!strcasecmp(el, "title")) && (ri->item_tag_nesting == 0) && (ri->chardata != NULL) ) {
266                 safestrncpy(ri->channel_title, ri->chardata, sizeof ri->channel_title);
267                 striplt(ri->channel_title);
268         }
269
270         if ( (!strcasecmp(el, "guid")) && (ri->chardata != NULL) ) {
271                 if (ri->guid != NULL) free(ri->guid);
272                 striplt(ri->chardata);
273                 ri->guid = strdup(ri->chardata);
274         }
275
276         if ( (!strcasecmp(el, "title")) && (ri->chardata != NULL) ) {
277                 if (ri->title != NULL) free(ri->title);
278                 striplt(ri->chardata);
279                 ri->title = strdup(ri->chardata);
280         }
281
282         if ( (!strcasecmp(el, "link")) && (ri->chardata != NULL) ) {
283                 if (ri->link != NULL) free(ri->link);
284                 striplt(ri->chardata);
285                 ri->link = strdup(ri->chardata);
286         }
287
288         if ( (!strcasecmp(el, "description")) && (ri->chardata != NULL) ) {
289                 if (ri->description != NULL) free(ri->description);
290                 ri->description = strdup(ri->chardata);
291         }
292
293         if ( ((!strcasecmp(el, "pubdate")) || (!strcasecmp(el, "date"))) && (ri->chardata != NULL) ) {
294                 striplt(ri->chardata);
295                 ri->pubdate = rdf_parsedate(ri->chardata);
296         }
297
298         if (!strcasecmp(el, "item")) {
299                 --ri->item_tag_nesting;
300                 rss_save_item(ri);
301         }
302
303         if ( (!strcasecmp(el, "rss")) || (!strcasecmp(el, "rdf")) ) {
304                 CtdlLogPrintf(CTDL_DEBUG, "End of feed detected.  Closing parser.\n");
305                 ri->done_parsing = 1;
306         }
307
308         if (ri->chardata_len > 0) {
309                 free(ri->chardata);
310                 ri->chardata = 0;
311                 ri->chardata_len = 0;
312         }
313
314 }
315
316
317 /*
318  * This callback stores up the data which appears in between tags.
319  */
320 void rss_xml_chardata(void *data, const XML_Char *s, int len) {
321         struct rss_item *ri = (struct rss_item *) data;
322         int old_len;
323         int new_len;
324         char *new_buffer;
325
326         old_len = ri->chardata_len;
327         new_len = old_len + len;
328         new_buffer = realloc(ri->chardata, new_len + 1);
329         if (new_buffer != NULL) {
330                 memcpy(&new_buffer[old_len], s, len);
331                 new_buffer[new_len] = 0;
332                 ri->chardata = new_buffer;
333                 ri->chardata_len = new_len;
334         }
335 }
336
337
338
339 /*
340  * Callback function for passing libcurl's output to expat for parsing
341  */
342 size_t rss_libcurl_callback(void *ptr, size_t size, size_t nmemb, void *stream)
343 {
344         XML_Parse((XML_Parser)stream, ptr, (size * nmemb), 0);
345         return (size*nmemb);
346 }
347
348
349
350 /*
351  * Begin a feed parse
352  */
353 void rss_do_fetching(char *url, char *rooms) {
354         struct rss_item ri;
355         XML_Parser xp;
356
357         CURL *curl;
358         CURLcode res;
359         char errmsg[1024] = "";
360
361         CtdlLogPrintf(CTDL_DEBUG, "Fetching RSS feed <%s>\n", url);
362
363         curl = curl_easy_init();
364         if (!curl) {
365                 CtdlLogPrintf(CTDL_ALERT, "Unable to initialize libcurl.\n");
366                 return;
367         }
368
369         xp = XML_ParserCreateNS("UTF-8", ':');
370         if (!xp) {
371                 CtdlLogPrintf(CTDL_ALERT, "Cannot create XML parser!\n");
372                 curl_easy_cleanup(curl);
373                 return;
374         }
375
376         curl_easy_setopt(curl, CURLOPT_URL, url);
377         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
378         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
379         curl_easy_setopt(curl, CURLOPT_WRITEDATA, xp);
380         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, rss_libcurl_callback);
381         curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
382         curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
383         curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
384         if (!IsEmptyStr(config.c_ip_addr)) {
385                 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
386         }
387
388         memset(&ri, 0, sizeof(struct rss_item));
389         ri.roomlist = rooms;
390         XML_SetElementHandler(xp, rss_xml_start, rss_xml_end);
391         XML_SetCharacterDataHandler(xp, rss_xml_chardata);
392         XML_SetUserData(xp, &ri);
393
394         if (CtdlThreadCheckStop())
395         {
396                 XML_ParserFree(xp);
397                 curl_easy_cleanup(curl);
398                 return;
399         }
400         
401         if (CtdlThreadCheckStop())
402                 goto shutdown ;
403
404         res = curl_easy_perform(curl);
405         if (res) {
406                 CtdlLogPrintf(CTDL_ALERT, "libcurl error %d: %s\n", res, errmsg);
407         }
408
409         if (CtdlThreadCheckStop())
410                 goto shutdown ;
411
412         if (ri.done_parsing == 0) XML_Parse(xp, "", 0, 1);
413
414
415 shutdown:
416         curl_easy_cleanup(curl);
417         XML_ParserFree(xp);
418
419         /* Free the feed item data structure */
420         if (ri.guid != NULL) free(ri.guid);
421         ri.guid = NULL;
422         if (ri.title != NULL) free(ri.title);
423         ri.title = NULL;
424         if (ri.link != NULL) free(ri.link);
425         ri.link = NULL;
426         if (ri.description != NULL) free(ri.description);
427         ri.description = NULL;
428         if (ri.chardata_len > 0) {
429                 free(ri.chardata);
430                 ri.chardata = 0;
431                 ri.chardata_len = 0;
432         }
433 }
434
435
436 /*
437  * Scan a room's netconfig to determine whether it is requesting any RSS feeds
438  */
439 void rssclient_scan_room(struct ctdlroom *qrbuf, void *data)
440 {
441         char filename[PATH_MAX];
442         char buf[1024];
443         char instr[32];
444         FILE *fp;
445         char feedurl[256];
446         struct rssnetcfg *rncptr = NULL;
447         struct rssnetcfg *use_this_rncptr = NULL;
448         int len = 0;
449         char *ptr = NULL;
450
451         assoc_file_name(filename, sizeof filename, qrbuf, ctdl_netcfg_dir);
452
453         if (CtdlThreadCheckStop())
454                 return;
455                 
456         /* Only do net processing for rooms that have netconfigs */
457         fp = fopen(filename, "r");
458         if (fp == NULL) {
459                 return;
460         }
461
462         while (fgets(buf, sizeof buf, fp) != NULL && !CtdlThreadCheckStop()) {
463                 buf[strlen(buf)-1] = 0;
464
465                 extract_token(instr, buf, 0, '|', sizeof instr);
466                 if (!strcasecmp(instr, "rssclient")) {
467
468                         use_this_rncptr = NULL;
469
470                         extract_token(feedurl, buf, 1, '|', sizeof feedurl);
471
472                         /* If any other rooms have requested the same feed, then we will just add this
473                          * room to the target list for that client request.
474                          */
475                         for (rncptr=rnclist; rncptr!=NULL; rncptr=rncptr->next) {
476                                 if (!strcmp(rncptr->url, feedurl)) {
477                                         use_this_rncptr = rncptr;
478                                 }
479                         }
480
481                         /* Otherwise create a new client request */
482                         if (use_this_rncptr == NULL) {
483                                 rncptr = (struct rssnetcfg *) malloc(sizeof(struct rssnetcfg));
484                                 if (rncptr != NULL) {
485                                         rncptr->next = rnclist;
486                                         safestrncpy(rncptr->url, feedurl, sizeof rncptr->url);
487                                         rncptr->rooms = NULL;
488                                         rnclist = rncptr;
489                                         use_this_rncptr = rncptr;
490                                 }
491                         }
492
493                         /* Add the room name to the request */
494                         if (use_this_rncptr != NULL) {
495                                 if (use_this_rncptr->rooms == NULL) {
496                                         rncptr->rooms = strdup(qrbuf->QRname);
497                                 }
498                                 else {
499                                         len = strlen(use_this_rncptr->rooms) + strlen(qrbuf->QRname) + 5;
500                                         ptr = realloc(use_this_rncptr->rooms, len);
501                                         if (ptr != NULL) {
502                                                 strcat(ptr, "|");
503                                                 strcat(ptr, qrbuf->QRname);
504                                                 use_this_rncptr->rooms = ptr;
505                                         }
506                                 }
507                         }
508                 }
509
510         }
511
512         fclose(fp);
513
514 }
515
516 /*
517  * Scan for rooms that have RSS client requests configured
518  */
519 void *rssclient_scan(void *args) {
520         static time_t last_run = 0L;
521         static int doing_rssclient = 0;
522         struct rssnetcfg *rptr = NULL;
523         struct CitContext rssclientCC;
524
525         /* Give this thread its own private CitContext */
526         CtdlFillPrivateContext(&rssclientCC, "rssclient");
527         citthread_setspecific(MyConKey, (void *)&rssclientCC );
528
529         CtdlThreadAllocTSD();
530
531         /*
532          * This is a simple concurrency check to make sure only one rssclient run
533          * is done at a time.  We could do this with a mutex, but since we
534          * don't really require extremely fine granularity here, we'll do it
535          * with a static variable instead.
536          */
537         if (doing_rssclient) return NULL;
538         doing_rssclient = 1;
539
540         CtdlLogPrintf(CTDL_DEBUG, "rssclient started\n");
541         ForEachRoom(rssclient_scan_room, NULL);
542
543         while (rnclist != NULL && !CtdlThreadCheckStop()) {
544                 rss_do_fetching(rnclist->url, rnclist->rooms);
545                 rptr = rnclist;
546                 rnclist = rnclist->next;
547                 if (rptr->rooms != NULL) free(rptr->rooms);
548                 free(rptr);
549         }
550
551         CtdlLogPrintf(CTDL_DEBUG, "rssclient ended\n");
552         last_run = time(NULL);
553         doing_rssclient = 0;
554         if (!CtdlThreadCheckStop())
555                 CtdlThreadSchedule ("RSS Client", CTDLTHREAD_BIGSTACK, rssclient_scan, NULL, last_run + config.c_net_freq);
556         else
557                 CtdlLogPrintf(CTDL_DEBUG, "rssclient: Task STOPPED.\n");
558         return NULL;
559 }
560
561
562 CTDL_MODULE_INIT(rssclient)
563 {
564         if (threading)
565         {
566                 CtdlLogPrintf(CTDL_INFO, "%s\n", curl_version());
567                 CtdlThreadSchedule ("RSS Client", CTDLTHREAD_BIGSTACK, rssclient_scan, NULL, 0);
568         }
569         /* return our Subversion id for the Log */
570         return "$Id: serv_rssclient.c 5652 2007-10-29 20:14:48Z ajc $";
571 }