/* Distributed Checksum Clearinghouse
 *
 * controller dcc server
 *
 * Copyright (c) 2005 by Rhyolite Software
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND RHYOLITE SOFTWARE DISCLAIMS ALL
 * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL RHYOLITE SOFTWARE
 * BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
 * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
 * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
 * SOFTWARE.
 *
 * Rhyolite Software DCC 1.2.74-1.31 $Revision$
 */

#include "dcc_clnt.h"
#include "dcc_xhdr.h"


static void
print_srvr(const DCC_SRVR_CLASS *class,
	   u_char grey,
	   const DCC_SRVR_ADDR *ap,
	   u_char name,
	   u_char have_rtt_adj)
{
	char srvr_nm[MAXHOSTNAMELEN];
	DCC_SOCKU su;
	int i;

	if (name) {
		dcc_mk_su(&su, ap->family, &ap->ip, ap->port);
		dcc_su2name(srvr_nm, sizeof(srvr_nm), &su);
	} else {
		srvr_nm[0] = '\0';
	}
	printf("# %1s %-22s %-25s",
	       class->act_inx == ap - class->addrs
	       ? "*" : "",
	       dcc_ap2str_opt(ap, DCC_GREY2PORT(grey), '-'),
	       srvr_nm);
	if (ap->srvr_id != DCC_ID_INVALID) {
		printf(" %16s ID %-4d",
		       ap->brand, ap->srvr_id);
		if (ap->srvr_pkt_vers != DCC_PKT_VERSION)
			printf("\n#   pkt_vers %d",
			       ap->srvr_pkt_vers);
	}
	putchar('\n');

	if (ap->rtt >= DCC_RTT_BAD) {
		fputs("#      not answering\n", stdout);
		return;
	}
	if (ap->total_xmits == 0) {
		printf("#     %22s", "");
	} else {
		printf("#     %3.0f%% of %2d requests ok",
		       (ap->total_resps*100.0)/ap->total_xmits,
		       ap->total_xmits);
	}
	if (have_rtt_adj) {
		i = printf("%8.2f%+d ms RTT",
			   ap->rtt/1000.0,
			   class->nms[ap->nm_inx].rtt_adj/1000);
	} else {
		i = printf("%8.2f ms RTT",
			   ap->rtt/1000.0);
	}
	i = (i >= 22) ? 1 : (22-i);
	printf("  %*s  %4d ms queue wait\n",
	       i, "", ap->srvr_wait/1000);
}



/* dump the /var/dcc/map file */
void
dcc_print_info(const char *map_nm,	/* or null for temporary file */
	       const DCC_CLNT_INFO *info,
	       u_char grey,
	       u_char names,
	       u_char show_passwd)
{
#define dcc_clnt_info ??? this is an error
	char date_buf[40];
	int port, nm_inx;
	struct tm tm;
	const DCC_SRVR_CLASS *class;
	const DCC_SRVR_ADDR *ap,*ap_prev, *ap_next;
	u_char printed_addr[DCC_MAX_SRVR_ADDRS];
	u_char have_rtt_adj;
	u_char need_blank_line;
	int i;

	class = grey ? &info->grey : &info->dcc;
	if (map_nm) {
		strftime(date_buf, sizeof(date_buf), "%x %X %Z",
			 dcc_localtime(time(0), &tm));
		printf("# %-s  %s%s\n",
		       date_buf, grey ? "GreyList " : "", DCC_NM2PATH(map_nm));
		fputs("# ", stdout);
		if (class->resolve > time(0) || dcc_clnt_debug) {
			strftime(date_buf, sizeof(date_buf), "%X",
				 dcc_localtime(class->resolve, &tm));
			printf("Re-resolve names after %s  ", date_buf);
		}
		if (class->measure > time(0) || dcc_clnt_debug) {
			strftime(date_buf, sizeof(date_buf), "%X",
				 dcc_localtime(class->measure, &tm));
			printf("Check RTTs after %s", date_buf);
		}
		putchar('\n');

		fputs("# ", stdout);
		i = 0;
		for (ap = class->addrs; ap <= LAST(class->addrs); ++ap) {
			if (ap->rtt != DCC_RTT_BAD
			    && ap->family != 0)
				++i;
		}
		if (i > 1 || dcc_clnt_debug)
			printf("%6.2f ms threshold, %4.2f ms average    ",
			       class->thold_rtt/1000.0,
			       class->avg_thold_rtt/1000.0);
		printf("%d total, %d working servers\n",
		       class->num_addrs, i);
		if (class->fail_exp != 0) {
			int fail_time = class->fail_time - time(0);
			if (fail_time > 0
			    && fail_time <= DCC_MAX_FAIL_SECS) {
				printf("# skipping asking %s server"
				       " %d seconds more\n",
				       grey ? "Greylist" : "DCC", fail_time);
			}
		}

		if (!grey) {
			fputs((info->flags & DCC_CLNT_INFO_FG_IPV6)
			      ? DCC_INFO_USE_IPV6 : DCC_INFO_USE_IPV4, stdout);
			if (info->flags & DCC_CLNT_INFO_FG_SOCKS)
				fputs("   "DCC_INFO_USE_SOCKS, stdout);
			putchar('\n');
		}
	}

	have_rtt_adj = 0;
	for (nm_inx = 0; nm_inx < DIM(class->nms); ++nm_inx) {
		if (class->nms[nm_inx].hostname[0] != '\0'
		    && class->nms[nm_inx].rtt_adj != 0) {
			have_rtt_adj = 1;
			break;
		}
	}

	memset(printed_addr, 0, sizeof(printed_addr));

	/* convert each non-null hostname */
	need_blank_line = 1;
	for (nm_inx = 0; nm_inx < DIM(class->nms); ++nm_inx) {
		if (class->nms[nm_inx].hostname[0] == '\0')
			continue;

		/* First display the main line for a host */
		if (class->nms[nm_inx].defined == 0)
			need_blank_line = 1;
		if (!need_blank_line && nm_inx != 0) {
			for (ap = class->addrs; ap<=LAST(class->addrs); ++ap) {
				if (ap->nm_inx == nm_inx) {
					need_blank_line = 1;
					break;
				}
			}
		}
		if (need_blank_line) {
			need_blank_line = 0;
			putchar('\n');
		}
		i = printf("%s", class->nms[nm_inx].hostname);
		i = (i >= 26) ? 1 : (26-i);
		port = class->nms[nm_inx].port;
		if (port == DCC_GREY2PORT(grey))
			printf(",%-*s", i, "-   ");
		else
			printf(",%-*d", i, ntohs(port));

		if (grey)
			fputs(" Greylist", stdout);

		if (have_rtt_adj) {
			i = printf(" RTT%+d ms",
				   class->nms[nm_inx].rtt_adj/1000);
			i = (i >= 12) ? 1 : (12-i);
			printf("%*s", i, "");
		}

		/* Suppress the password if it does not exist or is secret */
		if (class->nms[nm_inx].clnt_id == DCC_ID_ANON) {
			fputs(" "DCC_XHDR_ID_ANON"\n", stdout);
		} else {
			printf(" %5d %s\n",
			       class->nms[nm_inx].clnt_id,
			       show_passwd ? class->nms[nm_inx].passwd : "");
		}

		if (class->nms[nm_inx].defined == 0) {
			need_blank_line = 1;
			fputs("#   UNDEFINED\n", stdout);
		}

		/* display operating information for each A RR
		 * kludge sort the IP addresses */
		for (ap_prev = 0, i = 0;
		     i < DCC_MAX_SRVR_ADDRS;
		     ap_prev = ap_next, ++i) {
			ap_next = 0;
			for (ap = class->addrs; ap<=LAST(class->addrs); ++ap) {
				if (ap->nm_inx != nm_inx
				    || ap->family == 0)
					continue;
				/* find smallest IP address not yet printed */
				if (printed_addr[ap - class->addrs])
					continue;
				if (ap_next
				    && ap->family >= ap_next->family
				    && 0 <= memcmp(&ap->ip, &ap_next->ip,
						   sizeof(ap->ip))
				    && ap->port >= ap_next->port)
					continue;
				if (!ap_prev
				    || ap->family >= ap_prev->family
				    || 0 <= memcmp(&ap->ip, &ap_prev->ip,
						   sizeof(ap->ip))
				    || ap->port >= ap_prev->port)
					ap_next = ap;
			}
			if (!ap_next)
				break;
			print_srvr(class, grey, ap_next, names, have_rtt_adj);
			printed_addr[ap_next - class->addrs] = 1;
			need_blank_line = 1;

		}
	}

	for (ap = class->addrs, i = 0; ap <= LAST(class->addrs); ++ap, ++i) {
		if (ap->family == 0)
			continue;
		if (printed_addr[i])
			continue;
		printf("\n# stray address entry #%d, nm_inx %d:\n",
		       i, ap->nm_inx);
		print_srvr(class, grey, ap, names, have_rtt_adj);
	}

#undef dcc_clnt_info
}
