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