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