2 * $Id: serv_rssclient.c 5652 2007-10-29 20:14:48Z ajc $
4 * Bring external RSS feeds into rooms.
12 #if TIME_WITH_SYS_TIME
13 # include <sys/time.h>
17 # include <sys/time.h>
26 #include <sys/types.h>
30 #include "citserver.h"
35 #include "ctdl_module.h"
36 #include "clientsocket.h"
39 #include "citadel_dirs.h"
47 struct rssnetcfg *next;
62 int channel_tag_nesting;
63 char channel_title[256];
67 struct rssnetcfg *rnclist = NULL;
71 * Commit a fetched and parsed RSS item to disk
73 void rss_save_item(struct rss_item *ri) {
75 struct MD5Context md5context;
76 u_char rawdigest[MD5_DIGEST_LEN];
79 struct cdbdata *cdbut;
81 struct CtdlMessage *msg;
82 struct recptypes *recp = NULL;
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;
92 /* Construct a GUID to use in the S_USETABLE table.
93 * If one is not present in the item itself, make one up.
95 if (ri->guid != NULL) {
96 snprintf(utmsgid, sizeof utmsgid, "rss/%s", ri->guid);
100 if (ri->title != NULL) {
101 MD5Update(&md5context, ri->title, strlen(ri->title));
103 if (ri->link != NULL) {
104 MD5Update(&md5context, ri->link, strlen(ri->link));
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]);
112 strcat(utmsgid, "_rss2ctdl");
115 /* Find out if we've already seen this item */
116 cdbut = cdb_fetch(CDB_USETABLE, utmsgid, strlen(utmsgid));
118 /* Item has already been seen */
119 lprintf(CTDL_DEBUG, "%s has already been seen\n", utmsgid);
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) );
128 /* Item has not been seen, so save it. */
130 for (i=strlen(ri->description); i>=0; --i) {
131 if (isspace(ri->description[i])) {
132 ri->description[i] = ' ';
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);
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"
156 "<a href=\"%s\">%s</a>\n"
163 CtdlSubmitMsg(msg, recp, NULL);
164 CtdlFreeMessage(msg);
165 free_recipients(recp);
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) );
177 * Convert an RDF/RSS datestamp into a time_t
179 time_t rdf_parsedate(char *p)
184 if (strlen(p) < 10) return 0L;
186 memset(&tm, 0, sizeof tm);
188 /* YYYY-MM-DDTHH:MM format...
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]);
201 /* FIXME try an imap timestamp conversion */
209 void rss_xml_start(void *data, const char *el, const char **attr) {
210 struct rss_item *ri = (struct rss_item *) data;
212 if (!strcasecmp(el, "channel")) {
213 ++ri->channel_tag_nesting;
216 if (!strcasecmp(el, "item")) {
217 ++ri->item_tag_nesting;
219 /* Initialize the feed item data structure */
220 if (ri->guid != NULL) free(ri->guid);
222 if (ri->title != NULL) free(ri->title);
224 if (ri->link != NULL) free(ri->link);
226 if (ri->description != NULL) free(ri->description);
227 ri->description = NULL;
229 /* Throw away any existing character data */
230 if (ri->chardata_len > 0) {
233 ri->chardata_len = 0;
241 void rss_xml_end(void *data, const char *supplied_el) {
242 struct rss_item *ri = (struct rss_item *) data;
247 /* Axe the namespace, we don't care about it */
248 safestrncpy(el, supplied_el, sizeof el);
249 while (sep = strchr(el, ':'), sep) {
253 if (!strcasecmp(el, "channel")) {
254 --ri->channel_tag_nesting;
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);
262 if (!strcasecmp(el, "guid")) {
263 if (ri->guid != NULL) free(ri->guid);
264 striplt(ri->chardata);
265 ri->guid = strdup(ri->chardata);
268 if (!strcasecmp(el, "title")) {
269 if (ri->title != NULL) free(ri->title);
270 striplt(ri->chardata);
271 ri->title = strdup(ri->chardata);
274 if (!strcasecmp(el, "link")) {
275 if (ri->link != NULL) free(ri->link);
276 striplt(ri->chardata);
277 ri->link = strdup(ri->chardata);
280 if (!strcasecmp(el, "description")) {
281 if (ri->description != NULL) free(ri->description);
282 ri->description = strdup(ri->chardata);
285 if ( (!strcasecmp(el, "pubdate")) || (!strcasecmp(el, "date")) ) {
286 striplt(ri->chardata);
287 ri->pubdate = rdf_parsedate(ri->chardata);
290 if (!strcasecmp(el, "item")) {
291 --ri->item_tag_nesting;
295 if ( (!strcasecmp(el, "rss")) || (!strcasecmp(el, "rdf")) ) {
296 lprintf(CTDL_DEBUG, "End of feed detected. Closing parser.\n");
297 ri->done_parsing = 1;
300 if (ri->chardata_len > 0) {
303 ri->chardata_len = 0;
310 * This callback stores up the data which appears in between tags.
312 void rss_xml_chardata(void *data, const XML_Char *s, int len) {
313 struct rss_item *ri = (struct rss_item *) data;
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;
332 * Parse a URL into host, port number, and resource identifier.
334 int parse_url(char *url, char *hostname, int *port, char *identifier)
341 strcpy(scratch, url);
342 ptr = (char *)strchr(scratch, ':');
344 return(1); /* no protocol specified */
348 strcpy(protocol, scratch);
349 if (strcmp(protocol, "http")) {
350 return(2); /* not HTTP */
353 strcpy(scratch, url);
354 ptr = (char *) strstr(scratch, "//");
356 return(3); /* no server specified */
360 strcpy(hostname, ptr);
361 nptr = (char *)strchr(ptr, ':');
363 *port = 80; /* default */
364 nptr = (char *)strchr(hostname, '/');
367 sscanf(nptr, ":%d", port);
368 nptr = (char *)strchr(hostname, ':');
375 nptr = (char *)strchr(ptr, '/');
378 return(4); /* no url specified */
381 strcpy(identifier, nptr);
389 void rss_do_fetching(char *url, char *rooms) {
397 int got_bytes = (-1);
398 int redirect_count = 0;
401 if (parse_url(url, rsshost, &rssport, rssurl) != 0) {
402 lprintf(CTDL_ALERT, "Invalid URL: %s\n", url);
405 xp = XML_ParserCreateNS("UTF-8", ':');
407 lprintf(CTDL_ALERT, "Cannot create XML parser!\n");
411 memset(&ri, 0, sizeof(struct rss_item));
413 XML_SetElementHandler(xp, rss_xml_start, rss_xml_end);
414 XML_SetCharacterDataHandler(xp, rss_xml_chardata);
415 XML_SetUserData(xp, &ri);
417 retry: lprintf(CTDL_NOTICE, "Connecting to <%s>\n", rsshost);
418 sprintf(buf, "%d", rssport);
419 sock = sock_connect(rsshost, buf, "tcp");
421 lprintf(CTDL_DEBUG, "Connected!\n");
423 snprintf(buf, sizeof buf, "GET %s HTTP/1.0", rssurl);
424 lprintf(CTDL_DEBUG, "<%s\n", buf);
425 sock_puts(sock, buf);
427 snprintf(buf, sizeof buf, "Host: %s", rsshost);
428 lprintf(CTDL_DEBUG, "<%s\n", buf);
429 sock_puts(sock, buf);
433 if (sock_getln(sock, buf, sizeof buf) >= 0) {
434 lprintf(CTDL_DEBUG, ">%s\n", buf);
435 remove_token(buf, 0, ' ');
440 while (got_bytes = sock_getln(sock, buf, sizeof buf),
441 (got_bytes >= 0 && (strcmp(buf, "")) && (strcmp(buf, "\r"))) ) {
442 /* discard headers */
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);
449 if (ri.done_parsing == 0) XML_Parse(xp, "", 0, 1);
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)) {
458 strcpy(buf, &buf[9]);
460 if (parse_url(buf, rsshost, &rssport, rssurl) == 0) {
464 lprintf(CTDL_ALERT, "Invalid URL: %s\n", buf);
474 lprintf(CTDL_ERR, "Could not connect: %s\n", strerror(errno));
479 /* Free the feed item data structure */
480 if (ri.guid != NULL) free(ri.guid);
482 if (ri.title != NULL) free(ri.title);
484 if (ri.link != NULL) free(ri.link);
486 if (ri.description != NULL) free(ri.description);
487 ri.description = NULL;
488 if (ri.chardata_len > 0) {
497 * Scan a room's netconfig to determine whether it is requesting any RSS feeds
499 void rssclient_scan_room(struct ctdlroom *qrbuf, void *data)
501 char filename[PATH_MAX];
506 struct rssnetcfg *rncptr = NULL;
507 struct rssnetcfg *use_this_rncptr = NULL;
511 assoc_file_name(filename, sizeof filename, qrbuf, ctdl_netcfg_dir);
513 /* Only do net processing for rooms that have netconfigs */
514 fp = fopen(filename, "r");
519 while (fgets(buf, sizeof buf, fp) != NULL) {
520 buf[strlen(buf)-1] = 0;
522 extract_token(instr, buf, 0, '|', sizeof instr);
523 if (!strcasecmp(instr, "rssclient")) {
524 extract_token(feedurl, buf, 1, '|', sizeof feedurl);
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.
529 for (rncptr=rnclist; rncptr!=NULL; rncptr=rncptr->next) {
530 if (!strcmp(rncptr->url, feedurl)) {
531 use_this_rncptr = rncptr;
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;
543 use_this_rncptr = rncptr;
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);
553 len = strlen(use_this_rncptr->rooms) + strlen(qrbuf->QRname) + 5;
554 ptr = realloc(use_this_rncptr->rooms, len);
557 strcat(ptr, qrbuf->QRname);
558 use_this_rncptr->rooms = ptr;
571 * Scan for rooms that have RSS client requests configured
573 void rssclient_scan(void) {
574 static time_t last_run = 0L;
575 static int doing_rssclient = 0;
576 struct rssnetcfg *rptr = NULL;
579 * Run RSS client no more frequently than once every n seconds
581 if ( (time(NULL) - last_run) < config.c_net_freq ) {
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.
591 if (doing_rssclient) return;
594 lprintf(CTDL_DEBUG, "rssclient started\n");
595 ForEachRoom(rssclient_scan_room, NULL);
597 while (rnclist != NULL) {
598 rss_do_fetching(rnclist->url, rnclist->rooms);
600 rnclist = rnclist->next;
601 if (rptr->rooms != NULL) free(rptr->rooms);
605 lprintf(CTDL_DEBUG, "rssclient ended\n");
606 last_run = time(NULL);
611 #endif /* HAVE_EXPAT */
613 CTDL_MODULE_INIT(rssclient)
616 CtdlRegisterSessionHook(rssclient_scan, EVT_TIMER);
618 lprintf(CTDL_INFO, "This server is missing the Expat XML parser. RSS client will be disabled.\n");
620 /* return our Subversion id for the Log */
621 return "$Id: serv_rssclient.c 5652 2007-10-29 20:14:48Z ajc $";