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"
36 #include "ctdl_module.h"
37 #include "clientsocket.h"
39 #include "parsedate.h"
41 #include "citadel_dirs.h"
49 struct rssnetcfg *next;
64 char channel_title[256];
68 struct rssnetcfg *rnclist = NULL;
72 * Commit a fetched and parsed RSS item to disk
74 void rss_save_item(struct rss_item *ri) {
76 struct MD5Context md5context;
77 u_char rawdigest[MD5_DIGEST_LEN];
80 struct cdbdata *cdbut;
82 struct CtdlMessage *msg;
83 struct recptypes *recp = NULL;
86 recp = (struct recptypes *) malloc(sizeof(struct recptypes));
87 if (recp == NULL) return;
88 memset(recp, 0, sizeof(struct recptypes));
89 recp->recp_room = strdup(ri->roomlist);
90 recp->num_room = num_tokens(ri->roomlist, '|');
91 recp->recptypes_magic = RECPTYPES_MAGIC;
93 /* Construct a GUID to use in the S_USETABLE table.
94 * If one is not present in the item itself, make one up.
96 if (ri->guid != NULL) {
97 snprintf(utmsgid, sizeof utmsgid, "rss/%s", ri->guid);
100 MD5Init(&md5context);
101 if (ri->title != NULL) {
102 MD5Update(&md5context, ri->title, strlen(ri->title));
104 if (ri->link != NULL) {
105 MD5Update(&md5context, ri->link, strlen(ri->link));
107 MD5Final(rawdigest, &md5context);
108 for (i=0; i<MD5_DIGEST_LEN; i++) {
109 sprintf(&utmsgid[i*2], "%02X", (unsigned char) (rawdigest[i] & 0xff));
110 utmsgid[i*2] = tolower(utmsgid[i*2]);
111 utmsgid[(i*2)+1] = tolower(utmsgid[(i*2)+1]);
113 strcat(utmsgid, "_rss2ctdl");
116 /* Find out if we've already seen this item */
117 cdbut = cdb_fetch(CDB_USETABLE, utmsgid, strlen(utmsgid));
119 /* Item has already been seen */
120 lprintf(CTDL_DEBUG, "%s has already been seen\n", utmsgid);
123 /* rewrite the record anyway, to update the timestamp */
124 strcpy(ut.ut_msgid, utmsgid);
125 ut.ut_timestamp = time(NULL);
126 cdb_store(CDB_USETABLE, utmsgid, strlen(utmsgid), &ut, sizeof(struct UseTable) );
129 /* Item has not been seen, so save it. */
131 if (ri->description == NULL) ri->description = strdup("");
132 for (i=strlen(ri->description); i>=0; --i) {
133 if (isspace(ri->description[i])) {
134 ri->description[i] = ' ';
138 msg = malloc(sizeof(struct CtdlMessage));
139 memset(msg, 0, sizeof(struct CtdlMessage));
140 msg->cm_magic = CTDLMESSAGE_MAGIC;
141 msg->cm_anon_type = MES_NORMAL;
142 msg->cm_format_type = FMT_RFC822;
143 msg->cm_fields['A'] = strdup("rss");
144 msg->cm_fields['N'] = strdup(NODENAME);
145 msg->cm_fields['U'] = strdup(ri->title);
146 msg->cm_fields['T'] = malloc(64);
147 snprintf(msg->cm_fields['T'], 64, "%ld", ri->pubdate);
148 if (!IsEmptyStr(ri->channel_title)) {
149 msg->cm_fields['O'] = strdup(ri->channel_title);
152 msglen = 1024 + strlen(ri->link) + strlen(ri->description) ;
153 msg->cm_fields['M'] = malloc(msglen);
154 snprintf(msg->cm_fields['M'], msglen,
155 "Content-type: text/html\r\n\r\n"
158 "<a href=\"%s\">%s</a>\n"
165 CtdlSubmitMsg(msg, recp, NULL);
166 CtdlFreeMessage(msg);
168 /* write the uidl to the use table so we don't store this item again */
169 strcpy(ut.ut_msgid, utmsgid);
170 ut.ut_timestamp = time(NULL);
171 cdb_store(CDB_USETABLE, utmsgid, strlen(utmsgid), &ut, sizeof(struct UseTable) );
173 free_recipients(recp);
179 * Convert an RDF/RSS datestamp into a time_t
181 time_t rdf_parsedate(char *p)
187 if (strlen(p) < 10) return 0L;
189 memset(&tm, 0, sizeof tm);
191 /* YYYY-MM-DDTHH:MM format...
193 if ( (p[4] == '-') && (p[7] == '-') ) {
194 tm.tm_year = atoi(&p[0]) - 1900;
195 tm.tm_mon = atoi(&p[5]) - 1;
196 tm.tm_mday = atoi(&p[8]);
197 if ( (p[10] == 'T') && (p[13] == ':') ) {
198 tm.tm_hour = atoi(&p[11]);
199 tm.tm_min = atoi(&p[14]);
204 /* hmm... try RFC822 date stamp format */
207 if (t > 0) return(t);
209 /* yeesh. ok, just return the current date and time. */
215 void rss_xml_start(void *data, const char *supplied_el, const char **attr) {
216 struct rss_item *ri = (struct rss_item *) data;
220 /* Axe the namespace, we don't care about it */
221 safestrncpy(el, supplied_el, sizeof el);
222 while (sep = strchr(el, ':'), sep) {
226 if (!strcasecmp(el, "item")) {
227 ++ri->item_tag_nesting;
229 /* Initialize the feed item data structure */
230 if (ri->guid != NULL) free(ri->guid);
232 if (ri->title != NULL) free(ri->title);
234 if (ri->link != NULL) free(ri->link);
236 if (ri->description != NULL) free(ri->description);
237 ri->description = NULL;
239 /* Throw away any existing character data */
240 if (ri->chardata_len > 0) {
243 ri->chardata_len = 0;
251 void rss_xml_end(void *data, const char *supplied_el) {
252 struct rss_item *ri = (struct rss_item *) data;
256 /* Axe the namespace, we don't care about it */
257 safestrncpy(el, supplied_el, sizeof el);
258 while (sep = strchr(el, ':'), sep) {
262 if ( (!strcasecmp(el, "title")) && (ri->item_tag_nesting == 0) && (ri->chardata != NULL) ) {
263 safestrncpy(ri->channel_title, ri->chardata, sizeof ri->channel_title);
264 striplt(ri->channel_title);
267 if ( (!strcasecmp(el, "guid")) && (ri->chardata != NULL) ) {
268 if (ri->guid != NULL) free(ri->guid);
269 striplt(ri->chardata);
270 ri->guid = strdup(ri->chardata);
273 if ( (!strcasecmp(el, "title")) && (ri->chardata != NULL) ) {
274 if (ri->title != NULL) free(ri->title);
275 striplt(ri->chardata);
276 ri->title = strdup(ri->chardata);
279 if ( (!strcasecmp(el, "link")) && (ri->chardata != NULL) ) {
280 if (ri->link != NULL) free(ri->link);
281 striplt(ri->chardata);
282 ri->link = strdup(ri->chardata);
285 if ( (!strcasecmp(el, "description")) && (ri->chardata != NULL) ) {
286 if (ri->description != NULL) free(ri->description);
287 ri->description = strdup(ri->chardata);
290 if ( ((!strcasecmp(el, "pubdate")) || (!strcasecmp(el, "date"))) && (ri->chardata != NULL) ) {
291 striplt(ri->chardata);
292 ri->pubdate = rdf_parsedate(ri->chardata);
295 if (!strcasecmp(el, "item")) {
296 --ri->item_tag_nesting;
300 if ( (!strcasecmp(el, "rss")) || (!strcasecmp(el, "rdf")) ) {
301 lprintf(CTDL_DEBUG, "End of feed detected. Closing parser.\n");
302 ri->done_parsing = 1;
305 if (ri->chardata_len > 0) {
308 ri->chardata_len = 0;
315 * This callback stores up the data which appears in between tags.
317 void rss_xml_chardata(void *data, const XML_Char *s, int len) {
318 struct rss_item *ri = (struct rss_item *) data;
323 old_len = ri->chardata_len;
324 new_len = old_len + len;
325 new_buffer = realloc(ri->chardata, new_len + 1);
326 if (new_buffer != NULL) {
327 memcpy(&new_buffer[old_len], s, len);
328 new_buffer[new_len] = 0;
329 ri->chardata = new_buffer;
330 ri->chardata_len = new_len;
337 * Parse a URL into host, port number, and resource identifier.
339 int parse_url(char *url, char *hostname, int *port, char *identifier)
346 strcpy(scratch, url);
347 ptr = (char *)strchr(scratch, ':');
349 return(1); /* no protocol specified */
353 strcpy(protocol, scratch);
354 if (strcmp(protocol, "http")) {
355 return(2); /* not HTTP */
358 strcpy(scratch, url);
359 ptr = (char *) strstr(scratch, "//");
361 return(3); /* no server specified */
365 strcpy(hostname, ptr);
366 nptr = (char *)strchr(ptr, ':');
368 *port = 80; /* default */
369 nptr = (char *)strchr(hostname, '/');
372 sscanf(nptr, ":%d", port);
373 nptr = (char *)strchr(hostname, ':');
380 nptr = (char *)strchr(ptr, '/');
383 return(4); /* no url specified */
386 strcpy(identifier, nptr);
394 void rss_do_fetching(char *url, char *rooms) {
402 int got_bytes = (-1);
403 int redirect_count = 0;
406 if (parse_url(url, rsshost, &rssport, rssurl) != 0) {
407 lprintf(CTDL_ALERT, "Invalid URL: %s\n", url);
410 xp = XML_ParserCreateNS("UTF-8", ':');
412 lprintf(CTDL_ALERT, "Cannot create XML parser!\n");
416 memset(&ri, 0, sizeof(struct rss_item));
418 XML_SetElementHandler(xp, rss_xml_start, rss_xml_end);
419 XML_SetCharacterDataHandler(xp, rss_xml_chardata);
420 XML_SetUserData(xp, &ri);
422 retry: lprintf(CTDL_NOTICE, "Connecting to <%s>\n", rsshost);
423 sprintf(buf, "%d", rssport);
424 sock = sock_connect(rsshost, buf, "tcp");
426 lprintf(CTDL_DEBUG, "Connected!\n");
428 snprintf(buf, sizeof buf, "GET %s HTTP/1.0", rssurl);
429 lprintf(CTDL_DEBUG, "<%s\n", buf);
430 sock_puts(sock, buf);
432 snprintf(buf, sizeof buf, "Host: %s", rsshost);
433 lprintf(CTDL_DEBUG, "<%s\n", buf);
434 sock_puts(sock, buf);
436 snprintf(buf, sizeof buf, "User-Agent: %s", CITADEL);
437 lprintf(CTDL_DEBUG, "<%s\n", buf);
438 sock_puts(sock, buf);
440 snprintf(buf, sizeof buf, "Accept: */*");
441 lprintf(CTDL_DEBUG, "<%s\n", buf);
442 sock_puts(sock, buf);
446 if (sock_getln(sock, buf, sizeof buf) >= 0) {
447 lprintf(CTDL_DEBUG, ">%s\n", buf);
448 remove_token(buf, 0, ' ');
453 while (got_bytes = sock_getln(sock, buf, sizeof buf),
454 (got_bytes >= 0 && (strcmp(buf, "")) && (strcmp(buf, "\r"))) ) {
455 /* discard headers */
458 while (got_bytes = sock_read(sock, buf, sizeof buf, 0),
459 ((got_bytes>=0) && (ri.done_parsing == 0)) ) {
460 XML_Parse(xp, buf, got_bytes, 0);
462 if (ri.done_parsing == 0) XML_Parse(xp, "", 0, 1);
466 else if ( (!strncmp(buf, "30", 2)) && (redirect_count < 16) ) {
467 while (got_bytes = sock_getln(sock, buf, sizeof buf),
468 (got_bytes >= 0 && (strcmp(buf, "")) && (strcmp(buf, "\r"))) ) {
469 if (!strncasecmp(buf, "Location:", 9)) {
471 strcpy(buf, &buf[9]);
473 if (parse_url(buf, rsshost, &rssport, rssurl) == 0) {
478 lprintf(CTDL_ALERT, "Invalid URL: %s\n", buf);
488 lprintf(CTDL_ERR, "Could not connect: %s\n", strerror(errno));
493 /* Free the feed item data structure */
494 if (ri.guid != NULL) free(ri.guid);
496 if (ri.title != NULL) free(ri.title);
498 if (ri.link != NULL) free(ri.link);
500 if (ri.description != NULL) free(ri.description);
501 ri.description = NULL;
502 if (ri.chardata_len > 0) {
511 * Scan a room's netconfig to determine whether it is requesting any RSS feeds
513 void rssclient_scan_room(struct ctdlroom *qrbuf, void *data)
515 char filename[PATH_MAX];
520 struct rssnetcfg *rncptr = NULL;
521 struct rssnetcfg *use_this_rncptr = NULL;
525 assoc_file_name(filename, sizeof filename, qrbuf, ctdl_netcfg_dir);
527 /* Only do net processing for rooms that have netconfigs */
528 fp = fopen(filename, "r");
533 while (fgets(buf, sizeof buf, fp) != NULL) {
534 buf[strlen(buf)-1] = 0;
536 extract_token(instr, buf, 0, '|', sizeof instr);
537 if (!strcasecmp(instr, "rssclient")) {
539 use_this_rncptr = NULL;
541 extract_token(feedurl, buf, 1, '|', sizeof feedurl);
543 /* If any other rooms have requested the same feed, then we will just add this
544 * room to the target list for that client request.
546 for (rncptr=rnclist; rncptr!=NULL; rncptr=rncptr->next) {
547 if (!strcmp(rncptr->url, feedurl)) {
548 use_this_rncptr = rncptr;
552 /* Otherwise create a new client request */
553 if (use_this_rncptr == NULL) {
554 rncptr = (struct rssnetcfg *) malloc(sizeof(struct rssnetcfg));
555 if (rncptr != NULL) {
556 rncptr->next = rnclist;
557 safestrncpy(rncptr->url, feedurl, sizeof rncptr->url);
558 rncptr->rooms = NULL;
560 use_this_rncptr = rncptr;
564 /* Add the room name to the request */
565 if (use_this_rncptr != NULL) {
566 if (use_this_rncptr->rooms == NULL) {
567 rncptr->rooms = strdup(qrbuf->QRname);
570 len = strlen(use_this_rncptr->rooms) + strlen(qrbuf->QRname) + 5;
571 ptr = realloc(use_this_rncptr->rooms, len);
574 strcat(ptr, qrbuf->QRname);
575 use_this_rncptr->rooms = ptr;
588 * Scan for rooms that have RSS client requests configured
590 void *rssclient_scan(void *args) {
591 static time_t last_run = 0L;
592 static int doing_rssclient = 0;
593 struct rssnetcfg *rptr = NULL;
594 struct CitContext rssclientCC;
596 /* Give this thread its own private CitContext */
597 memset(&rssclientCC, 0, sizeof(struct CitContext));
598 rssclientCC.internal_pgm = 1;
599 rssclientCC.cs_pid = 0;
600 pthread_setspecific(MyConKey, (void *)&rssclientCC );
602 CtdlThreadAllocTSD();
605 * This is a simple concurrency check to make sure only one rssclient run
606 * is done at a time. We could do this with a mutex, but since we
607 * don't really require extremely fine granularity here, we'll do it
608 * with a static variable instead.
610 if (doing_rssclient) return NULL;
613 lprintf(CTDL_DEBUG, "rssclient started\n");
614 ForEachRoom(rssclient_scan_room, NULL);
616 while (rnclist != NULL) {
617 rss_do_fetching(rnclist->url, rnclist->rooms);
619 rnclist = rnclist->next;
620 if (rptr->rooms != NULL) free(rptr->rooms);
624 lprintf(CTDL_DEBUG, "rssclient ended\n");
625 last_run = time(NULL);
627 CtdlThreadSchedule ("RSS Client", CTDLTHREAD_BIGSTACK, rssclient_scan, NULL, last_run + config.c_net_freq);
632 #endif /* HAVE_EXPAT */
634 CTDL_MODULE_INIT(rssclient)
639 CtdlThreadSchedule ("RSS Client", CTDLTHREAD_BIGSTACK, rssclient_scan, NULL, 0);
641 lprintf(CTDL_INFO, "This server is missing the Expat XML parser. RSS client will be disabled.\n");
645 /* return our Subversion id for the Log */
646 return "$Id: serv_rssclient.c 5652 2007-10-29 20:14:48Z ajc $";