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>
29 #include <libcitadel.h>
32 #include "citserver.h"
37 #include "ctdl_module.h"
38 #include "clientsocket.h"
40 #include "parsedate.h"
42 #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, (unsigned char*)ri->title, strlen(ri->title));
102 if (ri->link != NULL) {
103 MD5Update(&md5context, (unsigned char*)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 CtdlLogPrintf(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 if (ri->description == NULL) ri->description = strdup("");
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);
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) );
171 free_recipients(recp);
177 * Convert an RDF/RSS datestamp into a time_t
179 time_t rdf_parsedate(char *p)
185 if (strlen(p) < 10) return 0L;
187 memset(&tm, 0, sizeof tm);
189 /* YYYY-MM-DDTHH:MM format...
191 if ( (p[4] == '-') && (p[7] == '-') ) {
192 tm.tm_year = atoi(&p[0]) - 1900;
193 tm.tm_mon = atoi(&p[5]) - 1;
194 tm.tm_mday = atoi(&p[8]);
195 if ( (p[10] == 'T') && (p[13] == ':') ) {
196 tm.tm_hour = atoi(&p[11]);
197 tm.tm_min = atoi(&p[14]);
202 /* hmm... try RFC822 date stamp format */
205 if (t > 0) return(t);
207 /* yeesh. ok, just return the current date and time. */
213 void rss_xml_start(void *data, const char *supplied_el, const char **attr) {
214 struct rss_item *ri = (struct rss_item *) data;
218 /* Axe the namespace, we don't care about it */
219 safestrncpy(el, supplied_el, sizeof el);
220 while (sep = strchr(el, ':'), sep) {
224 if (!strcasecmp(el, "item")) {
225 ++ri->item_tag_nesting;
227 /* Initialize the feed item data structure */
228 if (ri->guid != NULL) free(ri->guid);
230 if (ri->title != NULL) free(ri->title);
232 if (ri->link != NULL) free(ri->link);
234 if (ri->description != NULL) free(ri->description);
235 ri->description = NULL;
237 /* Throw away any existing character data */
238 if (ri->chardata_len > 0) {
241 ri->chardata_len = 0;
249 void rss_xml_end(void *data, const char *supplied_el) {
250 struct rss_item *ri = (struct rss_item *) data;
254 /* Axe the namespace, we don't care about it */
255 safestrncpy(el, supplied_el, sizeof el);
256 while (sep = strchr(el, ':'), sep) {
260 if ( (!strcasecmp(el, "title")) && (ri->item_tag_nesting == 0) && (ri->chardata != NULL) ) {
261 safestrncpy(ri->channel_title, ri->chardata, sizeof ri->channel_title);
262 striplt(ri->channel_title);
265 if ( (!strcasecmp(el, "guid")) && (ri->chardata != NULL) ) {
266 if (ri->guid != NULL) free(ri->guid);
267 striplt(ri->chardata);
268 ri->guid = strdup(ri->chardata);
271 if ( (!strcasecmp(el, "title")) && (ri->chardata != NULL) ) {
272 if (ri->title != NULL) free(ri->title);
273 striplt(ri->chardata);
274 ri->title = strdup(ri->chardata);
277 if ( (!strcasecmp(el, "link")) && (ri->chardata != NULL) ) {
278 if (ri->link != NULL) free(ri->link);
279 striplt(ri->chardata);
280 ri->link = strdup(ri->chardata);
283 if ( (!strcasecmp(el, "description")) && (ri->chardata != NULL) ) {
284 if (ri->description != NULL) free(ri->description);
285 ri->description = strdup(ri->chardata);
288 if ( ((!strcasecmp(el, "pubdate")) || (!strcasecmp(el, "date"))) && (ri->chardata != NULL) ) {
289 striplt(ri->chardata);
290 ri->pubdate = rdf_parsedate(ri->chardata);
293 if (!strcasecmp(el, "item")) {
294 --ri->item_tag_nesting;
298 if ( (!strcasecmp(el, "rss")) || (!strcasecmp(el, "rdf")) ) {
299 CtdlLogPrintf(CTDL_DEBUG, "End of feed detected. Closing parser.\n");
300 ri->done_parsing = 1;
303 if (ri->chardata_len > 0) {
306 ri->chardata_len = 0;
313 * This callback stores up the data which appears in between tags.
315 void rss_xml_chardata(void *data, const XML_Char *s, int len) {
316 struct rss_item *ri = (struct rss_item *) data;
321 old_len = ri->chardata_len;
322 new_len = old_len + len;
323 new_buffer = realloc(ri->chardata, new_len + 1);
324 if (new_buffer != NULL) {
325 memcpy(&new_buffer[old_len], s, len);
326 new_buffer[new_len] = 0;
327 ri->chardata = new_buffer;
328 ri->chardata_len = new_len;
337 void rss_do_fetching(char *url, char *rooms) {
345 int got_bytes = (-1);
346 int redirect_count = 0;
349 if (parse_url(url, rsshost, &rssport, rssurl) != 0) {
350 CtdlLogPrintf(CTDL_ALERT, "Invalid URL: %s\n", url);
353 if (CtdlThreadCheckStop())
356 xp = XML_ParserCreateNS("UTF-8", ':');
358 CtdlLogPrintf(CTDL_ALERT, "Cannot create XML parser!\n");
362 memset(&ri, 0, sizeof(struct rss_item));
364 XML_SetElementHandler(xp, rss_xml_start, rss_xml_end);
365 XML_SetCharacterDataHandler(xp, rss_xml_chardata);
366 XML_SetUserData(xp, &ri);
368 if (CtdlThreadCheckStop())
374 retry: CtdlLogPrintf(CTDL_NOTICE, "Connecting to <%s>\n", rsshost);
375 sprintf(buf, "%d", rssport);
376 sock = sock_connect(rsshost, buf, "tcp");
378 CtdlLogPrintf(CTDL_DEBUG, "Connected!\n");
380 if (CtdlThreadCheckStop())
383 snprintf(buf, sizeof buf, "GET %s HTTP/1.0", rssurl);
384 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
385 sock_puts(sock, buf);
387 if (CtdlThreadCheckStop())
390 snprintf(buf, sizeof buf, "Host: %s", rsshost);
391 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
392 sock_puts(sock, buf);
394 if (CtdlThreadCheckStop())
397 snprintf(buf, sizeof buf, "User-Agent: %s", CITADEL);
398 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
399 sock_puts(sock, buf);
401 if (CtdlThreadCheckStop())
404 snprintf(buf, sizeof buf, "Accept: */*");
405 CtdlLogPrintf(CTDL_DEBUG, "<%s\n", buf);
406 sock_puts(sock, buf);
408 if (CtdlThreadCheckStop())
413 if (CtdlThreadCheckStop())
416 if (sock_getln(sock, buf, sizeof buf) >= 0) {
417 CtdlLogPrintf(CTDL_DEBUG, ">%s\n", buf);
418 remove_token(buf, 0, ' ');
423 while (got_bytes = sock_getln(sock, buf, sizeof buf),
424 (got_bytes >= 0 && (strcmp(buf, "")) && (strcmp(buf, "\r"))) ) {
425 if (CtdlThreadCheckStop())
427 /* discard headers */
430 while (got_bytes = sock_read(sock, buf, sizeof buf, 0),
431 ((got_bytes>=0) && (ri.done_parsing == 0)) ) {
432 if (CtdlThreadCheckStop())
434 XML_Parse(xp, buf, got_bytes, 0);
436 if (ri.done_parsing == 0) XML_Parse(xp, "", 0, 1);
440 else if ( (!strncmp(buf, "30", 2)) && (redirect_count < 16) ) {
441 while (got_bytes = sock_getln(sock, buf, sizeof buf),
442 (got_bytes >= 0 && (strcmp(buf, "")) && (strcmp(buf, "\r"))) ) {
443 if (CtdlThreadCheckStop())
445 if (!strncasecmp(buf, "Location:", 9)) {
447 strcpy(buf, &buf[9]);
449 if (parse_url(buf, rsshost, &rssport, rssurl) == 0) {
454 CtdlLogPrintf(CTDL_ALERT, "Invalid URL: %s\n", buf);
465 CtdlLogPrintf(CTDL_ERR, "Could not connect: %s\n", strerror(errno));
470 /* Free the feed item data structure */
471 if (ri.guid != NULL) free(ri.guid);
473 if (ri.title != NULL) free(ri.title);
475 if (ri.link != NULL) free(ri.link);
477 if (ri.description != NULL) free(ri.description);
478 ri.description = NULL;
479 if (ri.chardata_len > 0) {
488 * Scan a room's netconfig to determine whether it is requesting any RSS feeds
490 void rssclient_scan_room(struct ctdlroom *qrbuf, void *data)
492 char filename[PATH_MAX];
497 struct rssnetcfg *rncptr = NULL;
498 struct rssnetcfg *use_this_rncptr = NULL;
502 assoc_file_name(filename, sizeof filename, qrbuf, ctdl_netcfg_dir);
504 if (CtdlThreadCheckStop())
507 /* Only do net processing for rooms that have netconfigs */
508 fp = fopen(filename, "r");
513 while (fgets(buf, sizeof buf, fp) != NULL && !CtdlThreadCheckStop()) {
514 buf[strlen(buf)-1] = 0;
516 extract_token(instr, buf, 0, '|', sizeof instr);
517 if (!strcasecmp(instr, "rssclient")) {
519 use_this_rncptr = NULL;
521 extract_token(feedurl, buf, 1, '|', sizeof feedurl);
523 /* If any other rooms have requested the same feed, then we will just add this
524 * room to the target list for that client request.
526 for (rncptr=rnclist; rncptr!=NULL; rncptr=rncptr->next) {
527 if (!strcmp(rncptr->url, feedurl)) {
528 use_this_rncptr = rncptr;
532 /* Otherwise create a new client request */
533 if (use_this_rncptr == NULL) {
534 rncptr = (struct rssnetcfg *) malloc(sizeof(struct rssnetcfg));
535 if (rncptr != NULL) {
536 rncptr->next = rnclist;
537 safestrncpy(rncptr->url, feedurl, sizeof rncptr->url);
538 rncptr->rooms = NULL;
540 use_this_rncptr = rncptr;
544 /* Add the room name to the request */
545 if (use_this_rncptr != NULL) {
546 if (use_this_rncptr->rooms == NULL) {
547 rncptr->rooms = strdup(qrbuf->QRname);
550 len = strlen(use_this_rncptr->rooms) + strlen(qrbuf->QRname) + 5;
551 ptr = realloc(use_this_rncptr->rooms, len);
554 strcat(ptr, qrbuf->QRname);
555 use_this_rncptr->rooms = ptr;
568 * Scan for rooms that have RSS client requests configured
570 void *rssclient_scan(void *args) {
571 static time_t last_run = 0L;
572 static int doing_rssclient = 0;
573 struct rssnetcfg *rptr = NULL;
574 struct CitContext rssclientCC;
576 /* Give this thread its own private CitContext */
577 memset(&rssclientCC, 0, sizeof(struct CitContext));
578 rssclientCC.internal_pgm = 1;
579 rssclientCC.cs_pid = 0;
580 pthread_setspecific(MyConKey, (void *)&rssclientCC );
582 CtdlThreadAllocTSD();
585 * This is a simple concurrency check to make sure only one rssclient run
586 * is done at a time. We could do this with a mutex, but since we
587 * don't really require extremely fine granularity here, we'll do it
588 * with a static variable instead.
590 if (doing_rssclient) return NULL;
593 CtdlLogPrintf(CTDL_DEBUG, "rssclient started\n");
594 ForEachRoom(rssclient_scan_room, NULL);
596 while (rnclist != NULL && !CtdlThreadCheckStop()) {
597 rss_do_fetching(rnclist->url, rnclist->rooms);
599 rnclist = rnclist->next;
600 if (rptr->rooms != NULL) free(rptr->rooms);
604 CtdlLogPrintf(CTDL_DEBUG, "rssclient ended\n");
605 last_run = time(NULL);
607 if (!CtdlThreadCheckStop())
608 CtdlThreadSchedule ("RSS Client", CTDLTHREAD_BIGSTACK, rssclient_scan, NULL, last_run + config.c_net_freq);
610 CtdlLogPrintf(CTDL_DEBUG, "rssclient: Task STOPPED.\n");
615 CTDL_MODULE_INIT(rssclient)
619 CtdlThreadSchedule ("RSS Client", CTDLTHREAD_BIGSTACK, rssclient_scan, NULL, 0);
621 /* return our Subversion id for the Log */
622 return "$Id: serv_rssclient.c 5652 2007-10-29 20:14:48Z ajc $";