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 char channel_title[256];
66 struct rssnetcfg *rnclist = NULL;
70 * Commit a fetched and parsed RSS item to disk
72 void rss_save_item(struct rss_item *ri) {
74 struct MD5Context md5context;
75 u_char rawdigest[MD5_DIGEST_LEN];
78 struct cdbdata *cdbut;
80 struct CtdlMessage *msg;
81 struct recptypes *recp = NULL;
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;
91 /* Construct a GUID to use in the S_USETABLE table.
92 * If one is not present in the item itself, make one up.
94 if (ri->guid != NULL) {
95 snprintf(utmsgid, sizeof utmsgid, "rss/%s", ri->guid);
99 if (ri->title != NULL) {
100 MD5Update(&md5context, ri->title, strlen(ri->title));
102 if (ri->link != NULL) {
103 MD5Update(&md5context, ri->link, strlen(ri->link));
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]);
111 strcat(utmsgid, "_rss2ctdl");
114 /* Find out if we've already seen this item */
115 cdbut = cdb_fetch(CDB_USETABLE, utmsgid, strlen(utmsgid));
117 /* Item has already been seen */
118 lprintf(CTDL_DEBUG, "%s has already been seen\n", utmsgid);
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) );
127 /* Item has not been seen, so save it. */
129 for (i=strlen(ri->description); i>=0; --i) {
130 if (isspace(ri->description[i])) {
131 ri->description[i] = ' ';
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);
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"
155 "<a href=\"%s\">%s</a>\n"
162 CtdlSubmitMsg(msg, recp, NULL);
163 CtdlFreeMessage(msg);
164 free_recipients(recp);
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) );
176 * Convert an RDF/RSS datestamp into a time_t
178 time_t rdf_parsedate(char *p)
183 if (strlen(p) < 10) return 0L;
185 memset(&tm, 0, sizeof tm);
187 /* YYYY-MM-DDTHH:MM format...
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]);
200 /* FIXME try an imap timestamp conversion */
208 void rss_xml_start(void *data, const char *supplied_el, const char **attr) {
209 struct rss_item *ri = (struct rss_item *) data;
213 /* Axe the namespace, we don't care about it */
214 safestrncpy(el, supplied_el, sizeof el);
215 while (sep = strchr(el, ':'), sep) {
219 if (!strcasecmp(el, "item")) {
220 ++ri->item_tag_nesting;
222 /* Initialize the feed item data structure */
223 if (ri->guid != NULL) free(ri->guid);
225 if (ri->title != NULL) free(ri->title);
227 if (ri->link != NULL) free(ri->link);
229 if (ri->description != NULL) free(ri->description);
230 ri->description = NULL;
232 /* Throw away any existing character data */
233 if (ri->chardata_len > 0) {
236 ri->chardata_len = 0;
244 void rss_xml_end(void *data, const char *supplied_el) {
245 struct rss_item *ri = (struct rss_item *) data;
249 /* Axe the namespace, we don't care about it */
250 safestrncpy(el, supplied_el, sizeof el);
251 while (sep = strchr(el, ':'), sep) {
255 if ( (!strcasecmp(el, "title")) && (ri->item_tag_nesting == 0) && (ri->chardata != NULL) ) {
256 safestrncpy(ri->channel_title, ri->chardata, sizeof ri->channel_title);
257 striplt(ri->channel_title);
260 if ( (!strcasecmp(el, "guid")) && (ri->chardata != NULL) ) {
261 if (ri->guid != NULL) free(ri->guid);
262 striplt(ri->chardata);
263 ri->guid = strdup(ri->chardata);
266 if ( (!strcasecmp(el, "title")) && (ri->chardata != NULL) ) {
267 if (ri->title != NULL) free(ri->title);
268 striplt(ri->chardata);
269 ri->title = strdup(ri->chardata);
272 if ( (!strcasecmp(el, "link")) && (ri->chardata != NULL) ) {
273 if (ri->link != NULL) free(ri->link);
274 striplt(ri->chardata);
275 ri->link = strdup(ri->chardata);
278 if ( (!strcasecmp(el, "description")) && (ri->chardata != NULL) ) {
279 if (ri->description != NULL) free(ri->description);
280 ri->description = strdup(ri->chardata);
283 if ( ((!strcasecmp(el, "pubdate")) || (!strcasecmp(el, "date"))) && (ri->chardata != NULL) ) {
284 striplt(ri->chardata);
285 ri->pubdate = rdf_parsedate(ri->chardata);
288 if (!strcasecmp(el, "item")) {
289 --ri->item_tag_nesting;
293 if ( (!strcasecmp(el, "rss")) || (!strcasecmp(el, "rdf")) ) {
294 lprintf(CTDL_DEBUG, "End of feed detected. Closing parser.\n");
295 ri->done_parsing = 1;
298 if (ri->chardata_len > 0) {
301 ri->chardata_len = 0;
308 * This callback stores up the data which appears in between tags.
310 void rss_xml_chardata(void *data, const XML_Char *s, int len) {
311 struct rss_item *ri = (struct rss_item *) data;
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;
330 * Parse a URL into host, port number, and resource identifier.
332 int parse_url(char *url, char *hostname, int *port, char *identifier)
339 strcpy(scratch, url);
340 ptr = (char *)strchr(scratch, ':');
342 return(1); /* no protocol specified */
346 strcpy(protocol, scratch);
347 if (strcmp(protocol, "http")) {
348 return(2); /* not HTTP */
351 strcpy(scratch, url);
352 ptr = (char *) strstr(scratch, "//");
354 return(3); /* no server specified */
358 strcpy(hostname, ptr);
359 nptr = (char *)strchr(ptr, ':');
361 *port = 80; /* default */
362 nptr = (char *)strchr(hostname, '/');
365 sscanf(nptr, ":%d", port);
366 nptr = (char *)strchr(hostname, ':');
373 nptr = (char *)strchr(ptr, '/');
376 return(4); /* no url specified */
379 strcpy(identifier, nptr);
387 void rss_do_fetching(char *url, char *rooms) {
395 int got_bytes = (-1);
396 int redirect_count = 0;
399 if (parse_url(url, rsshost, &rssport, rssurl) != 0) {
400 lprintf(CTDL_ALERT, "Invalid URL: %s\n", url);
403 xp = XML_ParserCreateNS("UTF-8", ':');
405 lprintf(CTDL_ALERT, "Cannot create XML parser!\n");
409 memset(&ri, 0, sizeof(struct rss_item));
411 XML_SetElementHandler(xp, rss_xml_start, rss_xml_end);
412 XML_SetCharacterDataHandler(xp, rss_xml_chardata);
413 XML_SetUserData(xp, &ri);
415 retry: lprintf(CTDL_NOTICE, "Connecting to <%s>\n", rsshost);
416 sprintf(buf, "%d", rssport);
417 sock = sock_connect(rsshost, buf, "tcp");
419 lprintf(CTDL_DEBUG, "Connected!\n");
421 snprintf(buf, sizeof buf, "GET %s HTTP/1.0", rssurl);
422 lprintf(CTDL_DEBUG, "<%s\n", buf);
423 sock_puts(sock, buf);
425 snprintf(buf, sizeof buf, "Host: %s", rsshost);
426 lprintf(CTDL_DEBUG, "<%s\n", buf);
427 sock_puts(sock, buf);
429 snprintf(buf, sizeof buf, "User-Agent: %s", CITADEL);
430 lprintf(CTDL_DEBUG, "<%s\n", buf);
431 sock_puts(sock, buf);
433 snprintf(buf, sizeof buf, "Accept: */*");
434 lprintf(CTDL_DEBUG, "<%s\n", buf);
435 sock_puts(sock, buf);
439 if (sock_getln(sock, buf, sizeof buf) >= 0) {
440 lprintf(CTDL_DEBUG, ">%s\n", buf);
441 remove_token(buf, 0, ' ');
446 while (got_bytes = sock_getln(sock, buf, sizeof buf),
447 (got_bytes >= 0 && (strcmp(buf, "")) && (strcmp(buf, "\r"))) ) {
448 /* discard headers */
451 while (got_bytes = sock_read(sock, buf, sizeof buf, 0),
452 ((got_bytes>=0) && (ri.done_parsing == 0)) ) {
453 XML_Parse(xp, buf, got_bytes, 0);
455 if (ri.done_parsing == 0) XML_Parse(xp, "", 0, 1);
459 else if ( (!strncmp(buf, "30", 2)) && (redirect_count < 16) ) {
460 while (got_bytes = sock_getln(sock, buf, sizeof buf),
461 (got_bytes >= 0 && (strcmp(buf, "")) && (strcmp(buf, "\r"))) ) {
462 if (!strncasecmp(buf, "Location:", 9)) {
464 strcpy(buf, &buf[9]);
466 if (parse_url(buf, rsshost, &rssport, rssurl) == 0) {
470 lprintf(CTDL_ALERT, "Invalid URL: %s\n", buf);
480 lprintf(CTDL_ERR, "Could not connect: %s\n", strerror(errno));
485 /* Free the feed item data structure */
486 if (ri.guid != NULL) free(ri.guid);
488 if (ri.title != NULL) free(ri.title);
490 if (ri.link != NULL) free(ri.link);
492 if (ri.description != NULL) free(ri.description);
493 ri.description = NULL;
494 if (ri.chardata_len > 0) {
503 * Scan a room's netconfig to determine whether it is requesting any RSS feeds
505 void rssclient_scan_room(struct ctdlroom *qrbuf, void *data)
507 char filename[PATH_MAX];
512 struct rssnetcfg *rncptr = NULL;
513 struct rssnetcfg *use_this_rncptr = NULL;
517 assoc_file_name(filename, sizeof filename, qrbuf, ctdl_netcfg_dir);
519 /* Only do net processing for rooms that have netconfigs */
520 fp = fopen(filename, "r");
525 while (fgets(buf, sizeof buf, fp) != NULL) {
526 buf[strlen(buf)-1] = 0;
528 extract_token(instr, buf, 0, '|', sizeof instr);
529 if (!strcasecmp(instr, "rssclient")) {
531 use_this_rncptr = NULL;
533 extract_token(feedurl, buf, 1, '|', sizeof feedurl);
535 /* If any other rooms have requested the same feed, then we will just add this
536 * room to the target list for that client request.
538 for (rncptr=rnclist; rncptr!=NULL; rncptr=rncptr->next) {
539 if (!strcmp(rncptr->url, feedurl)) {
540 use_this_rncptr = rncptr;
544 /* Otherwise create a new client request */
545 if (use_this_rncptr == NULL) {
546 rncptr = (struct rssnetcfg *) malloc(sizeof(struct rssnetcfg));
547 if (rncptr != NULL) {
548 rncptr->next = rnclist;
549 safestrncpy(rncptr->url, feedurl, sizeof rncptr->url);
550 rncptr->rooms = NULL;
552 use_this_rncptr = rncptr;
556 /* Add the room name to the request */
557 if (use_this_rncptr != NULL) {
558 if (use_this_rncptr->rooms == NULL) {
559 rncptr->rooms = strdup(qrbuf->QRname);
562 len = strlen(use_this_rncptr->rooms) + strlen(qrbuf->QRname) + 5;
563 ptr = realloc(use_this_rncptr->rooms, len);
566 strcat(ptr, qrbuf->QRname);
567 use_this_rncptr->rooms = ptr;
580 * Scan for rooms that have RSS client requests configured
582 void rssclient_scan(void) {
583 static time_t last_run = 0L;
584 static int doing_rssclient = 0;
585 struct rssnetcfg *rptr = NULL;
588 * Run RSS client no more frequently than once every n seconds
590 if ( (time(NULL) - last_run) < config.c_net_freq ) {
595 * This is a simple concurrency check to make sure only one rssclient run
596 * is done at a time. We could do this with a mutex, but since we
597 * don't really require extremely fine granularity here, we'll do it
598 * with a static variable instead.
600 if (doing_rssclient) return;
603 lprintf(CTDL_DEBUG, "rssclient started\n");
604 ForEachRoom(rssclient_scan_room, NULL);
606 while (rnclist != NULL) {
607 rss_do_fetching(rnclist->url, rnclist->rooms);
609 rnclist = rnclist->next;
610 if (rptr->rooms != NULL) free(rptr->rooms);
614 lprintf(CTDL_DEBUG, "rssclient ended\n");
615 last_run = time(NULL);
620 #endif /* HAVE_EXPAT */
622 CTDL_MODULE_INIT(rssclient)
625 CtdlRegisterSessionHook(rssclient_scan, EVT_TIMER);
627 lprintf(CTDL_INFO, "This server is missing the Expat XML parser. RSS client will be disabled.\n");
629 /* return our Subversion id for the Log */
630 return "$Id: serv_rssclient.c 5652 2007-10-29 20:14:48Z ajc $";