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