// Copyright (C) 2025, The Duplicati Team // https://duplicati.com, hello@duplicati.com // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Threading; using Duplicati.Library.Interface; namespace Duplicati.Library.Utility { public static class SystemContextSettings { private static string defaultTempPath = null; private struct SystemSettings { public string Tempdir; public long Buffersize; } public static string DefaultTempPath { get { return defaultTempPath ?? System.IO.Path.GetTempPath(); } set { if (!System.IO.Directory.Exists(value)) throw new FolderMissingException(Strings.TempFolder.TempFolderDoesNotExistError(value)); defaultTempPath = value; } } public static IDisposable StartSession(string tempdir = null, long buffersize = 0) { if (buffersize < 1024) buffersize = 64 * 1024; var systemSettings = new SystemSettings { Tempdir = string.IsNullOrWhiteSpace(tempdir) ? DefaultTempPath : tempdir, Buffersize = buffersize }; return CallContextSettings.StartContext(systemSettings); } public static string Tempdir { get { var tf = CallContextSettings.Settings.Tempdir; if (string.IsNullOrWhiteSpace(tf)) { tf = DefaultTempPath; } return tf; } set { var st = CallContextSettings.Settings; st.Tempdir = value; CallContextSettings.Settings = st; } } public static long Buffersize { get { var bs = CallContextSettings.Settings.Buffersize; if (bs < 1024) bs = 64 * 1024; return bs; } } } /// /// Class for providing call-context access to http settings /// public static class HttpContextSettings { /// /// Internal struct with properties /// private struct HttpSettings { /// /// Gets or sets the operation timeout. /// /// The operation timeout. public TimeSpan OperationTimeout; /// /// Gets or sets the read write timeout. /// /// The read write timeout. public TimeSpan ReadWriteTimeout; /// /// Gets or sets a value indicating whether http requests are buffered. /// /// true if buffer requests; otherwise, false. public bool BufferRequests; /// /// Gets or sets the certificate validator. /// /// The certificate validator. public SslCertificateValidator CertificateValidator; } /// /// Starts a new session /// /// The session. /// The operation timeout. /// The readwrite timeout. /// If set to true http requests are buffered. public static IDisposable StartSession(TimeSpan operationTimeout = default(TimeSpan), TimeSpan readwriteTimeout = default(TimeSpan), bool bufferRequests = false, bool acceptAnyCertificate = false, string[] allowedCertificates = null) { // Make sure we always use our own version of the callback System.Net.ServicePointManager.ServerCertificateValidationCallback = ServicePointManagerCertificateCallback; var httpSettings = new HttpSettings { OperationTimeout = operationTimeout, ReadWriteTimeout = readwriteTimeout, BufferRequests = bufferRequests, CertificateValidator = acceptAnyCertificate || (allowedCertificates != null) ? new SslCertificateValidator(acceptAnyCertificate, allowedCertificates) : null }; return CallContextSettings.StartContext(httpSettings); } /// /// The callback used to defer the call context, such that each scope can have its own callback /// /// true, if point manager certificate callback was serviced, false otherwise. /// The sender of the validation. /// The certificate to validate. /// The certificate chain. /// Errors discovered. private static bool ServicePointManagerCertificateCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { // If we have a custom SSL validator, invoke it if (HttpContextSettings.CertificateValidator != null) return CertificateValidator.ValidateServerCertificate(sender, certificate, chain, sslPolicyErrors); // Default is to only approve certificates without errors var result = sslPolicyErrors == SslPolicyErrors.None; // Hack: If we have no validator, see if the context is all messed up // This is not the right way, but ServicePointManager is not designed right for this var any = false; foreach (var v in CallContextSettings.GetAllInstances()) if (v.CertificateValidator != null) { var t = v.CertificateValidator.ValidateServerCertificate(sender, certificate, chain, sslPolicyErrors); // First instance overrides framework result if (!any) result = t; // If there are more, we see if anyone will accept it else result |= t; any = true; } return result; } /// /// Gets the operation timeout. /// /// The operation timeout. public static TimeSpan OperationTimeout => CallContextSettings.Settings.OperationTimeout; /// /// Gets the read-write timeout. /// /// The read write timeout. public static TimeSpan ReadWriteTimeout => CallContextSettings.Settings.ReadWriteTimeout; /// /// Gets a value indicating whether https requests are buffered. /// /// true if buffer requests; otherwise, false. public static bool BufferRequests => CallContextSettings.Settings.BufferRequests; /// /// Gets or sets the certificate validator. /// /// The certificate validator. public static SslCertificateValidator CertificateValidator => CallContextSettings.Settings.CertificateValidator; } /// /// Help class for providing settings in the current call context /// public static class CallContextSettings { /// /// The call context settings for OAuth /// private static readonly AsyncLocal _settings = new AsyncLocal(); /// /// The instances that are currently active /// private static readonly ConcurrentDictionary _instances = new ConcurrentDictionary(); /// /// Disposable class for setting call context settings /// /// The type of the settings private sealed class Disposer : IDisposable { /// /// A flag indicating if the object has been disposed /// private bool m_disposed = false; /// /// The previous value /// private T m_prev; /// /// The current value /// private T m_current; /// /// Initializes a new instance of the class. /// /// The current server URL /// The previous server URL public Disposer(T current, T prev) { _settings.Value = m_current = current; this.m_prev = prev; _instances.TryAdd(current, null); } /// public void Dispose() { if (m_disposed) return; GC.SuppressFinalize(this); m_disposed = true; if (_settings.Value.Equals(m_current)) _settings.Value = m_prev; _instances.TryRemove(m_current, out _); } } /// /// Gets or sets the values in the current call context /// /// The settings. public static T Settings { get => _settings.Value; set => _settings.Value = value; } /// /// Starts the context wit a default value. /// /// The disposable handle for the context. /// The initial value. public static IDisposable StartContext(T initial = default(T)) => new Disposer(initial, _settings.Value); public static IEnumerable GetAllInstances() => _instances.Keys.ToList(); } }