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