/* Distributed Checksum Clearinghouse
 *
 * 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.11 $Revision$
 */

#include "dcc_defs.h"

char *
dcc_ck2str(char *tgt, u_int tgt_len, DCC_CK_TYPES type, const DCC_SUM sum)
{
	u_int32_t n[sizeof(DCC_SUM)+3/4];
	u_char c;
	char *p;
	int i;

	if (type != DCC_CK_SRVR_ID) {
		memcpy(n, sum, sizeof(n));
		snprintf(tgt, tgt_len, "%08x %08x %08x %08x",
			 (int)ntohl(n[0]), (int)ntohl(n[1]),
			 (int)ntohl(n[2]), (int)ntohl(n[3]));
		return tgt;
	}

	/* decode string from server-ID declaration */
	p = tgt;
	if (tgt_len == 0)
		return tgt;
	*p++ = '"';
	--tgt_len;
	for (i = 0; i < ISZ(DCC_SUM); ++i) {
		if (tgt_len == 0)
			return tgt;
		c = sum[i];
		if (c == '\0')
			break;
		if (c >= ' ' && c < 0x7f) {
			*p++ = c;
			--tgt_len;
		} else {
			*p++ = '\\';
			if (--tgt_len == 0)
				return tgt;
			*p++ = '0'+(c>>6);
			if (--tgt_len == 0)
				return tgt;
			*p++ = '0'+((c>>3) & 7);
			if (--tgt_len == 0)
				return tgt;
			*p++ = '0'+(c & 7);
			--tgt_len;
		}
	}
	*p++ = '"';
	--tgt_len;
	if (--tgt_len != 0)
		*p = '\0';
	return tgt;
}



/* this is not thread safe */
const char *
dcc_ck2str_err(DCC_CK_TYPES type, const DCC_SUM sum)
{
	static char ck_buf[DCC_CK2STR_LEN];

	return dcc_ck2str(ck_buf, sizeof(ck_buf), type, sum);
}
