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