HUGE PATCH. This moves all of mime_parser.c and all
[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 <libcitadel.h>
29 #include "citadel.h"
30 #include "server.h"
31 #include "citserver.h"
32 #include "support.h"
33 #include "config.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                 if (ri->description == NULL) ri->description = strdup("");
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 *supplied_el, const char **attr) {
210         struct rss_item *ri = (struct rss_item *) data;
211         char el[256];
212         char *sep = NULL;
213
214         /* Axe the namespace, we don't care about it */
215         safestrncpy(el, supplied_el, sizeof el);
216         while (sep = strchr(el, ':'), sep) {
217                 strcpy(el, ++sep);
218         }
219
220         if (!strcasecmp(el, "item")) {
221                 ++ri->item_tag_nesting;
222
223                 /* Initialize the feed item data structure */
224                 if (ri->guid != NULL) free(ri->guid);
225                 ri->guid = NULL;
226                 if (ri->title != NULL) free(ri->title);
227                 ri->title = NULL;
228                 if (ri->link != NULL) free(ri->link);
229                 ri->link = NULL;
230                 if (ri->description != NULL) free(ri->description);
231                 ri->description = NULL;
232
233                 /* Throw away any existing character data */
234                 if (ri->chardata_len > 0) {
235                         free(ri->chardata);
236                         ri->chardata = 0;
237                         ri->chardata_len = 0;
238                 }
239         }
240
241
242
243 }
244
245 void rss_xml_end(void *data, const char *supplied_el) {
246         struct rss_item *ri = (struct rss_item *) data;
247         char el[256];
248         char *sep = NULL;
249
250         /* Axe the namespace, we don't care about it */
251         safestrncpy(el, supplied_el, sizeof el);
252         while (sep = strchr(el, ':'), sep) {
253                 strcpy(el, ++sep);
254         }
255
256         if ( (!strcasecmp(el, "title")) && (ri->item_tag_nesting == 0) && (ri->chardata != NULL) ) {
257                 safestrncpy(ri->channel_title, ri->chardata, sizeof ri->channel_title);
258                 striplt(ri->channel_title);
259         }
260
261         if ( (!strcasecmp(el, "guid")) && (ri->chardata != NULL) ) {
262                 if (ri->guid != NULL) free(ri->guid);
263                 striplt(ri->chardata);
264                 ri->guid = strdup(ri->chardata);
265         }
266
267         if ( (!strcasecmp(el, "title")) && (ri->chardata != NULL) ) {
268                 if (ri->title != NULL) free(ri->title);
269                 striplt(ri->chardata);
270                 ri->title = strdup(ri->chardata);
271         }
272
273         if ( (!strcasecmp(el, "link")) && (ri->chardata != NULL) ) {
274                 if (ri->link != NULL) free(ri->link);
275                 striplt(ri->chardata);
276                 ri->link = strdup(ri->chardata);
277         }
278
279         if ( (!strcasecmp(el, "description")) && (ri->chardata != NULL) ) {
280                 if (ri->description != NULL) free(ri->description);
281                 ri->description = strdup(ri->chardata);
282         }
283
284         if ( ((!strcasecmp(el, "pubdate")) || (!strcasecmp(el, "date"))) && (ri->chardata != NULL) ) {
285                 striplt(ri->chardata);
286                 ri->pubdate = rdf_parsedate(ri->chardata);
287         }
288
289         if (!strcasecmp(el, "item")) {
290                 --ri->item_tag_nesting;
291                 rss_save_item(ri);
292         }
293
294         if ( (!strcasecmp(el, "rss")) || (!strcasecmp(el, "rdf")) ) {
295                 lprintf(CTDL_DEBUG, "End of feed detected.  Closing parser.\n");
296                 ri->done_parsing = 1;
297         }
298
299         if (ri->chardata_len > 0) {
300                 free(ri->chardata);
301                 ri->chardata = 0;
302                 ri->chardata_len = 0;
303         }
304
305 }
306
307
308 /*
309  * This callback stores up the data which appears in between tags.
310  */
311 void rss_xml_chardata(void *data, const XML_Char *s, int len) {
312         struct rss_item *ri = (struct rss_item *) data;
313         int old_len;
314         int new_len;
315         char *new_buffer;
316
317         old_len = ri->chardata_len;
318         new_len = old_len + len;
319         new_buffer = realloc(ri->chardata, new_len + 1);
320         if (new_buffer != NULL) {
321                 memcpy(&new_buffer[old_len], s, len);
322                 new_buffer[new_len] = 0;
323                 ri->chardata = new_buffer;
324                 ri->chardata_len = new_len;
325         }
326 }
327
328
329
330 /* 
331  * Parse a URL into host, port number, and resource identifier.
332  */
333 int parse_url(char *url, char *hostname, int *port, char *identifier)
334 {
335         char protocol[1024];
336         char scratch[1024];
337         char *ptr = NULL;
338         char *nptr = NULL;
339         
340         strcpy(scratch, url);
341         ptr = (char *)strchr(scratch, ':');
342         if (!ptr) {
343                 return(1);      /* no protocol specified */
344         }
345
346         strcpy(ptr, "");
347         strcpy(protocol, scratch);
348         if (strcmp(protocol, "http")) {
349                 return(2);      /* not HTTP */
350         }
351
352         strcpy(scratch, url);
353         ptr = (char *) strstr(scratch, "//");
354         if (!ptr) {
355                 return(3);      /* no server specified */
356         }
357         ptr += 2;
358
359         strcpy(hostname, ptr);
360         nptr = (char *)strchr(ptr, ':');
361         if (!nptr) {
362                 *port = 80;     /* default */
363                 nptr = (char *)strchr(hostname, '/');
364         }
365         else {
366                 sscanf(nptr, ":%d", port);
367                 nptr = (char *)strchr(hostname, ':');
368         }
369
370         if (nptr) {
371                 *nptr = '\0';
372         }
373
374         nptr = (char *)strchr(ptr, '/');
375         
376         if (!nptr) {
377                 return(4);      /* no url specified */
378         }
379         
380         strcpy(identifier, nptr);
381         return(0);
382 }
383
384
385 /*
386  * Begin a feed parse
387  */
388 void rss_do_fetching(char *url, char *rooms) {
389         char buf[1024];
390         char rsshost[1024];
391         int rssport = 80;
392         char rssurl[1024];
393         struct rss_item ri;
394         XML_Parser xp;
395         int sock = (-1);
396         int got_bytes = (-1);
397         int redirect_count = 0;
398
399         /* Parse the URL */
400         if (parse_url(url, rsshost, &rssport, rssurl) != 0) {
401                 lprintf(CTDL_ALERT, "Invalid URL: %s\n", url);
402         }
403
404         xp = XML_ParserCreateNS("UTF-8", ':');
405         if (!xp) {
406                 lprintf(CTDL_ALERT, "Cannot create XML parser!\n");
407                 return;
408         }
409
410         memset(&ri, 0, sizeof(struct rss_item));
411         ri.roomlist = rooms;
412         XML_SetElementHandler(xp, rss_xml_start, rss_xml_end);
413         XML_SetCharacterDataHandler(xp, rss_xml_chardata);
414         XML_SetUserData(xp, &ri);
415
416 retry:  lprintf(CTDL_NOTICE, "Connecting to <%s>\n", rsshost);
417         sprintf(buf, "%d", rssport);
418         sock = sock_connect(rsshost, buf, "tcp");
419         if (sock >= 0) {
420                 lprintf(CTDL_DEBUG, "Connected!\n");
421
422                 snprintf(buf, sizeof buf, "GET %s HTTP/1.0", rssurl);
423                 lprintf(CTDL_DEBUG, "<%s\n", buf);
424                 sock_puts(sock, buf);
425
426                 snprintf(buf, sizeof buf, "Host: %s", rsshost);
427                 lprintf(CTDL_DEBUG, "<%s\n", buf);
428                 sock_puts(sock, buf);
429
430                 snprintf(buf, sizeof buf, "User-Agent: %s", CITADEL);
431                 lprintf(CTDL_DEBUG, "<%s\n", buf);
432                 sock_puts(sock, buf);
433
434                 snprintf(buf, sizeof buf, "Accept: */*");
435                 lprintf(CTDL_DEBUG, "<%s\n", buf);
436                 sock_puts(sock, buf);
437
438                 sock_puts(sock, "");
439
440                 if (sock_getln(sock, buf, sizeof buf) >= 0) {
441                 lprintf(CTDL_DEBUG, ">%s\n", buf);
442                         remove_token(buf, 0, ' ');
443
444                         /* 200 OK */
445                         if (buf[0] == '2') {
446
447                                 while (got_bytes = sock_getln(sock, buf, sizeof buf),
448                                       (got_bytes >= 0 && (strcmp(buf, "")) && (strcmp(buf, "\r"))) ) {
449                                         /* discard headers */
450                                 }
451
452                                 while (got_bytes = sock_read(sock, buf, sizeof buf, 0),
453                                       ((got_bytes>=0) && (ri.done_parsing == 0)) ) {
454                                         XML_Parse(xp, buf, got_bytes, 0);
455                                 }
456                                 if (ri.done_parsing == 0) XML_Parse(xp, "", 0, 1);
457                         }
458
459                         /* 30X redirect */
460                         else if ( (!strncmp(buf, "30", 2)) && (redirect_count < 16) ) {
461                                 while (got_bytes = sock_getln(sock, buf, sizeof buf),
462                                       (got_bytes >= 0 && (strcmp(buf, "")) && (strcmp(buf, "\r"))) ) {
463                                         if (!strncasecmp(buf, "Location:", 9)) {
464                                                 ++redirect_count;
465                                                 strcpy(buf, &buf[9]);
466                                                 striplt(buf);
467                                                 if (parse_url(buf, rsshost, &rssport, rssurl) == 0) {
468                                                         goto retry;
469                                                 }
470                                                 else {
471                                                         lprintf(CTDL_ALERT, "Invalid URL: %s\n", buf);
472                                                 }
473                                         }
474                                 }
475                         }
476
477                 }
478                 sock_close(sock);
479         }
480         else {
481                 lprintf(CTDL_ERR, "Could not connect: %s\n", strerror(errno));
482         }
483
484         XML_ParserFree(xp);
485
486         /* Free the feed item data structure */
487         if (ri.guid != NULL) free(ri.guid);
488         ri.guid = NULL;
489         if (ri.title != NULL) free(ri.title);
490         ri.title = NULL;
491         if (ri.link != NULL) free(ri.link);
492         ri.link = NULL;
493         if (ri.description != NULL) free(ri.description);
494         ri.description = NULL;
495         if (ri.chardata_len > 0) {
496                 free(ri.chardata);
497                 ri.chardata = 0;
498                 ri.chardata_len = 0;
499         }
500 }
501
502
503 /*
504  * Scan a room's netconfig to determine whether it is requesting any RSS feeds
505  */
506 void rssclient_scan_room(struct ctdlroom *qrbuf, void *data)
507 {
508         char filename[PATH_MAX];
509         char buf[1024];
510         char instr[32];
511         FILE *fp;
512         char feedurl[256];
513         struct rssnetcfg *rncptr = NULL;
514         struct rssnetcfg *use_this_rncptr = NULL;
515         int len = 0;
516         char *ptr = NULL;
517
518         assoc_file_name(filename, sizeof filename, qrbuf, ctdl_netcfg_dir);
519
520         /* Only do net processing for rooms that have netconfigs */
521         fp = fopen(filename, "r");
522         if (fp == NULL) {
523                 return;
524         }
525
526         while (fgets(buf, sizeof buf, fp) != NULL) {
527                 buf[strlen(buf)-1] = 0;
528
529                 extract_token(instr, buf, 0, '|', sizeof instr);
530                 if (!strcasecmp(instr, "rssclient")) {
531
532                         use_this_rncptr = NULL;
533
534                         extract_token(feedurl, buf, 1, '|', sizeof feedurl);
535
536                         /* If any other rooms have requested the same feed, then we will just add this
537                          * room to the target list for that client request.
538                          */
539                         for (rncptr=rnclist; rncptr!=NULL; rncptr=rncptr->next) {
540                                 if (!strcmp(rncptr->url, feedurl)) {
541                                         use_this_rncptr = rncptr;
542                                 }
543                         }
544
545                         /* Otherwise create a new client request */
546                         if (use_this_rncptr == NULL) {
547                                 rncptr = (struct rssnetcfg *) malloc(sizeof(struct rssnetcfg));
548                                 if (rncptr != NULL) {
549                                         rncptr->next = rnclist;
550                                         safestrncpy(rncptr->url, feedurl, sizeof rncptr->url);
551                                         rncptr->rooms = NULL;
552                                         rnclist = rncptr;
553                                         use_this_rncptr = rncptr;
554                                 }
555                         }
556
557                         /* Add the room name to the request */
558                         if (use_this_rncptr != NULL) {
559                                 if (use_this_rncptr->rooms == NULL) {
560                                         rncptr->rooms = strdup(qrbuf->QRname);
561                                 }
562                                 else {
563                                         len = strlen(use_this_rncptr->rooms) + strlen(qrbuf->QRname) + 5;
564                                         ptr = realloc(use_this_rncptr->rooms, len);
565                                         if (ptr != NULL) {
566                                                 strcat(ptr, "|");
567                                                 strcat(ptr, qrbuf->QRname);
568                                                 use_this_rncptr->rooms = ptr;
569                                         }
570                                 }
571                         }
572                 }
573
574         }
575
576         fclose(fp);
577
578 }
579
580 /*
581  * Scan for rooms that have RSS client requests configured
582  */
583 void rssclient_scan(void) {
584         static time_t last_run = 0L;
585         static int doing_rssclient = 0;
586         struct rssnetcfg *rptr = NULL;
587
588         /*
589          * Run RSS client no more frequently than once every n seconds
590          */
591         if ( (time(NULL) - last_run) < config.c_net_freq ) {
592                 return;
593         }
594
595         /*
596          * This is a simple concurrency check to make sure only one rssclient run
597          * is done at a time.  We could do this with a mutex, but since we
598          * don't really require extremely fine granularity here, we'll do it
599          * with a static variable instead.
600          */
601         if (doing_rssclient) return;
602         doing_rssclient = 1;
603
604         lprintf(CTDL_DEBUG, "rssclient started\n");
605         ForEachRoom(rssclient_scan_room, NULL);
606
607         while (rnclist != NULL) {
608                 rss_do_fetching(rnclist->url, rnclist->rooms);
609                 rptr = rnclist;
610                 rnclist = rnclist->next;
611                 if (rptr->rooms != NULL) free(rptr->rooms);
612                 free(rptr);
613         }
614
615         lprintf(CTDL_DEBUG, "rssclient ended\n");
616         last_run = time(NULL);
617         doing_rssclient = 0;
618 }
619
620
621 #endif  /* HAVE_EXPAT */
622
623 CTDL_MODULE_INIT(rssclient)
624 {
625 #ifdef HAVE_EXPAT
626         CtdlRegisterSessionHook(rssclient_scan, EVT_TIMER);
627 #else
628          lprintf(CTDL_INFO, "This server is missing the Expat XML parser.  RSS client will be disabled.\n");
629 #endif
630         /* return our Subversion id for the Log */
631         return "$Id: serv_rssclient.c 5652 2007-10-29 20:14:48Z ajc $";
632 }