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