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;
64 struct rssnetcfg *rnclist = NULL;
68 * Commit a fetched and parsed RSS item to disk
70 void rss_save_item(struct rss_item *ri) {
72 struct MD5Context md5context;
73 u_char rawdigest[MD5_DIGEST_LEN];
76 struct cdbdata *cdbut;
78 struct CtdlMessage *msg;
79 struct recptypes *recp = NULL;
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;
89 /* Construct a GUID to use in the S_USETABLE table.
90 * If one is not present in the item itself, make one up.
92 if (ri->guid != NULL) {
93 snprintf(utmsgid, sizeof utmsgid, "rss/%s", ri->guid);
97 if (ri->title != NULL) {
98 MD5Update(&md5context, ri->title, strlen(ri->title));
100 if (ri->link != NULL) {
101 MD5Update(&md5context, ri->link, strlen(ri->link));
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]);
109 strcat(utmsgid, "_rss2ctdl");
112 /* Find out if we've already seen this item */
113 cdbut = cdb_fetch(CDB_USETABLE, utmsgid, strlen(utmsgid));
115 /* Item has already been seen */
116 lprintf(CTDL_DEBUG, "%s has already been seen\n", utmsgid);
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) );
125 /* Item has not been seen, so save it. */
127 for (i=strlen(ri->description); i>=0; --i) {
128 if (isspace(ri->description[i])) {
129 ri->description[i] = ' ';
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);
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"
150 "<a href=\"%s\">%s</a>\n"
157 CtdlSubmitMsg(msg, recp, NULL);
158 CtdlFreeMessage(msg);
159 free_recipients(recp);
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) );
171 * Convert an RDF/RSS datestamp into a time_t
173 time_t rdf_parsedate(char *p)
178 if (strlen(p) < 10) return 0L;
180 memset(&tm, 0, sizeof tm);
182 /* YYYY-MM-DDTHH:MM format...
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]);
195 /* FIXME try an imap timestamp conversion */
203 void rss_xml_start(void *data, const char *el, const char **attr) {
204 struct rss_item *ri = (struct rss_item *) data;
206 if (!strcasecmp(el, "item")) {
208 /* Initialize the feed item data structure */
209 if (ri->guid != NULL) free(ri->guid);
211 if (ri->title != NULL) free(ri->title);
213 if (ri->link != NULL) free(ri->link);
215 if (ri->description != NULL) free(ri->description);
216 ri->description = NULL;
218 /* Throw away any existing character data */
219 if (ri->chardata_len > 0) {
222 ri->chardata_len = 0;
230 void rss_xml_end(void *data, const char *supplied_el) {
231 struct rss_item *ri = (struct rss_item *) data;
236 /* Axe the namespace, we don't care about it */
238 safestrncpy(el, supplied_el, sizeof el);
239 while (sep = strchr(el, ':'), sep) {
243 if (!strcasecmp(el, "guid")) {
244 if (ri->guid != NULL) free(ri->guid);
245 striplt(ri->chardata);
246 ri->guid = strdup(ri->chardata);
249 if (!strcasecmp(el, "title")) {
250 if (ri->title != NULL) free(ri->title);
251 striplt(ri->chardata);
252 ri->title = strdup(ri->chardata);
255 if (!strcasecmp(el, "link")) {
256 if (ri->link != NULL) free(ri->link);
257 striplt(ri->chardata);
258 ri->link = strdup(ri->chardata);
261 if (!strcasecmp(el, "description")) {
262 if (ri->description != NULL) free(ri->description);
263 ri->description = strdup(ri->chardata);
266 if ( (!strcasecmp(el, "pubdate")) || (!strcasecmp(el, "date")) ) {
267 striplt(ri->chardata);
268 ri->pubdate = rdf_parsedate(ri->chardata);
271 if (!strcasecmp(el, "item")) {
275 if ( (!strcasecmp(el, "rss")) || (!strcasecmp(el, "rdf")) ) {
276 lprintf(CTDL_DEBUG, "End of feed detected. Closing parser.\n");
277 ri->done_parsing = 1;
280 if (ri->chardata_len > 0) {
283 ri->chardata_len = 0;
290 * This callback stores up the data which appears in between tags.
292 void rss_xml_chardata(void *data, const XML_Char *s, int len) {
293 struct rss_item *ri = (struct rss_item *) data;
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;
312 * Parse a URL into host, port number, and resource identifier.
314 int parse_url(char *url, char *hostname, int *port, char *identifier)
321 strcpy(scratch, url);
322 ptr = (char *)strchr(scratch, ':');
324 return(1); /* no protocol specified */
328 strcpy(protocol, scratch);
329 if (strcmp(protocol, "http")) {
330 return(2); /* not HTTP */
333 strcpy(scratch, url);
334 ptr = (char *) strstr(scratch, "//");
336 return(3); /* no server specified */
340 strcpy(hostname, ptr);
341 nptr = (char *)strchr(ptr, ':');
343 *port = 80; /* default */
344 nptr = (char *)strchr(hostname, '/');
347 sscanf(nptr, ":%d", port);
348 nptr = (char *)strchr(hostname, ':');
355 nptr = (char *)strchr(ptr, '/');
358 return(4); /* no url specified */
361 strcpy(identifier, nptr);
369 void rss_do_fetching(char *url, char *rooms) {
377 int got_bytes = (-1);
378 int redirect_count = 0;
381 if (parse_url(url, rsshost, &rssport, rssurl) != 0) {
382 lprintf(CTDL_ALERT, "Invalid URL: %s\n", url);
385 xp = XML_ParserCreateNS("UTF-8", ':');
387 lprintf(CTDL_ALERT, "Cannot create XML parser!\n");
391 memset(&ri, 0, sizeof(struct rss_item));
393 XML_SetElementHandler(xp, rss_xml_start, rss_xml_end);
394 XML_SetCharacterDataHandler(xp, rss_xml_chardata);
395 XML_SetUserData(xp, &ri);
397 retry: lprintf(CTDL_NOTICE, "Connecting to <%s>\n", rsshost);
398 sprintf(buf, "%d", rssport);
399 sock = sock_connect(rsshost, buf, "tcp");
401 lprintf(CTDL_DEBUG, "Connected!\n");
403 snprintf(buf, sizeof buf, "GET %s HTTP/1.0", rssurl);
404 lprintf(CTDL_DEBUG, "<%s\n", buf);
405 sock_puts(sock, buf);
407 snprintf(buf, sizeof buf, "Host: %s", rsshost);
408 lprintf(CTDL_DEBUG, "<%s\n", buf);
409 sock_puts(sock, buf);
413 if (sock_getln(sock, buf, sizeof buf) >= 0) {
414 lprintf(CTDL_DEBUG, ">%s\n", buf);
415 remove_token(buf, 0, ' ');
420 while (got_bytes = sock_getln(sock, buf, sizeof buf),
421 (got_bytes >= 0 && (strcmp(buf, "")) && (strcmp(buf, "\r"))) ) {
422 /* discard headers */
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);
429 if (ri.done_parsing == 0) XML_Parse(xp, "", 0, 1);
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)) {
438 strcpy(buf, &buf[9]);
440 if (parse_url(buf, rsshost, &rssport, rssurl) == 0) {
444 lprintf(CTDL_ALERT, "Invalid URL: %s\n", buf);
454 lprintf(CTDL_ERR, "Could not connect: %s\n", strerror(errno));
459 /* Free the feed item data structure */
460 if (ri.guid != NULL) free(ri.guid);
462 if (ri.title != NULL) free(ri.title);
464 if (ri.link != NULL) free(ri.link);
466 if (ri.description != NULL) free(ri.description);
467 ri.description = NULL;
468 if (ri.chardata_len > 0) {
477 * Scan a room's netconfig to determine whether it is requesting any RSS feeds
479 void rssclient_scan_room(struct ctdlroom *qrbuf, void *data)
481 char filename[PATH_MAX];
486 struct rssnetcfg *rncptr = NULL;
487 struct rssnetcfg *use_this_rncptr = NULL;
491 assoc_file_name(filename, sizeof filename, qrbuf, ctdl_netcfg_dir);
493 /* Only do net processing for rooms that have netconfigs */
494 fp = fopen(filename, "r");
499 while (fgets(buf, sizeof buf, fp) != NULL) {
500 buf[strlen(buf)-1] = 0;
502 extract_token(instr, buf, 0, '|', sizeof instr);
503 if (!strcasecmp(instr, "rssclient")) {
504 extract_token(feedurl, buf, 1, '|', sizeof feedurl);
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.
509 for (rncptr=rnclist; rncptr!=NULL; rncptr=rncptr->next) {
510 if (!strcmp(rncptr->url, feedurl)) {
511 use_this_rncptr = rncptr;
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;
523 use_this_rncptr = rncptr;
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);
533 len = strlen(use_this_rncptr->rooms) + strlen(qrbuf->QRname) + 5;
534 ptr = realloc(use_this_rncptr->rooms, len);
537 strcat(ptr, qrbuf->QRname);
538 use_this_rncptr->rooms = ptr;
551 * Scan for rooms that have RSS client requests configured
553 void rssclient_scan(void) {
554 static time_t last_run = 0L;
555 static int doing_rssclient = 0;
556 struct rssnetcfg *rptr = NULL;
559 * Run RSS client no more frequently than once every n seconds
561 if ( (time(NULL) - last_run) < config.c_net_freq ) {
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.
571 if (doing_rssclient) return;
574 lprintf(CTDL_DEBUG, "rssclient started\n");
575 ForEachRoom(rssclient_scan_room, NULL);
577 while (rnclist != NULL) {
578 rss_do_fetching(rnclist->url, rnclist->rooms);
580 rnclist = rnclist->next;
581 if (rptr->rooms != NULL) free(rptr->rooms);
585 lprintf(CTDL_DEBUG, "rssclient ended\n");
586 last_run = time(NULL);
591 #endif /* HAVE_EXPAT */
593 CTDL_MODULE_INIT(rssclient)
596 CtdlRegisterSessionHook(rssclient_scan, EVT_TIMER);
598 lprintf(CTDL_INFO, "This server is missing the Expat XML parser. RSS client will be disabled.\n");
600 /* return our Subversion id for the Log */
601 return "$Id: serv_rssclient.c 5652 2007-10-29 20:14:48Z ajc $";