Checked in an RSS feed reader to replace the
[citadel.git] / citadel / modules / rssclient / serv_rssclient.c
1 /*
2  * $Id: serv_rssclient.c 5652 2007-10-29 20:14:48Z ajc $
3  *
4  * Bring external RSS feeds into rooms.
5  *
6  */
7
8 #include <stdlib.h>
9 #include <unistd.h>
10 #include <stdio.h>
11
12 #if TIME_WITH_SYS_TIME
13 # include <sys/time.h>
14 # include <time.h>
15 #else
16 # if HAVE_SYS_TIME_H
17 #  include <sys/time.h>
18 # else
19 #  include <time.h>
20 # endif
21 #endif
22
23 #include <ctype.h>
24 #include <string.h>
25 #include <errno.h>
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include "citadel.h"
29 #include "server.h"
30 #include "citserver.h"
31 #include "support.h"
32 #include "config.h"
33 #include "tools.h"
34 #include "room_ops.h"
35 #include "ctdl_module.h"
36 #include "clientsocket.h"
37 #include "msgbase.h"
38 #include "database.h"
39 #include "citadel_dirs.h"
40 #include "md5.h"
41
42 #ifdef HAVE_EXPAT
43 #include <expat.h>
44
45
46 struct rssnetcfg {
47         struct rssnetcfg *next;
48         char url[256];
49         char *rooms;
50 };
51
52 struct rss_item {
53         char *chardata;
54         int chardata_len;
55         char *roomlist;
56         int done_parsing;
57         char *guid;
58         char *title;
59         char *link;
60         char *description;
61         time_t pubdate;
62 };
63
64 struct rssnetcfg *rnclist = NULL;
65
66
67 /*
68  * Commit a fetched and parsed RSS item to disk
69  */
70 void rss_save_item(struct rss_item *ri) {
71
72         struct MD5Context md5context;
73         u_char rawdigest[MD5_DIGEST_LEN];
74         int i;
75         char utmsgid[SIZ];
76         struct cdbdata *cdbut;
77         struct UseTable ut;
78         struct CtdlMessage *msg;
79         struct recptypes *recp = NULL;
80         int msglen = 0;
81
82         recp = (struct recptypes *) malloc(sizeof(struct recptypes));
83         if (recp == NULL) return;
84         memset(recp, 0, sizeof(struct recptypes));
85         recp->recp_room = strdup(ri->roomlist);
86         recp->num_room = num_tokens(ri->roomlist, '|');
87         recp->recptypes_magic = RECPTYPES_MAGIC;
88    
89         /* Construct a GUID to use in the S_USETABLE table.
90          * If one is not present in the item itself, make one up.
91          */
92         if (ri->guid != NULL) {
93                 snprintf(utmsgid, sizeof utmsgid, "rss/%s", ri->guid);
94         }
95         else {
96                 MD5Init(&md5context);
97                 if (ri->title != NULL) {
98                         MD5Update(&md5context, ri->title, strlen(ri->title));
99                 }
100                 if (ri->link != NULL) {
101                         MD5Update(&md5context, ri->link, strlen(ri->link));
102                 }
103                 MD5Final(rawdigest, &md5context);
104                 for (i=0; i<MD5_DIGEST_LEN; i++) {
105                         sprintf(&utmsgid[i*2], "%02X", (unsigned char) (rawdigest[i] & 0xff));
106                         utmsgid[i*2] = tolower(utmsgid[i*2]);
107                         utmsgid[(i*2)+1] = tolower(utmsgid[(i*2)+1]);
108                 }
109                 strcat(utmsgid, "_rss2ctdl");
110         }
111
112         /* Find out if we've already seen this item */
113         cdbut = cdb_fetch(CDB_USETABLE, utmsgid, strlen(utmsgid));
114         if (cdbut != NULL) {
115                 /* Item has already been seen */
116                 lprintf(CTDL_DEBUG, "%s has already been seen\n", utmsgid);
117                 cdb_free(cdbut);
118
119                 /* rewrite the record anyway, to update the timestamp */
120                 strcpy(ut.ut_msgid, utmsgid);
121                 ut.ut_timestamp = time(NULL);
122                 cdb_store(CDB_USETABLE, utmsgid, strlen(utmsgid), &ut, sizeof(struct UseTable) );
123         }
124         else {
125                 /* Item has not been seen, so save it. */
126
127                 for (i=strlen(ri->description); i>=0; --i) {
128                         if (isspace(ri->description[i])) {
129                                 ri->description[i] = ' ';
130                         }
131                 }
132
133                 msg = malloc(sizeof(struct CtdlMessage));
134                 memset(msg, 0, sizeof(struct CtdlMessage));
135                 msg->cm_magic = CTDLMESSAGE_MAGIC;
136                 msg->cm_anon_type = MES_NORMAL;
137                 msg->cm_format_type = FMT_RFC822;
138                 msg->cm_fields['A'] = strdup("rss");
139                 msg->cm_fields['N'] = strdup(NODENAME);
140                 msg->cm_fields['U'] = strdup(ri->title);
141                 msg->cm_fields['T'] = malloc(64);
142                 snprintf(msg->cm_fields['T'], 64, "%ld", ri->pubdate);
143
144                 msglen = 1024 + strlen(ri->link) + strlen(ri->description) ;
145                 msg->cm_fields['M'] = malloc(msglen);
146                 snprintf(msg->cm_fields['M'], msglen,
147                         "Content-type: text/html\r\n\r\n"
148                         "<html><body>\n"
149                         "%s<br><br>\n"
150                         "<a href=\"%s\">%s</a>\n"
151                         "</body></html>\n"
152                         ,
153                         ri->description,
154                         ri->link, ri->link
155                 );
156
157                 CtdlSubmitMsg(msg, recp, NULL);
158                 CtdlFreeMessage(msg);
159                 free_recipients(recp);
160
161                 /* write the uidl to the use table so we don't store this item again */
162                 strcpy(ut.ut_msgid, utmsgid);
163                 ut.ut_timestamp = time(NULL);
164                 cdb_store(CDB_USETABLE, utmsgid, strlen(utmsgid), &ut, sizeof(struct UseTable) );
165         }
166 }
167
168
169
170 /*
171  * Convert an RDF/RSS datestamp into a time_t
172  */
173 time_t rdf_parsedate(char *p)
174 {
175         struct tm tm;
176
177         if (!p) return 0L;
178         if (strlen(p) < 10) return 0L;
179
180         memset(&tm, 0, sizeof tm);
181
182         /* YYYY-MM-DDTHH:MM format...
183          */
184         if ( (p[4] == '-') && (p[7] == '-') ) {
185                 tm.tm_year = atoi(&p[0]) - 1900;
186                 tm.tm_mon = atoi(&p[5]) - 1;
187                 tm.tm_mday = atoi(&p[8]);
188                 if ( (p[10] == 'T') && (p[13] == ':') ) {
189                         tm.tm_hour = atoi(&p[11]);
190                         tm.tm_min = atoi(&p[14]);
191                 }
192         }
193
194         else {
195                 /* FIXME try an imap timestamp conversion */
196         }
197
198         return mktime(&tm);
199 }
200
201
202
203 void rss_xml_start(void *data, const char *el, const char **attr) {
204         struct rss_item *ri = (struct rss_item *) data;
205
206         if (!strcasecmp(el, "item")) {
207
208                 /* Initialize the feed item data structure */
209                 if (ri->guid != NULL) free(ri->guid);
210                 ri->guid = NULL;
211                 if (ri->title != NULL) free(ri->title);
212                 ri->title = NULL;
213                 if (ri->link != NULL) free(ri->link);
214                 ri->link = NULL;
215                 if (ri->description != NULL) free(ri->description);
216                 ri->description = NULL;
217
218                 /* Throw away any existing character data */
219                 if (ri->chardata_len > 0) {
220                         free(ri->chardata);
221                         ri->chardata = 0;
222                         ri->chardata_len = 0;
223                 }
224         }
225
226
227
228 }
229
230 void rss_xml_end(void *data, const char *supplied_el) {
231         struct rss_item *ri = (struct rss_item *) data;
232         char el[256];
233         char *sep = NULL;
234
235
236         /* Axe the namespace, we don't care about it */
237
238         safestrncpy(el, supplied_el, sizeof el);
239         while (sep = strchr(el, ':'), sep) {
240                 strcpy(el, ++sep);
241         }
242
243         if (!strcasecmp(el, "guid")) {
244                 if (ri->guid != NULL) free(ri->guid);
245                 striplt(ri->chardata);
246                 ri->guid = strdup(ri->chardata);
247         }
248
249         if (!strcasecmp(el, "title")) {
250                 if (ri->title != NULL) free(ri->title);
251                 striplt(ri->chardata);
252                 ri->title = strdup(ri->chardata);
253         }
254
255         if (!strcasecmp(el, "link")) {
256                 if (ri->link != NULL) free(ri->link);
257                 striplt(ri->chardata);
258                 ri->link = strdup(ri->chardata);
259         }
260
261         if (!strcasecmp(el, "description")) {
262                 if (ri->description != NULL) free(ri->description);
263                 ri->description = strdup(ri->chardata);
264         }
265
266         if ( (!strcasecmp(el, "pubdate")) || (!strcasecmp(el, "date")) ) {
267                 striplt(ri->chardata);
268                 ri->pubdate = rdf_parsedate(ri->chardata);
269         }
270
271         if (!strcasecmp(el, "item")) {
272                 rss_save_item(ri);
273         }
274
275         if ( (!strcasecmp(el, "rss")) || (!strcasecmp(el, "rdf")) ) {
276                 lprintf(CTDL_DEBUG, "KILL THE PARSER, KILL THE PARSER, KILL THE PARSER!\n");
277                 ri->done_parsing = 1;
278         }
279
280         if (ri->chardata_len > 0) {
281                 free(ri->chardata);
282                 ri->chardata = 0;
283                 ri->chardata_len = 0;
284         }
285
286 }
287
288
289 /*
290  * This callback stores up the data which appears in between tags.
291  */
292 void rss_xml_chardata(void *data, const XML_Char *s, int len) {
293         struct rss_item *ri = (struct rss_item *) data;
294         int old_len;
295         int new_len;
296         char *new_buffer;
297
298         old_len = ri->chardata_len;
299         new_len = old_len + len;
300         new_buffer = realloc(ri->chardata, new_len + 1);
301         if (new_buffer != NULL) {
302                 memcpy(&new_buffer[old_len], s, len);
303                 new_buffer[new_len] = 0;
304                 ri->chardata = new_buffer;
305                 ri->chardata_len = new_len;
306         }
307 }
308
309
310
311 /* 
312  * Parses an url into hostname, port number and resource identifier.
313  */
314 int parse_url(char *url, char *hostname, int *port, char *identifier)
315 {
316         char protocol[1024], scratch[1024];
317         char *ptr = NULL;
318         char *nptr = NULL;
319         
320         strcpy(scratch, url);
321         ptr = (char *)strchr(scratch, ':');
322         if (!ptr) {
323                 return(1);      /* no protocol specified */
324         }
325         strcpy(ptr, "");
326         strcpy(protocol, scratch);
327         if (strcmp(protocol, "http")) {
328                 return(2);      /* not HTTP */
329         }
330
331         strcpy(scratch, url);
332         ptr = (char *) strstr(scratch, "//");
333         if (!ptr) {
334                 return(3);      /* no server specified */
335         }
336         ptr += 2;
337
338         strcpy(hostname, ptr);
339         nptr = (char *)strchr(ptr, ':');
340         if (!nptr) {
341                 *port = 80;     /* default */
342                 nptr = (char *)strchr(hostname, '/');
343         }
344         else {
345                 sscanf(nptr, ":%d", port);
346                 nptr = (char *)strchr(hostname, ':');
347         }
348
349         if (nptr) {
350                 *nptr = '\0';
351         }
352
353         nptr = (char *)strchr(ptr, '/');
354         
355         if (!nptr) {
356                 return(4);      /* no url specified */
357         }
358         
359         strcpy(identifier, nptr);
360         return(0);
361 }
362
363
364
365
366
367
368 /*
369  * Begin a feed parse
370  */
371 void rss_do_fetching(char *url, char *rooms) {
372         char buf[1024];
373         char rsshost[1024];
374         int rssport = 80;
375         char rssurl[1024];
376         struct rss_item ri;
377         XML_Parser xp;
378         int sock = (-1);
379         int got_bytes = (-1);
380
381
382         xp = XML_ParserCreateNS("UTF-8", ':');
383         if (!xp) {
384                 lprintf(CTDL_ALERT, "Cannot create XML parser!\n");
385                 return;
386         }
387
388         memset(&ri, 0, sizeof(struct rss_item));
389         ri.roomlist = rooms;
390         XML_SetElementHandler(xp, rss_xml_start, rss_xml_end);
391         XML_SetCharacterDataHandler(xp, rss_xml_chardata);
392         XML_SetUserData(xp, &ri);
393
394         /* Parse the URL */
395         
396 retry:  sock = (-1);
397         if (parse_url(url, rsshost, &rssport, rssurl) != 0) {
398                 lprintf(CTDL_ALERT, "Invalid URL: %s\n", url);
399         }
400         else {
401                 lprintf(CTDL_NOTICE, "Connecting to <%s>\n", rsshost);
402                 sprintf(buf, "%d", rssport);
403                 sock = sock_connect(rsshost, buf, "tcp");
404         }
405
406         if (sock >= 0) {
407                 lprintf(CTDL_DEBUG, "Connected!\n");
408
409                 snprintf(buf, sizeof buf, "GET %s HTTP/1.0\r", rssurl);
410                 lprintf(CTDL_DEBUG, "<%s\n", buf);
411                 sock_puts(sock, buf);
412
413                 snprintf(buf, sizeof buf, "Server: %s\r", rsshost);
414                 lprintf(CTDL_DEBUG, "<%s\n", buf);
415                 sock_puts(sock, buf);
416
417                 sock_puts(sock, "\r");
418
419                 if (sock_getln(sock, buf, sizeof buf) >= 0) {
420                 lprintf(CTDL_DEBUG, ">%s\n", buf);
421                         remove_token(buf, 0, ' ');
422                         if (buf[0] == '2') {
423
424                                 while (got_bytes = sock_getln(sock, buf, sizeof buf),
425                                       (got_bytes >= 0 && (strcmp(buf, "")) && (strcmp(buf, "\r"))) ) {
426                                         /* FIXME handle 302 redirects!! */
427                                 }
428
429
430                                 while (got_bytes = sock_read(sock, buf, sizeof buf, 0),
431                                       ((got_bytes>=0) && (ri.done_parsing == 0)) ) {
432                                         XML_Parse(xp, buf, got_bytes, 0);
433                                 }
434                                 if (ri.done_parsing == 0) XML_Parse(xp, "", 0, 1);
435                         }
436                 }
437                 sock_close(sock);
438         }
439         else {
440                 lprintf(CTDL_ERR, "Could not connect: %s\n", strerror(errno));
441         }
442
443         XML_ParserFree(xp);
444
445         /* Free the feed item data structure */
446         if (ri.guid != NULL) free(ri.guid);
447         ri.guid = NULL;
448         if (ri.title != NULL) free(ri.title);
449         ri.title = NULL;
450         if (ri.link != NULL) free(ri.link);
451         ri.link = NULL;
452         if (ri.description != NULL) free(ri.description);
453         ri.description = NULL;
454         if (ri.chardata_len > 0) {
455                 free(ri.chardata);
456                 ri.chardata = 0;
457                 ri.chardata_len = 0;
458         }
459 }
460
461
462 /*
463  * Scan a room's netconfig to determine whether it is requesting any RSS feeds
464  */
465 void rssclient_scan_room(struct ctdlroom *qrbuf, void *data)
466 {
467         char filename[PATH_MAX];
468         char buf[1024];
469         char instr[32];
470         FILE *fp;
471         char feedurl[256];
472         struct rssnetcfg *rncptr = NULL;
473         struct rssnetcfg *use_this_rncptr = NULL;
474         int len = 0;
475         char *ptr = NULL;
476
477         assoc_file_name(filename, sizeof filename, qrbuf, ctdl_netcfg_dir);
478
479         /* Only do net processing for rooms that have netconfigs */
480         fp = fopen(filename, "r");
481         if (fp == NULL) {
482                 return;
483         }
484
485         while (fgets(buf, sizeof buf, fp) != NULL) {
486                 buf[strlen(buf)-1] = 0;
487
488                 extract_token(instr, buf, 0, '|', sizeof instr);
489                 if (!strcasecmp(instr, "rssclient")) {
490                         extract_token(feedurl, buf, 1, '|', sizeof feedurl);
491
492                         /* If any other rooms have requested the same feed, then we will just add this
493                          * room to the target list for that client request.
494                          */
495                         for (rncptr=rnclist; rncptr!=NULL; rncptr=rncptr->next) {
496                                 if (!strcmp(rncptr->url, feedurl)) {
497                                         use_this_rncptr = rncptr;
498                                 }
499                         }
500
501                         /* Otherwise create a new client request */
502                         if (use_this_rncptr == NULL) {
503                                 rncptr = (struct rssnetcfg *) malloc(sizeof(struct rssnetcfg));
504                                 if (rncptr != NULL) {
505                                         rncptr->next = rnclist;
506                                         safestrncpy(rncptr->url, feedurl, sizeof rncptr->url);
507                                         rncptr->rooms = NULL;
508                                         rnclist = rncptr;
509                                         use_this_rncptr = rncptr;
510                                 }
511                         }
512
513                         /* Add the room name to the request */
514                         if (use_this_rncptr != NULL) {
515                                 if (use_this_rncptr->rooms == NULL) {
516                                         rncptr->rooms = strdup(qrbuf->QRname);
517                                 }
518                                 else {
519                                         len = strlen(use_this_rncptr->rooms) + strlen(qrbuf->QRname) + 5;
520                                         ptr = realloc(use_this_rncptr->rooms, len);
521                                         if (ptr != NULL) {
522                                                 strcat(ptr, "|");
523                                                 strcat(ptr, qrbuf->QRname);
524                                                 use_this_rncptr->rooms = ptr;
525                                         }
526                                 }
527                         }
528                 }
529
530         }
531
532         fclose(fp);
533
534 }
535
536 /*
537  * Scan for rooms that have RSS client requests configured
538  */
539 void rssclient_scan(void) {
540         static time_t last_run = 0L;
541         static int doing_rssclient = 0;
542         struct rssnetcfg *rptr = NULL;
543
544         /*
545          * Run RSS client no more frequently than once every n seconds
546          */
547         if ( (time(NULL) - last_run) < config.c_net_freq ) {
548                 return;
549         }
550
551         /*
552          * This is a simple concurrency check to make sure only one rssclient run
553          * is done at a time.  We could do this with a mutex, but since we
554          * don't really require extremely fine granularity here, we'll do it
555          * with a static variable instead.
556          */
557         if (doing_rssclient) return;
558         doing_rssclient = 1;
559
560         lprintf(CTDL_DEBUG, "rssclient started\n");
561         ForEachRoom(rssclient_scan_room, NULL);
562
563         while (rnclist != NULL) {
564                 rss_do_fetching(rnclist->url, rnclist->rooms);
565                 rptr = rnclist;
566                 rnclist = rnclist->next;
567                 if (rptr->rooms != NULL) free(rptr->rooms);
568                 free(rptr);
569         }
570
571         lprintf(CTDL_DEBUG, "rssclient ended\n");
572         last_run = time(NULL);
573         doing_rssclient = 0;
574 }
575
576
577 #endif  /* HAVE_EXPAT */
578
579 CTDL_MODULE_INIT(rssclient)
580 {
581 #ifdef HAVE_EXPAT
582         CtdlRegisterSessionHook(rssclient_scan, EVT_TIMER);
583 #else
584          lprintf(CTDL_INFO, "This server is missing the Expat XML parser.  RSS client will be disabled.\n");
585 #endif
586         /* return our Subversion id for the Log */
587         return "$Id: serv_rssclient.c 5652 2007-10-29 20:14:48Z ajc $";
588 }