HTTPClients: avoid Exception User-Unhandled notices

This commit is contained in:
kaso17
2019-04-02 15:39:14 +02:00
parent 859da99442
commit a4ba0d21d9
3 changed files with 88 additions and 68 deletions

View File

@@ -14,6 +14,7 @@ using Jackett.Common.Models.Config;
using Jackett.Common.Services.Interfaces;
using NLog;
using Jackett.Common.Helpers;
using System.Diagnostics;
namespace Jackett.Common.Utils.Clients
{
@@ -30,6 +31,34 @@ namespace Jackett.Common.Utils.Clients
static protected string webProxyUrl;
static protected IWebProxy webProxy;
[DebuggerNonUserCode] // avoid "Exception User-Unhandled" Visual Studio messages
static public bool ValidateCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
if (sender.GetType() != typeof(HttpWebRequest))
return sslPolicyErrors == SslPolicyErrors.None;
var request = (HttpWebRequest)sender;
var hash = certificate.GetCertHashString();
ICollection<string> hosts;
trustedCertificates.TryGetValue(hash, out hosts);
if (hosts != null)
{
if (hosts.Contains(request.Host))
return true;
}
if (sslPolicyErrors != SslPolicyErrors.None)
{
// Throw exception with certificate details, this will cause a "Exception User-Unhandled" when running it in the Visual Studio debugger.
// The certificate is only available inside this function, so we can't catch it at the calling method.
throw new Exception("certificate validation failed: " + certificate.ToString());
}
return sslPolicyErrors == SslPolicyErrors.None;
}
static public void InitProxy(ServerConfig serverConfig)
{
// dispose old SocksWebProxy
@@ -134,30 +163,7 @@ namespace Jackett.Common.Utils.Clients
ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;
// custom handler for our own internal certificates
ServicePointManager.ServerCertificateValidationCallback += delegate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
if (sender.GetType() != typeof(HttpWebRequest))
return sslPolicyErrors == SslPolicyErrors.None;
var request = (HttpWebRequest)sender;
var hash = certificate.GetCertHashString();
ICollection<string> hosts;
trustedCertificates.TryGetValue(hash, out hosts);
if (hosts != null)
{
if (hosts.Contains(request.Host))
return true;
}
if (sslPolicyErrors != SslPolicyErrors.None)
{
throw new Exception("certificate validation failed: " + certificate.ToString());
}
return sslPolicyErrors == SslPolicyErrors.None;
};
ServicePointManager.ServerCertificateValidationCallback += ValidateCertificate;
}
override protected async Task<WebClientByteResult> Run(WebRequest webRequest)