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