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