serv_rssclient.c: style update
[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                                 StrBuf *TheMessage = NewStrBuf();
130                                 StrBufAppendPrintf(TheMessage,
131                                         "Content-type: text/html\n\n"
132                                         "\n\n"
133                                         "<html><head></head><body>"
134                                 );
135                 
136                                 if (r->description != NULL) {
137                                         StrBufAppendPrintf(TheMessage, "%s<br><br>\r\n", r->description);
138                                         free(r->description);
139                                         r->description = NULL;
140                                 }
141                 
142                                 if (r->link != NULL) {
143                                         StrBufAppendPrintf(TheMessage, "<a href=\"%s\">%s</a>\r\n", r->link, r->link);
144                                         free(r->link);
145                                         r->link = NULL;
146                                 }
147         
148                                 StrBufAppendPrintf(TheMessage, "</body></html>\r\n");
149                                 CM_SetField(r->msg, eMesageText, ChrPtr(TheMessage), StrLength(TheMessage));
150                                 FreeStrBuf(&TheMessage);
151         
152                                 if (CM_IsEmpty(r->msg, eAuthor)) {
153                                         CM_SetField(r->msg, eAuthor, HKEY("rss"));
154                                 }
155         
156                                 if (CM_IsEmpty(r->msg, eTimestamp)) {
157                                         CM_SetFieldLONG(r->msg, eTimestamp, time(NULL));
158                                 }
159         
160                                 // Save it to the room(s)
161                                 struct rssroom *rr = NULL;
162                                 long msgnum = (-1);
163                                 for (rr=r->rooms; rr!=NULL; rr=rr->next) {
164                                         if (rr == r->rooms) {
165                                                 msgnum = CtdlSubmitMsg(r->msg, NULL, rr->room);         // in first room, save msg
166                                         }
167                                         else {
168                                                 CtdlSaveMsgPointerInRoom(rr->room, msgnum, 0, NULL);    // elsewhere, save a pointer
169                                         }
170                                         syslog(LOG_DEBUG, "rssclient: saved message %ld to %s", msgnum, rr->room);
171                                 }
172                         }
173                         else {
174                                 syslog(LOG_DEBUG, "rssclient: already seen %s", r->item_id);
175                         }
176         
177                         CM_Free(r->msg);
178                         r->msg = NULL;
179                 }
180
181                 if (r->item_id != NULL) {
182                         free(r->item_id);
183                         r->item_id = NULL;
184                 }
185         }
186
187         else if (!strcasecmp(el, "title")) {                    // item subject (rss and atom)
188                 if ((r->msg != NULL) && (CM_IsEmpty(r->msg, eMsgSubject))) {
189                         encoded_field = NewStrBuf();
190                         StrBufRFC2047encode(&encoded_field, r->CData);
191                         CM_SetAsFieldSB(r->msg, eMsgSubject, &encoded_field);
192                 }
193         }
194
195         else if (!strcasecmp(el, "creator")) {                  // <creator> can be used if <author> is not present
196                 if ((r->msg != NULL) && (CM_IsEmpty(r->msg, eAuthor))) {
197                         encoded_field = NewStrBuf();
198                         StrBufRFC2047encode(&encoded_field, r->CData);
199                         CM_SetAsFieldSB(r->msg, eAuthor, &encoded_field);
200                 }
201         }
202
203         else if (!strcasecmp(el, "author")) {                   // <author> supercedes <creator> if both are present
204                 if (r->msg != NULL) {
205                         encoded_field = NewStrBuf();
206                         StrBufRFC2047encode(&encoded_field, r->CData);
207                         CM_SetAsFieldSB(r->msg, eAuthor, &encoded_field);
208                 }
209         }
210
211         else if (!strcasecmp(el, "pubdate")) {                  // date/time stamp (rss) Sat, 25 Feb 2017 14:28:01 EST
212                 if ((r->msg)&&(r->msg->cm_fields[eTimestamp]==NULL)) {
213                         CM_SetFieldLONG(r->msg, eTimestamp, parsedate(ChrPtr(r->CData)));
214                 }
215         }
216
217         else if (!strcasecmp(el, "updated")) {                  // date/time stamp (atom) 2003-12-13T18:30:02Z
218                 if ((r->msg)&&(r->msg->cm_fields[eTimestamp]==NULL)) {
219                         struct tm t;
220                         char zulu;
221                         memset(&t, 0, sizeof t);
222                         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);
223                         t.tm_year -= 1900;
224                         t.tm_mon -= 1;
225                         CM_SetFieldLONG(r->msg, eTimestamp, mktime(&t));
226                 }
227         }
228
229         else if (!strcasecmp(el, "link")) {                     // link to story (rss)
230                 if (r->link != NULL) {
231                         free(r->link);
232                         r->link = NULL;
233                 }
234                 r->link = strdup(ChrPtr(r->CData));
235         }
236
237         else if (
238                 (!strcasecmp(el, "guid"))                       // unique item id (rss)
239                 || (!strcasecmp(el, "id"))                      // unique item id (atom)
240         ) {
241                 if (r->item_id != NULL) {
242                         free(r->item_id);
243                         r->item_id = NULL;
244                 }
245                 r->item_id = strdup(ChrPtr(r->CData));
246         }
247
248         else if (
249                 (!strcasecmp(el, "description"))                // message text (rss)
250                 || (!strcasecmp(el, "summary"))                 // message text (atom)
251                 || (!strcasecmp(el, "content"))                 // message text (atom)
252         ) {
253                 if (r->description != NULL) {
254                         free(r->description);
255                         r->description = NULL;
256                 }
257                 r->description = strdup(ChrPtr(r->CData));
258         }
259
260         if (r->CData != NULL) {
261                 FreeStrBuf(&r->CData);
262                 r->CData = NULL;
263         }
264 }
265
266
267 // This handler is called whenever data appears between opening and closing tags.
268 void rss_handle_data(void *data, const char *content, int length) {
269         struct rssparser *r = (struct rssparser *)data;
270
271         if (r->CData == NULL) {
272                 r->CData = NewStrBuf();
273         }
274
275         StrBufAppendBufPlain(r->CData, content, length, 0);
276 }
277
278
279 // Feed has been downloaded, now parse it.
280 void rss_parse_feed(StrBuf *Feed, struct rssroom *rooms) {
281         struct rssparser r;
282
283         memset(&r, 0, sizeof r);
284         r.rooms = rooms;
285         XML_Parser p = XML_ParserCreate("UTF-8");
286         XML_SetElementHandler(p, rss_start_element, rss_end_element);
287         XML_SetCharacterDataHandler(p, rss_handle_data);
288         XML_SetUserData(p, (void *)&r);
289         XML_Parse(p, ChrPtr(Feed), StrLength(Feed), XML_TRUE);
290         XML_ParserFree(p);
291 }
292
293
294 // Add a feed/room pair into the todo list
295 void rssclient_push_todo(char *rssurl, char *roomname) {
296         struct rssurl *r = NULL;
297         struct rssurl *thisone = NULL;
298         struct rssroom *newroom = NULL;
299
300         syslog(LOG_DEBUG, "rssclient: will fetch %s to %s", rssurl, roomname);
301
302         for (r=rsstodo; r!=NULL; r=r->next) {
303                 if (!strcasecmp(r->url, rssurl)) {
304                         thisone = r;
305                 }
306         }
307
308         if (thisone == NULL) {
309                 thisone = malloc(sizeof(struct rssurl));
310                 thisone->url = strdup(rssurl);
311                 thisone->rooms = NULL;
312                 thisone->next = rsstodo;
313                 rsstodo = thisone;
314         }
315
316         newroom = malloc(sizeof(struct rssroom));
317         newroom->room = strdup(roomname);
318         newroom->next = thisone->rooms;
319         thisone->rooms = newroom;
320 }
321
322
323 // pull one feed (possibly multiple rooms)
324 void rss_pull_one_feed(struct rssurl *url) {
325         CURL *curl;
326         CURLcode res;
327         StrBuf *Downloaded = NULL;
328
329         syslog(LOG_DEBUG, "rssclient: fetching %s", url->url);
330
331         curl = curl_easy_init();
332         if (!curl) {
333                 return;
334         }
335
336         Downloaded = NewStrBuf();
337
338         curl_easy_setopt(curl, CURLOPT_URL, url->url);
339         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
340         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
341         curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);                     // Follow redirects
342         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlFillStrBuf_callback); // What to do with downloaded data
343         curl_easy_setopt(curl, CURLOPT_WRITEDATA, Downloaded);                  // Give it our StrBuf to work with
344         curl_easy_setopt(curl, CURLOPT_TIMEOUT, 20L);                           // Time out after 20 seconds
345         res = curl_easy_perform(curl);                                          // Perform the request
346         if (res != CURLE_OK) {
347                 syslog(LOG_WARNING, "rssclient: failed to load feed: %s", curl_easy_strerror(res));
348         }
349         curl_easy_cleanup(curl);
350
351         rss_parse_feed(Downloaded, url->rooms);                                 // parse the feed
352         FreeStrBuf(&Downloaded);                                                // free the downloaded feed data
353 }
354
355
356 // We have a list, now download the feeds
357 void rss_pull_feeds(void) {
358         struct rssurl *r;
359         struct rssroom *rr;
360
361         while ((rsstodo != NULL) && (!server_shutting_down)) {
362                 rss_pull_one_feed(rsstodo);
363                 r = rsstodo;
364                 rsstodo = rsstodo->next;
365                 while (r->rooms != NULL) {
366                         rr = r->rooms;
367                         r->rooms = r->rooms->next;
368                         free(rr->room);
369                         free(rr);
370                 }
371                 free(r->url);
372                 free(r);
373         }
374 }
375
376
377 // Scan a room's netconfig looking for RSS feed parsing requests
378 void rssclient_scan_room(struct ctdlroom *qrbuf, void *data) {
379         char *serialized_config = NULL;
380         int num_configs = 0;
381         char cfgline[SIZ];
382         int i = 0;
383
384         if (server_shutting_down) return;
385
386         serialized_config = LoadRoomNetConfigFile(qrbuf->QRnumber);
387         if (!serialized_config) {
388                 return;
389         }
390
391         num_configs = num_tokens(serialized_config, '\n');
392         for (i=0; i<num_configs; ++i) {
393                 extract_token(cfgline, serialized_config, i, '\n', sizeof cfgline);
394                 if (!strncasecmp(cfgline, HKEY("rssclient|"))) {
395                         strcpy(cfgline, &cfgline[10]);
396                         char *vbar = strchr(cfgline, '|');
397                         if (vbar != NULL) {
398                                 *vbar = 0;
399                         }
400                         rssclient_push_todo(cfgline, qrbuf->QRname);
401                 }
402         }
403
404         free(serialized_config);
405 }
406
407
408 // Scan for rooms that have RSS client requests configured
409 void rssclient_scan(void) {
410         time_t now = time(NULL);
411
412         // Run no more than once every 15 minutes.
413         if ((now - last_run) < 900) {
414                 syslog(LOG_DEBUG,
415                         "rssclient: polling interval not yet reached; last run was %ldm%lds ago",
416                         ((now - last_run) / 60),
417                         ((now - last_run) % 60)
418                 );
419                 return;
420         }
421
422         syslog(LOG_DEBUG, "rssclient: started");
423         CtdlForEachRoom(rssclient_scan_room, NULL);
424         rss_pull_feeds();
425         syslog(LOG_DEBUG, "rssclient: ended");
426         last_run = time(NULL);
427         return;
428 }
429
430
431 // Initialization function, called from modules_init.c
432 char *ctdl_module_init_rssclient(void) {
433         if (!threading) {
434                 syslog(LOG_INFO, "rssclient: using %s", curl_version());
435                 CtdlRegisterSessionHook(rssclient_scan, EVT_TIMER, PRIO_AGGR + 300);
436         }
437         return "rssclient";
438 }