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