private ReferralInfo getReferralConnection(System.String[] referrals)
{
ReferralInfo refInfo = null;
System.Exception ex = null;
LdapConnection rconn = null;
LdapReferralHandler rh = defSearchCons.getReferralHandler();
int i = 0;
// Check if we use LdapRebind to get authentication credentials
if ((rh == null) || (rh is LdapAuthHandler))
{
for (i = 0; i < referrals.Length; i++)
{
// dn, pw are null in the default case (anonymous bind)
System.String dn = null;
sbyte[] pw = null;
try
{
rconn = new LdapConnection();
rconn.Constraints = defSearchCons;
LdapUrl url = new LdapUrl(referrals[i]);
rconn.Connect(url.Host, url.Port);
if (rh != null)
{
if (rh is LdapAuthHandler)
{
// Get application supplied dn and pw
LdapAuthProvider ap = ((LdapAuthHandler) rh).getAuthProvider(url.Host, url.Port);
dn = ap.DN;
pw = ap.Password;
}
}
rconn.Bind(Ldap_V3, dn, pw);
ex = null;
refInfo = new ReferralInfo(rconn, referrals, url);
// Indicate this connection created to follow referral
rconn.Connection.ActiveReferral = refInfo;
break;
}
catch (System.Exception lex)
{
if (rconn != null)
{
try
{
rconn.Disconnect();
rconn = null;
ex = lex;
}
catch (LdapException e)
{
; // ignore
}
}
}
}
}
// Check if application gets connection and does bind
else
{
// rh instanceof LdapBind
try
{
rconn = ((LdapBindHandler) rh).Bind(referrals, this);
if (rconn == null)
{
LdapReferralException rex = new LdapReferralException(ExceptionMessages.REFERRAL_ERROR);
rex.setReferrals(referrals);
throw rex;
}
// Figure out which Url belongs to the connection
for (int idx = 0; idx < referrals.Length; idx++)
{
try
{
LdapUrl url = new LdapUrl(referrals[idx]);
if (url.Host.ToUpper().Equals(rconn.Host.ToUpper()) && (url.Port == rconn.Port))
{
refInfo = new ReferralInfo(rconn, referrals, url);
break;
}
}
catch (System.Exception e)
{
; // ignore
}
}
if (refInfo == null)
{
// Could not match LdapBind.bind() connecction with URL list
ex = new LdapLocalException(ExceptionMessages.REFERRAL_BIND_MATCH, LdapException.CONNECT_ERROR);
}
}
catch (System.Exception lex)
{
rconn = null;
ex = lex;
}
}
if (ex != null)
{
// Could not connect to any server, throw an exception
LdapException ldapex;
if (ex is LdapReferralException)
{
throw (LdapReferralException) ex;
}
else if (ex is LdapException)
{
ldapex = (LdapException) ex;
}
else
{
ldapex = new LdapLocalException(ExceptionMessages.SERVER_CONNECT_ERROR, new System.Object[]{conn.Host}, LdapException.CONNECT_ERROR, ex);
}
// Error attempting to follow a referral
LdapReferralException rex = new LdapReferralException(ExceptionMessages.REFERRAL_ERROR, ldapex);
rex.setReferrals(referrals);
// Use last URL string for the failed referral
rex.FailedReferral = referrals[referrals.Length - 1];
throw rex;
}
// We now have an authenticated connection
// to be used to follow the referral.
return refInfo;
}