61 lines
2.2 KiB
C#
61 lines
2.2 KiB
C#
namespace ZB.MOM.WW.Auth.Ldap.Internal;
|
||
|
||
/// <summary>A single LDAP server endpoint resolved from configuration.</summary>
|
||
internal sealed record LdapEndpoint(string Host, int Port)
|
||
{
|
||
/// <summary>Renders the endpoint as <c>host:port</c> — the form used in failover log messages.</summary>
|
||
public override string ToString() => $"{Host}:{Port}";
|
||
}
|
||
|
||
/// <summary>
|
||
/// Parses <c>FallbackServers</c> entries: <c>"host"</c> (adopts the caller's default port)
|
||
/// or <c>"host:port"</c>. IPv6 literals are not supported — use a DNS name.
|
||
/// </summary>
|
||
internal static class LdapEndpointParser
|
||
{
|
||
/// <summary>
|
||
/// Attempts to parse a single <c>FallbackServers</c> entry.
|
||
/// </summary>
|
||
/// <param name="entry">The configured entry, <c>"host"</c> or <c>"host:port"</c>. Surrounding whitespace is tolerated.</param>
|
||
/// <param name="defaultPort">Port adopted when the entry carries no explicit one.</param>
|
||
/// <param name="endpoint">The parsed endpoint on success; undefined otherwise.</param>
|
||
/// <param name="error">A human-readable reason on failure; empty on success.</param>
|
||
/// <returns><see langword="true"/> when the entry parsed.</returns>
|
||
public static bool TryParse(string entry, int defaultPort, out LdapEndpoint endpoint, out string error)
|
||
{
|
||
endpoint = null!;
|
||
error = "";
|
||
|
||
if (string.IsNullOrWhiteSpace(entry))
|
||
{
|
||
error = "entry is empty or whitespace";
|
||
return false;
|
||
}
|
||
|
||
var parts = entry.Trim().Split(':');
|
||
if (parts.Length > 2)
|
||
{
|
||
error = $"entry \"{entry.Trim()}\" contains more than one ':' " +
|
||
"(IPv6 literals are not supported — use a DNS name)";
|
||
return false;
|
||
}
|
||
|
||
var host = parts[0].Trim();
|
||
if (host.Length == 0)
|
||
{
|
||
error = $"entry \"{entry.Trim()}\" has an empty host";
|
||
return false;
|
||
}
|
||
|
||
var port = defaultPort;
|
||
if (parts.Length == 2 && (!int.TryParse(parts[1].Trim(), out port) || port is < 1 or > 65535))
|
||
{
|
||
error = $"entry \"{entry.Trim()}\" has an invalid port (must be 1–65535)";
|
||
return false;
|
||
}
|
||
|
||
endpoint = new LdapEndpoint(host, port);
|
||
return true;
|
||
}
|
||
}
|