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