stable now but there are GIANT PIECES MISSING
[citadel.git] / citadel / modules / rssclient / serv_rssclient.c
1 /*
2  * Bring external RSS and/or Atom feeds into rooms.  This module implements a
3  * very loose parser that scrapes both kinds of feeds and is not picky about
4  * the standards compliance of the source data.
5  *
6  * Copyright (c) 2007-2020 by the citadel.org team
7  *
8  * This program is open source software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License version 3.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  */
16
17 #include <stdlib.h>
18 #include <unistd.h>
19 #include <stdio.h>
20 #include <time.h>
21 #include <ctype.h>
22 #include <string.h>
23 #include <errno.h>
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <expat.h>
27 #include <curl/curl.h>
28 #include <libcitadel.h>
29 #include "citadel.h"
30 #include "server.h"
31 #include "citserver.h"
32 #include "support.h"
33 #include "config.h"
34 #include "threads.h"
35 #include "ctdl_module.h"
36 #include "msgbase.h"
37 #include "parsedate.h"
38 #include "database.h"
39 #include "citadel_dirs.h"
40 #include "context.h"
41 #include "internet_addressing.h"
42
43 struct rssroom {
44         struct rssroom *next;
45         char *room;
46 };
47
48 struct rssurl {
49         struct rssurl *next;
50         char *url;
51         struct rssroom *rooms;
52 };
53
54 struct rssparser {
55         StrBuf *CData;
56         struct CtdlMessage *msg;
57         char *link;
58         char *description;
59         char *item_id;
60         struct rssroom *rooms;
61 };
62
63 time_t last_run = 0L;
64 struct rssurl *rsstodo = NULL;
65
66
67 // This handler is called whenever an XML tag opens.
68 //
69 void rss_start_element(void *data, const char *el, const char **attribute)
70 {
71         struct rssparser *r = (struct rssparser *)data;
72         int i;
73
74         if (
75                 (!strcasecmp(el, "entry"))
76                 || (!strcasecmp(el, "item"))
77         ) {
78                 // this is the start of a new item(rss) or entry(atom)
79                 if (r->msg != NULL) {
80                         CM_Free(r->msg);
81                         r->msg = NULL;
82                 }
83                 r->msg = malloc(sizeof(struct CtdlMessage));
84                 memset(r->msg, 0, sizeof(struct CtdlMessage));
85                 r->msg->cm_magic = CTDLMESSAGE_MAGIC;
86                 r->msg->cm_anon_type = MES_NORMAL;
87                 r->msg->cm_format_type = FMT_RFC822;
88         }
89
90         else if (!strcasecmp(el, "link")) {                     // atom feeds have the link as an attribute
91                 for(i = 0; attribute[i]; i += 2) {
92                         if (!strcasecmp(attribute[i], "href")) {
93                                 if (r->link != NULL) {
94                                         free(r->link);
95                                         r->link = NULL;
96                                 }
97                                 r->link = strdup(attribute[i+1]);
98                                 striplt(r->link);
99                         }
100                 }
101         }
102 }
103
104
105 // This handler is called whenever an XML tag closes.
106 //
107 void rss_end_element(void *data, const char *el)
108 {
109         struct rssparser *r = (struct rssparser *)data;
110         StrBuf *encoded_field;
111
112         if (StrLength(r->CData) > 0) {                          // strip leading/trailing whitespace from field
113                 StrBufTrim(r->CData);
114         }
115
116         if (                                                    // end of a new item(rss) or entry(atom)
117                 (!strcasecmp(el, "entry"))
118                 || (!strcasecmp(el, "item"))
119         ) {
120                 if (r->msg != NULL) {                           // Save the message to the rooms
121
122                         // use the link as an item id if nothing else is available
123                         if ((r->item_id == NULL) && (r->link != NULL)) {
124                                 r->item_id = strdup(r->link);
125                         }
126
127                         // check the use table
128                         StrBuf *u = NewStrBuf();
129                         StrBufAppendPrintf(u, "rss/%s", r->item_id);
130                         int already_seen = CheckIfAlreadySeen(u);
131                         FreeStrBuf(&u);
132
133                         if (already_seen == 0) {
134
135                                 // Compose the message text
136                                 StrBuf *TheMessage = NewStrBuf();
137                                 StrBufAppendPrintf(TheMessage,
138                                         "Content-type: text/html\n\n"
139                                         "\n\n"
140                                         "<html><head></head><body>"
141                                 );
142                 
143                                 if (r->description != NULL) {
144                                         StrBufAppendPrintf(TheMessage, "%s<br><br>\r\n", r->description);
145                                         free(r->description);
146                                         r->description = NULL;
147                                 }
148                 
149                                 if (r->link != NULL) {
150                                         StrBufAppendPrintf(TheMessage, "<a href=\"%s\">%s</a>\r\n", r->link, r->link);
151                                         free(r->link);
152                                         r->link = NULL;
153                                 }
154         
155                                 StrBufAppendPrintf(TheMessage, "</body></html>\r\n");
156                                 CM_SetField(r->msg, eMesageText, ChrPtr(TheMessage), StrLength(TheMessage));
157                                 FreeStrBuf(&TheMessage);
158         
159                                 if (CM_IsEmpty(r->msg, eAuthor)) {
160                                         CM_SetField(r->msg, eAuthor, HKEY("rss"));
161                                 }
162         
163                                 if (CM_IsEmpty(r->msg, eTimestamp)) {
164                                         CM_SetFieldLONG(r->msg, eTimestamp, time(NULL));
165                                 }
166         
167                                 // Save it to the room(s)
168                                 struct rssroom *rr = NULL;
169                                 long msgnum = (-1);
170                                 for (rr=r->rooms; rr!=NULL; rr=rr->next) {
171                                         if (rr == r->rooms) {
172                                                 msgnum = CtdlSubmitMsg(r->msg, NULL, rr->room);         // in first room, save msg
173                                         }
174                                         else {
175                                                 CtdlSaveMsgPointerInRoom(rr->room, msgnum, 0, NULL);    // elsewhere, save a pointer
176                                         }
177                                         syslog(LOG_DEBUG, "rssclient: saved message %ld to %s", msgnum, rr->room);
178                                 }
179                         }
180                         else {
181                                 syslog(LOG_DEBUG, "rssclient: already seen %s", r->item_id);
182                         }
183         
184                         CM_Free(r->msg);
185                         r->msg = NULL;
186                 }
187
188                 if (r->item_id != NULL) {
189                         free(r->item_id);
190                         r->item_id = NULL;
191                 }
192         }
193
194         else if (!strcasecmp(el, "title")) {                    // item subject (rss and atom)
195                 if ((r->msg != NULL) && (CM_IsEmpty(r->msg, eMsgSubject))) {
196                         encoded_field = NewStrBuf();
197                         StrBufRFC2047encode(&encoded_field, r->CData);
198                         CM_SetAsFieldSB(r->msg, eMsgSubject, &encoded_field);
199                 }
200         }
201
202         else if (!strcasecmp(el, "creator")) {                  // <creator> can be used if <author> is not present
203                 if ((r->msg != NULL) && (CM_IsEmpty(r->msg, eAuthor))) {
204                         encoded_field = NewStrBuf();
205                         StrBufRFC2047encode(&encoded_field, r->CData);
206                         CM_SetAsFieldSB(r->msg, eAuthor, &encoded_field);
207                 }
208         }
209
210         else if (!strcasecmp(el, "author")) {                   // <author> supercedes <creator> if both are present
211                 if (r->msg != NULL) {
212                         encoded_field = NewStrBuf();
213                         StrBufRFC2047encode(&encoded_field, r->CData);
214                         CM_SetAsFieldSB(r->msg, eAuthor, &encoded_field);
215                 }
216         }
217
218         else if (!strcasecmp(el, "pubdate")) {                  // date/time stamp (rss) Sat, 25 Feb 2017 14:28:01 EST
219                 if ((r->msg)&&(r->msg->cm_fields[eTimestamp]==NULL)) {
220                         CM_SetFieldLONG(r->msg, eTimestamp, parsedate(ChrPtr(r->CData)));
221                 }
222         }
223
224         else if (!strcasecmp(el, "updated")) {                  // date/time stamp (atom) 2003-12-13T18:30:02Z
225                 if ((r->msg)&&(r->msg->cm_fields[eTimestamp]==NULL)) {
226                         struct tm t;
227                         char zulu;
228                         memset(&t, 0, sizeof t);
229                         sscanf(ChrPtr(r->CData), "%d-%d-%dT%d:%d:%d%c", &t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec, &zulu);
230                         t.tm_year -= 1900;
231                         t.tm_mon -= 1;
232                         CM_SetFieldLONG(r->msg, eTimestamp, mktime(&t));
233                 }
234         }
235
236         else if (!strcasecmp(el, "link")) {                     // link to story (rss)
237                 if (r->link != NULL) {
238                         free(r->link);
239                         r->link = NULL;
240                 }
241                 r->link = strdup(ChrPtr(r->CData));
242         }
243
244         else if (
245                 (!strcasecmp(el, "guid"))                       // unique item id (rss)
246                 || (!strcasecmp(el, "id"))                      // unique item id (atom)
247         ) {
248                 if (r->item_id != NULL) {
249                         free(r->item_id);
250                         r->item_id = NULL;
251                 }
252                 r->item_id = strdup(ChrPtr(r->CData));
253         }
254
255         else if (
256                 (!strcasecmp(el, "description"))                // message text (rss)
257                 || (!strcasecmp(el, "summary"))                 // message text (atom)
258                 || (!strcasecmp(el, "content"))                 // message text (atom)
259         ) {
260                 if (r->description != NULL) {
261                         free(r->description);
262                         r->description = NULL;
263                 }
264                 r->description = strdup(ChrPtr(r->CData));
265         }
266
267         if (r->CData != NULL) {
268                 FreeStrBuf(&r->CData);
269                 r->CData = NULL;
270         }
271 }
272
273
274 // This handler is called whenever data appears between opening and closing tags.
275 //
276 void rss_handle_data(void *data, const char *content, int length)
277 {
278         struct rssparser *r = (struct rssparser *)data;
279
280         if (r->CData == NULL) {
281                 r->CData = NewStrBuf();
282         }
283
284         StrBufAppendBufPlain(r->CData, content, length, 0);
285 }
286
287
288 // Feed has been downloaded, now parse it.
289 //
290 void rss_parse_feed(StrBuf *Feed, struct rssroom *rooms)
291 {
292         struct rssparser r;
293
294         memset(&r, 0, sizeof r);
295         r.rooms = rooms;
296         XML_Parser p = XML_ParserCreate("UTF-8");
297         XML_SetElementHandler(p, rss_start_element, rss_end_element);
298         XML_SetCharacterDataHandler(p, rss_handle_data);
299         XML_SetUserData(p, (void *)&r);
300         XML_Parse(p, ChrPtr(Feed), StrLength(Feed), XML_TRUE);
301         XML_ParserFree(p);
302 }
303
304
305 // Add a feed/room pair into the todo list
306 //
307 void rssclient_push_todo(char *rssurl, char *roomname)
308 {
309         struct rssurl *r = NULL;
310         struct rssurl *thisone = NULL;
311         struct rssroom *newroom = NULL;
312
313         syslog(LOG_DEBUG, "rssclient: will fetch %s to %s", rssurl, roomname);
314
315         for (r=rsstodo; r!=NULL; r=r->next) {
316                 if (!strcasecmp(r->url, rssurl)) {
317                         thisone = r;
318                 }
319         }
320
321         if (thisone == NULL) {
322                 thisone = malloc(sizeof(struct rssurl));
323                 thisone->url = strdup(rssurl);
324                 thisone->rooms = NULL;
325                 thisone->next = rsstodo;
326                 rsstodo = thisone;
327         }
328
329         newroom = malloc(sizeof(struct rssroom));
330         newroom->room = strdup(roomname);
331         newroom->next = thisone->rooms;
332         thisone->rooms = newroom;
333 }
334
335
336 // pull one feed (possibly multiple rooms)
337 //
338 void rss_pull_one_feed(struct rssurl *url)
339 {
340         CURL *curl;
341         CURLcode res;
342         StrBuf *Downloaded = NULL;
343
344         syslog(LOG_DEBUG, "rssclient: fetching %s", url->url);
345
346         curl = curl_easy_init();
347         if (!curl) {
348                 return;
349         }
350
351         Downloaded = NewStrBuf();
352
353         curl_easy_setopt(curl, CURLOPT_URL, url->url);
354         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
355         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
356         curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);                     // Follow redirects
357         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlFillStrBuf_callback); // What to do with downloaded data
358         curl_easy_setopt(curl, CURLOPT_WRITEDATA, Downloaded);                  // Give it our StrBuf to work with
359         curl_easy_setopt(curl, CURLOPT_TIMEOUT, 20L);                           // Time out after 20 seconds
360         res = curl_easy_perform(curl);                                          // Perform the request
361         if (res != CURLE_OK) {
362                 syslog(LOG_WARNING, "rssclient: failed to load feed: %s", curl_easy_strerror(res));
363         }
364         curl_easy_cleanup(curl);
365
366         rss_parse_feed(Downloaded, url->rooms);                                 // parse the feed
367         FreeStrBuf(&Downloaded);                                                // free the downloaded feed data
368 }
369
370
371 // We have a list, now download the feeds
372 //
373 void rss_pull_feeds(void)
374 {
375         struct rssurl *r;
376         struct rssroom *rr;
377
378         while (rsstodo != NULL) {
379                 rss_pull_one_feed(rsstodo);
380                 r = rsstodo;
381                 rsstodo = rsstodo->next;
382                 while (r->rooms != NULL) {
383                         rr = r->rooms;
384                         r->rooms = r->rooms->next;
385                         free(rr->room);
386                         free(rr);
387                 }
388                 free(r->url);
389                 free(r);
390         }
391 }
392
393
394 // Scan a room's netconfig looking for RSS feed parsing requests
395 //
396 void rssclient_scan_room(struct ctdlroom *qrbuf, void *data)
397 {
398         char *serialized_config = NULL;
399         int num_configs = 0;
400         char cfgline[SIZ];
401         int i = 0;
402
403         serialized_config = LoadRoomNetConfigFile(qrbuf->QRnumber);
404         if (!serialized_config) {
405                 return;
406         }
407
408         num_configs = num_tokens(serialized_config, '\n');
409         for (i=0; i<num_configs; ++i) {
410                 extract_token(cfgline, serialized_config, i, '\n', sizeof cfgline);
411                 if (!strncasecmp(cfgline, HKEY("rssclient|"))) {
412                         strcpy(cfgline, &cfgline[10]);
413                         char *vbar = strchr(cfgline, '|');
414                         if (vbar != NULL) {
415                                 *vbar = 0;
416                         }
417                         rssclient_push_todo(cfgline, qrbuf->QRname);
418                 }
419         }
420
421         free(serialized_config);
422 }
423
424
425 /*
426  * Scan for rooms that have RSS client requests configured
427  */
428 void rssclient_scan(void) {
429         time_t now = time(NULL);
430
431         /* Run no more than once every 15 minutes. */
432         if ((now - last_run) < 900) {
433                 syslog(LOG_DEBUG,
434                         "rssclient: polling interval not yet reached; last run was %ldm%lds ago",
435                         ((now - last_run) / 60),
436                         ((now - last_run) % 60)
437                 );
438                 return;
439         }
440
441         syslog(LOG_DEBUG, "rssclient: started");
442         CtdlForEachRoom(rssclient_scan_room, NULL);
443         rss_pull_feeds();
444         syslog(LOG_DEBUG, "rssclient: ended");
445         last_run = time(NULL);
446         return;
447 }
448
449
450 CTDL_MODULE_INIT(rssclient)
451 {
452         if (!threading)
453         {
454                 syslog(LOG_INFO, "rssclient: using %s", curl_version());
455                 CtdlRegisterSessionHook(rssclient_scan, EVT_TIMER, PRIO_AGGR + 300);
456         }
457         return "rssclient";
458 }