Handle 30X redirects when requesting RSS
[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, "End of feed detected.  Closing 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  * Parse a URL into host, port number, and resource identifier.
313  */
314 int parse_url(char *url, char *hostname, int *port, char *identifier)
315 {
316         char protocol[1024];
317         char scratch[1024];
318         char *ptr = NULL;
319         char *nptr = NULL;
320         
321         strcpy(scratch, url);
322         ptr = (char *)strchr(scratch, ':');
323         if (!ptr) {
324                 return(1);      /* no protocol specified */
325         }
326
327         strcpy(ptr, "");
328         strcpy(protocol, scratch);
329         if (strcmp(protocol, "http")) {
330                 return(2);      /* not HTTP */
331         }
332
333         strcpy(scratch, url);
334         ptr = (char *) strstr(scratch, "//");
335         if (!ptr) {
336                 return(3);      /* no server specified */
337         }
338         ptr += 2;
339
340         strcpy(hostname, ptr);
341         nptr = (char *)strchr(ptr, ':');
342         if (!nptr) {
343                 *port = 80;     /* default */
344                 nptr = (char *)strchr(hostname, '/');
345         }
346         else {
347                 sscanf(nptr, ":%d", port);
348                 nptr = (char *)strchr(hostname, ':');
349         }
350
351         if (nptr) {
352                 *nptr = '\0';
353         }
354
355         nptr = (char *)strchr(ptr, '/');
356         
357         if (!nptr) {
358                 return(4);      /* no url specified */
359         }
360         
361         strcpy(identifier, nptr);
362         return(0);
363 }
364
365
366 /*
367  * Begin a feed parse
368  */
369 void rss_do_fetching(char *url, char *rooms) {
370         char buf[1024];
371         char rsshost[1024];
372         int rssport = 80;
373         char rssurl[1024];
374         struct rss_item ri;
375         XML_Parser xp;
376         int sock = (-1);
377         int got_bytes = (-1);
378         int redirect_count = 0;
379
380         /* Parse the URL */
381         if (parse_url(url, rsshost, &rssport, rssurl) != 0) {
382                 lprintf(CTDL_ALERT, "Invalid URL: %s\n", url);
383         }
384
385         xp = XML_ParserCreateNS("UTF-8", ':');
386         if (!xp) {
387                 lprintf(CTDL_ALERT, "Cannot create XML parser!\n");
388                 return;
389         }
390
391         memset(&ri, 0, sizeof(struct rss_item));
392         ri.roomlist = rooms;
393         XML_SetElementHandler(xp, rss_xml_start, rss_xml_end);
394         XML_SetCharacterDataHandler(xp, rss_xml_chardata);
395         XML_SetUserData(xp, &ri);
396
397 retry:  lprintf(CTDL_NOTICE, "Connecting to <%s>\n", rsshost);
398         sprintf(buf, "%d", rssport);
399         sock = sock_connect(rsshost, buf, "tcp");
400         if (sock >= 0) {
401                 lprintf(CTDL_DEBUG, "Connected!\n");
402
403                 snprintf(buf, sizeof buf, "GET %s HTTP/1.0", rssurl);
404                 lprintf(CTDL_DEBUG, "<%s\n", buf);
405                 sock_puts(sock, buf);
406
407                 snprintf(buf, sizeof buf, "Host: %s", rsshost);
408                 lprintf(CTDL_DEBUG, "<%s\n", buf);
409                 sock_puts(sock, buf);
410
411                 sock_puts(sock, "");
412
413                 if (sock_getln(sock, buf, sizeof buf) >= 0) {
414                 lprintf(CTDL_DEBUG, ">%s\n", buf);
415                         remove_token(buf, 0, ' ');
416
417                         /* 200 OK */
418                         if (buf[0] == '2') {
419
420                                 while (got_bytes = sock_getln(sock, buf, sizeof buf),
421                                       (got_bytes >= 0 && (strcmp(buf, "")) && (strcmp(buf, "\r"))) ) {
422                                         /* discard headers */
423                                 }
424
425                                 while (got_bytes = sock_read(sock, buf, sizeof buf, 0),
426                                       ((got_bytes>=0) && (ri.done_parsing == 0)) ) {
427                                         XML_Parse(xp, buf, got_bytes, 0);
428                                 }
429                                 if (ri.done_parsing == 0) XML_Parse(xp, "", 0, 1);
430                         }
431
432                         /* 30X redirect */
433                         else if ( (!strncmp(buf, "30", 2)) && (redirect_count < 16) ) {
434                                 while (got_bytes = sock_getln(sock, buf, sizeof buf),
435                                       (got_bytes >= 0 && (strcmp(buf, "")) && (strcmp(buf, "\r"))) ) {
436                                         if (!strncasecmp(buf, "Location:", 9)) {
437                                                 ++redirect_count;
438                                                 strcpy(buf, &buf[9]);
439                                                 striplt(buf);
440                                                 if (parse_url(buf, rsshost, &rssport, rssurl) == 0) {
441                                                         goto retry;
442                                                 }
443                                                 else {
444                                                         lprintf(CTDL_ALERT, "Invalid URL: %s\n", buf);
445                                                 }
446                                         }
447                                 }
448                         }
449
450                 }
451                 sock_close(sock);
452         }
453         else {
454                 lprintf(CTDL_ERR, "Could not connect: %s\n", strerror(errno));
455         }
456
457         XML_ParserFree(xp);
458
459         /* Free the feed item data structure */
460         if (ri.guid != NULL) free(ri.guid);
461         ri.guid = NULL;
462         if (ri.title != NULL) free(ri.title);
463         ri.title = NULL;
464         if (ri.link != NULL) free(ri.link);
465         ri.link = NULL;
466         if (ri.description != NULL) free(ri.description);
467         ri.description = NULL;
468         if (ri.chardata_len > 0) {
469                 free(ri.chardata);
470                 ri.chardata = 0;
471                 ri.chardata_len = 0;
472         }
473 }
474
475
476 /*
477  * Scan a room's netconfig to determine whether it is requesting any RSS feeds
478  */
479 void rssclient_scan_room(struct ctdlroom *qrbuf, void *data)
480 {
481         char filename[PATH_MAX];
482         char buf[1024];
483         char instr[32];
484         FILE *fp;
485         char feedurl[256];
486         struct rssnetcfg *rncptr = NULL;
487         struct rssnetcfg *use_this_rncptr = NULL;
488         int len = 0;
489         char *ptr = NULL;
490
491         assoc_file_name(filename, sizeof filename, qrbuf, ctdl_netcfg_dir);
492
493         /* Only do net processing for rooms that have netconfigs */
494         fp = fopen(filename, "r");
495         if (fp == NULL) {
496                 return;
497         }
498
499         while (fgets(buf, sizeof buf, fp) != NULL) {
500                 buf[strlen(buf)-1] = 0;
501
502                 extract_token(instr, buf, 0, '|', sizeof instr);
503                 if (!strcasecmp(instr, "rssclient")) {
504                         extract_token(feedurl, buf, 1, '|', sizeof feedurl);
505
506                         /* If any other rooms have requested the same feed, then we will just add this
507                          * room to the target list for that client request.
508                          */
509                         for (rncptr=rnclist; rncptr!=NULL; rncptr=rncptr->next) {
510                                 if (!strcmp(rncptr->url, feedurl)) {
511                                         use_this_rncptr = rncptr;
512                                 }
513                         }
514
515                         /* Otherwise create a new client request */
516                         if (use_this_rncptr == NULL) {
517                                 rncptr = (struct rssnetcfg *) malloc(sizeof(struct rssnetcfg));
518                                 if (rncptr != NULL) {
519                                         rncptr->next = rnclist;
520                                         safestrncpy(rncptr->url, feedurl, sizeof rncptr->url);
521                                         rncptr->rooms = NULL;
522                                         rnclist = rncptr;
523                                         use_this_rncptr = rncptr;
524                                 }
525                         }
526
527                         /* Add the room name to the request */
528                         if (use_this_rncptr != NULL) {
529                                 if (use_this_rncptr->rooms == NULL) {
530                                         rncptr->rooms = strdup(qrbuf->QRname);
531                                 }
532                                 else {
533                                         len = strlen(use_this_rncptr->rooms) + strlen(qrbuf->QRname) + 5;
534                                         ptr = realloc(use_this_rncptr->rooms, len);
535                                         if (ptr != NULL) {
536                                                 strcat(ptr, "|");
537                                                 strcat(ptr, qrbuf->QRname);
538                                                 use_this_rncptr->rooms = ptr;
539                                         }
540                                 }
541                         }
542                 }
543
544         }
545
546         fclose(fp);
547
548 }
549
550 /*
551  * Scan for rooms that have RSS client requests configured
552  */
553 void rssclient_scan(void) {
554         static time_t last_run = 0L;
555         static int doing_rssclient = 0;
556         struct rssnetcfg *rptr = NULL;
557
558         /*
559          * Run RSS client no more frequently than once every n seconds
560          */
561         if ( (time(NULL) - last_run) < config.c_net_freq ) {
562                 return;
563         }
564
565         /*
566          * This is a simple concurrency check to make sure only one rssclient run
567          * is done at a time.  We could do this with a mutex, but since we
568          * don't really require extremely fine granularity here, we'll do it
569          * with a static variable instead.
570          */
571         if (doing_rssclient) return;
572         doing_rssclient = 1;
573
574         lprintf(CTDL_DEBUG, "rssclient started\n");
575         ForEachRoom(rssclient_scan_room, NULL);
576
577         while (rnclist != NULL) {
578                 rss_do_fetching(rnclist->url, rnclist->rooms);
579                 rptr = rnclist;
580                 rnclist = rnclist->next;
581                 if (rptr->rooms != NULL) free(rptr->rooms);
582                 free(rptr);
583         }
584
585         lprintf(CTDL_DEBUG, "rssclient ended\n");
586         last_run = time(NULL);
587         doing_rssclient = 0;
588 }
589
590
591 #endif  /* HAVE_EXPAT */
592
593 CTDL_MODULE_INIT(rssclient)
594 {
595 #ifdef HAVE_EXPAT
596         CtdlRegisterSessionHook(rssclient_scan, EVT_TIMER);
597 #else
598          lprintf(CTDL_INFO, "This server is missing the Expat XML parser.  RSS client will be disabled.\n");
599 #endif
600         /* return our Subversion id for the Log */
601         return "$Id: serv_rssclient.c 5652 2007-10-29 20:14:48Z ajc $";
602 }