/*
 * Copyright (c) 2002-2004 Sendmail, Inc. and its suppliers.
 *      All rights reserved.
 *
 * By using this file, you agree to the terms and conditions set
 * forth in the LICENSE file which can be found at the top level of
 * the sendmail distribution.
 */

#include "sm/generic.h"
SM_RCSID("@(#)$Id: getmxrr.c,v 1.28 2004/12/27 06:02:14 ca Exp $")
#include "sm/ctype.h"
#include "sm/dns.h"
#include "sm/dns-int.h"

/* used for mxrand */
static uint seed = 42;

/*
**  DNS_RSLV_NEW -- initialize DNS resolver code
**
**	Parameters:
**		randv -- random value for mxrand() function
**
**	Returns:
**		usual sm_error code (currently: SM_SUCCESS)
*/

sm_ret_T
dns_rslv_new(uint randv)
{
	seed = randv == 0 ? 33 : randv;
	res_init();
	return SM_SUCCESS;
}

/*
**  MXRAND -- create a randomizer for equal MX preferences
**
**	If two MX hosts have equal preferences we want to randomize
**	the selection.  But in order for signatures to be the same,
**	we need to randomize the same way each time.  This function
**	computes a pseudo-random hash function from the host name.
**
**	Parameters:
**		host -- the name of the host.
**
**	Returns:
**		A random but repeatable value based on the host name.
*/

ushort
mxrand(const uchar *host)
{
	int hval, c;

	SM_REQUIRE(host != NULL);
	hval = seed;
	while ((c = *host++) != '\0')
	{
		if (isascii(c) && isupper(c))
			c = tolower(c);
		hval = ((hval << 1) ^ c) % 2003;
	}
	return hval & 0xff;
}


syntax highlighted by Code2HTML, v. 0.9.1