using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
namespace ZB.MOM.WW.MxGateway.Client;
///
/// Builds the shared by and
/// : connect timeout, HTTP/2 keepalive, and TLS pinning.
///
internal static class GatewayHttpHandlerFactory
{
///
/// Creates the handler for an owned channel.
///
/// The client options supplying keepalive, connect timeout, and TLS settings.
///
/// The pinned CA certificate captured by the validation callback, or when none is pinned.
/// The caller disposes it after the handler is disposed.
///
/// The configured handler.
public static SocketsHttpHandler Create(MxGatewayClientOptions options, out X509Certificate2? trustedRoot)
{
trustedRoot = null;
// HTTP/2 keepalive (D7): a server-streaming call only reads, so on a half-open connection
// nothing would ever fail the pending read. Pings are sent while no call is active too
// (Always), because an idle event stream is exactly the case to detect.
SocketsHttpHandler handler = new()
{
ConnectTimeout = options.ConnectTimeout,
KeepAlivePingDelay = options.KeepAlivePingDelay,
KeepAlivePingTimeout = options.KeepAlivePingTimeout,
KeepAlivePingPolicy = HttpKeepAlivePingPolicy.Always,
};
if (!options.UseTls)
{
return handler;
}
handler.SslOptions = new SslClientAuthenticationOptions();
if (!string.IsNullOrWhiteSpace(options.ServerNameOverride))
{
handler.SslOptions.TargetHost = options.ServerNameOverride;
}
if (!string.IsNullOrWhiteSpace(options.CaCertificatePath))
{
X509Certificate2 root = X509CertificateLoader.LoadCertificateFromFile(options.CaCertificatePath);
trustedRoot = root;
handler.SslOptions.RemoteCertificateValidationCallback = (_, certificate, chain, errors) =>
{
if ((errors & SslPolicyErrors.RemoteCertificateNameMismatch) != 0)
{
return false;
}
if (certificate is null)
{
return false;
}
using X509Chain customChain = new();
customChain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
customChain.ChainPolicy.CustomTrustStore.Add(root);
customChain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
customChain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag;
X509Certificate2 certificateToValidate = certificate as X509Certificate2
?? X509CertificateLoader.LoadCertificate(certificate.Export(X509ContentType.Cert));
return customChain.Build(certificateToValidate);
};
}
else if (!options.RequireCertificateValidation)
{
handler.SslOptions.RemoteCertificateValidationCallback = (_, _, _, _) => true;
}
return handler;
}
}