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>
28 #include <libcitadel.h>
31 #include "citserver.h"
35 #include "ctdl_module.h"
36 #include "clientsocket.h"
38 #include "parsedate.h"
40 #include "citadel_dirs.h"
48 struct rssnetcfg *next;
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 if (ri->description == NULL) ri->description = strdup("");
131 for (i=strlen(ri->description); i>=0; --i) {
132 if (isspace(ri->description[i])) {
133 ri->description[i] = ' ';
137 msg = malloc(sizeof(struct CtdlMessage));
138 memset(msg, 0, sizeof(struct CtdlMessage));
139 msg->cm_magic = CTDLMESSAGE_MAGIC;
140 msg->cm_anon_type = MES_NORMAL;
141 msg->cm_format_type = FMT_RFC822;
142 msg->cm_fields['A'] = strdup("rss");
143 msg->cm_fields['N'] = strdup(NODENAME);
144 msg->cm_fields['U'] = strdup(ri->title);
145 msg->cm_fields['T'] = malloc(64);
146 snprintf(msg->cm_fields['T'], 64, "%ld", ri->pubdate);
147 if (!IsEmptyStr(ri->channel_title)) {
148 msg->cm_fields['O'] = strdup(ri->channel_title);
151 msglen = 1024 + strlen(ri->link) + strlen(ri->description) ;
152 msg->cm_fields['M'] = malloc(msglen);
153 snprintf(msg->cm_fields['M'], msglen,
154 "Content-type: text/html\r\n\r\n"
157 "<a href=\"%s\">%s</a>\n"
164 CtdlSubmitMsg(msg, recp, NULL);
165 CtdlFreeMessage(msg);
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) );
172 free_recipients(recp);
178 * Convert an RDF/RSS datestamp into a time_t
180 time_t rdf_parsedate(char *p)
186 if (strlen(p) < 10) return 0L;
188 memset(&tm, 0, sizeof tm);
190 /* YYYY-MM-DDTHH:MM format...
192 if ( (p[4] == '-') && (p[7] == '-') ) {
193 tm.tm_year = atoi(&p[0]) - 1900;
194 tm.tm_mon = atoi(&p[5]) - 1;
195 tm.tm_mday = atoi(&p[8]);
196 if ( (p[10] == 'T') && (p[13] == ':') ) {
197 tm.tm_hour = atoi(&p[11]);
198 tm.tm_min = atoi(&p[14]);
203 /* hmm... try RFC822 date stamp format */
206 if (t > 0) return(t);
208 /* yeesh. ok, just return the current date and time. */
214 void rss_xml_start(void *data, const char *supplied_el, const char **attr) {
215 struct rss_item *ri = (struct rss_item *) data;
219 /* Axe the namespace, we don't care about it */
220 safestrncpy(el, supplied_el, sizeof el);
221 while (sep = strchr(el, ':'), sep) {
225 if (!strcasecmp(el, "item")) {
226 ++ri->item_tag_nesting;
228 /* Initialize the feed item data structure */
229 if (ri->guid != NULL) free(ri->guid);
231 if (ri->title != NULL) free(ri->title);
233 if (ri->link != NULL) free(ri->link);
235 if (ri->description != NULL) free(ri->description);
236 ri->description = NULL;
238 /* Throw away any existing character data */
239 if (ri->chardata_len > 0) {
242 ri->chardata_len = 0;
250 void rss_xml_end(void *data, const char *supplied_el) {
251 struct rss_item *ri = (struct rss_item *) data;
255 /* Axe the namespace, we don't care about it */
256 safestrncpy(el, supplied_el, sizeof el);
257 while (sep = strchr(el, ':'), sep) {
261 if ( (!strcasecmp(el, "title")) && (ri->item_tag_nesting == 0) && (ri->chardata != NULL) ) {
262 safestrncpy(ri->channel_title, ri->chardata, sizeof ri->channel_title);
263 striplt(ri->channel_title);
266 if ( (!strcasecmp(el, "guid")) && (ri->chardata != NULL) ) {
267 if (ri->guid != NULL) free(ri->guid);
268 striplt(ri->chardata);
269 ri->guid = strdup(ri->chardata);
272 if ( (!strcasecmp(el, "title")) && (ri->chardata != NULL) ) {
273 if (ri->title != NULL) free(ri->title);
274 striplt(ri->chardata);
275 ri->title = strdup(ri->chardata);
278 if ( (!strcasecmp(el, "link")) && (ri->chardata != NULL) ) {
279 if (ri->link != NULL) free(ri->link);
280 striplt(ri->chardata);
281 ri->link = strdup(ri->chardata);
284 if ( (!strcasecmp(el, "description")) && (ri->chardata != NULL) ) {
285 if (ri->description != NULL) free(ri->description);
286 ri->description = strdup(ri->chardata);
289 if ( ((!strcasecmp(el, "pubdate")) || (!strcasecmp(el, "date"))) && (ri->chardata != NULL) ) {
290 striplt(ri->chardata);
291 ri->pubdate = rdf_parsedate(ri->chardata);
294 if (!strcasecmp(el, "item")) {
295 --ri->item_tag_nesting;
299 if ( (!strcasecmp(el, "rss")) || (!strcasecmp(el, "rdf")) ) {
300 lprintf(CTDL_DEBUG, "End of feed detected. Closing parser.\n");
301 ri->done_parsing = 1;
304 if (ri->chardata_len > 0) {
307 ri->chardata_len = 0;
314 * This callback stores up the data which appears in between tags.
316 void rss_xml_chardata(void *data, const XML_Char *s, int len) {
317 struct rss_item *ri = (struct rss_item *) data;
322 old_len = ri->chardata_len;
323 new_len = old_len + len;
324 new_buffer = realloc(ri->chardata, new_len + 1);
325 if (new_buffer != NULL) {
326 memcpy(&new_buffer[old_len], s, len);
327 new_buffer[new_len] = 0;
328 ri->chardata = new_buffer;
329 ri->chardata_len = new_len;
336 * Parse a URL into host, port number, and resource identifier.
338 int parse_url(char *url, char *hostname, int *port, char *identifier)
345 strcpy(scratch, url);
346 ptr = (char *)strchr(scratch, ':');
348 return(1); /* no protocol specified */
352 strcpy(protocol, scratch);
353 if (strcmp(protocol, "http")) {
354 return(2); /* not HTTP */
357 strcpy(scratch, url);
358 ptr = (char *) strstr(scratch, "//");
360 return(3); /* no server specified */
364 strcpy(hostname, ptr);
365 nptr = (char *)strchr(ptr, ':');
367 *port = 80; /* default */
368 nptr = (char *)strchr(hostname, '/');
371 sscanf(nptr, ":%d", port);
372 nptr = (char *)strchr(hostname, ':');
379 nptr = (char *)strchr(ptr, '/');
382 return(4); /* no url specified */
385 strcpy(identifier, nptr);
393 void rss_do_fetching(char *url, char *rooms) {
401 int got_bytes = (-1);
402 int redirect_count = 0;
405 if (parse_url(url, rsshost, &rssport, rssurl) != 0) {
406 lprintf(CTDL_ALERT, "Invalid URL: %s\n", url);
409 xp = XML_ParserCreateNS("UTF-8", ':');
411 lprintf(CTDL_ALERT, "Cannot create XML parser!\n");
415 memset(&ri, 0, sizeof(struct rss_item));
417 XML_SetElementHandler(xp, rss_xml_start, rss_xml_end);
418 XML_SetCharacterDataHandler(xp, rss_xml_chardata);
419 XML_SetUserData(xp, &ri);
421 retry: lprintf(CTDL_NOTICE, "Connecting to <%s>\n", rsshost);
422 sprintf(buf, "%d", rssport);
423 sock = sock_connect(rsshost, buf, "tcp");
425 lprintf(CTDL_DEBUG, "Connected!\n");
427 snprintf(buf, sizeof buf, "GET %s HTTP/1.0", rssurl);
428 lprintf(CTDL_DEBUG, "<%s\n", buf);
429 sock_puts(sock, buf);
431 snprintf(buf, sizeof buf, "Host: %s", rsshost);
432 lprintf(CTDL_DEBUG, "<%s\n", buf);
433 sock_puts(sock, buf);
435 snprintf(buf, sizeof buf, "User-Agent: %s", CITADEL);
436 lprintf(CTDL_DEBUG, "<%s\n", buf);
437 sock_puts(sock, buf);
439 snprintf(buf, sizeof buf, "Accept: */*");
440 lprintf(CTDL_DEBUG, "<%s\n", buf);
441 sock_puts(sock, buf);
445 if (sock_getln(sock, buf, sizeof buf) >= 0) {
446 lprintf(CTDL_DEBUG, ">%s\n", buf);
447 remove_token(buf, 0, ' ');
452 while (got_bytes = sock_getln(sock, buf, sizeof buf),
453 (got_bytes >= 0 && (strcmp(buf, "")) && (strcmp(buf, "\r"))) ) {
454 /* discard headers */
457 while (got_bytes = sock_read(sock, buf, sizeof buf, 0),
458 ((got_bytes>=0) && (ri.done_parsing == 0)) ) {
459 XML_Parse(xp, buf, got_bytes, 0);
461 if (ri.done_parsing == 0) XML_Parse(xp, "", 0, 1);
465 else if ( (!strncmp(buf, "30", 2)) && (redirect_count < 16) ) {
466 while (got_bytes = sock_getln(sock, buf, sizeof buf),
467 (got_bytes >= 0 && (strcmp(buf, "")) && (strcmp(buf, "\r"))) ) {
468 if (!strncasecmp(buf, "Location:", 9)) {
470 strcpy(buf, &buf[9]);
472 if (parse_url(buf, rsshost, &rssport, rssurl) == 0) {
476 lprintf(CTDL_ALERT, "Invalid URL: %s\n", buf);
486 lprintf(CTDL_ERR, "Could not connect: %s\n", strerror(errno));
491 /* Free the feed item data structure */
492 if (ri.guid != NULL) free(ri.guid);
494 if (ri.title != NULL) free(ri.title);
496 if (ri.link != NULL) free(ri.link);
498 if (ri.description != NULL) free(ri.description);
499 ri.description = NULL;
500 if (ri.chardata_len > 0) {
509 * Scan a room's netconfig to determine whether it is requesting any RSS feeds
511 void rssclient_scan_room(struct ctdlroom *qrbuf, void *data)
513 char filename[PATH_MAX];
518 struct rssnetcfg *rncptr = NULL;
519 struct rssnetcfg *use_this_rncptr = NULL;
523 assoc_file_name(filename, sizeof filename, qrbuf, ctdl_netcfg_dir);
525 /* Only do net processing for rooms that have netconfigs */
526 fp = fopen(filename, "r");
531 while (fgets(buf, sizeof buf, fp) != NULL) {
532 buf[strlen(buf)-1] = 0;
534 extract_token(instr, buf, 0, '|', sizeof instr);
535 if (!strcasecmp(instr, "rssclient")) {
537 use_this_rncptr = NULL;
539 extract_token(feedurl, buf, 1, '|', sizeof feedurl);
541 /* If any other rooms have requested the same feed, then we will just add this
542 * room to the target list for that client request.
544 for (rncptr=rnclist; rncptr!=NULL; rncptr=rncptr->next) {
545 if (!strcmp(rncptr->url, feedurl)) {
546 use_this_rncptr = rncptr;
550 /* Otherwise create a new client request */
551 if (use_this_rncptr == NULL) {
552 rncptr = (struct rssnetcfg *) malloc(sizeof(struct rssnetcfg));
553 if (rncptr != NULL) {
554 rncptr->next = rnclist;
555 safestrncpy(rncptr->url, feedurl, sizeof rncptr->url);
556 rncptr->rooms = NULL;
558 use_this_rncptr = rncptr;
562 /* Add the room name to the request */
563 if (use_this_rncptr != NULL) {
564 if (use_this_rncptr->rooms == NULL) {
565 rncptr->rooms = strdup(qrbuf->QRname);
568 len = strlen(use_this_rncptr->rooms) + strlen(qrbuf->QRname) + 5;
569 ptr = realloc(use_this_rncptr->rooms, len);
572 strcat(ptr, qrbuf->QRname);
573 use_this_rncptr->rooms = ptr;
586 * Scan for rooms that have RSS client requests configured
588 void *rssclient_scan(void *args) {
589 static time_t last_run = 0L;
590 static int doing_rssclient = 0;
591 struct rssnetcfg *rptr = NULL;
593 CtdlThreadAllocTSD();
595 * Run RSS client no more frequently than once every n seconds
597 // if ( (time(NULL) - last_run) < config.c_net_freq ) {
602 * This is a simple concurrency check to make sure only one rssclient run
603 * is done at a time. We could do this with a mutex, but since we
604 * don't really require extremely fine granularity here, we'll do it
605 * with a static variable instead.
607 if (doing_rssclient) return NULL;
610 lprintf(CTDL_DEBUG, "rssclient started\n");
611 ForEachRoom(rssclient_scan_room, NULL);
613 while (rnclist != NULL) {
614 rss_do_fetching(rnclist->url, rnclist->rooms);
616 rnclist = rnclist->next;
617 if (rptr->rooms != NULL) free(rptr->rooms);
621 lprintf(CTDL_DEBUG, "rssclient ended\n");
622 last_run = time(NULL);
624 CtdlThreadSchedule ("RSS Client", CTDLTHREAD_BIGSTACK, rssclient_scan, NULL, last_run + config.c_net_freq);
629 #endif /* HAVE_EXPAT */
631 CTDL_MODULE_INIT(rssclient)
636 // CtdlRegisterSessionHook(rssclient_scan, EVT_TIMER);
637 CtdlThreadSchedule ("RSS Client", CTDLTHREAD_BIGSTACK, rssclient_scan, NULL, 0);
639 lprintf(CTDL_INFO, "This server is missing the Expat XML parser. RSS client will be disabled.\n");
643 /* return our Subversion id for the Log */
644 return "$Id: serv_rssclient.c 5652 2007-10-29 20:14:48Z ajc $";