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