FrameworkProxyDetector.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #if !UNITY_WEBGL || UNITY_EDITOR
  2. using System;
  3. using Best.HTTP.Shared;
  4. namespace Best.HTTP.Proxies.Autodetect
  5. {
  6. /// <summary>
  7. /// This is a detector using the .net framework's implementation. It might work not just under Windows but MacOS and Linux too.
  8. /// </summary>
  9. /// <remarks>
  10. /// More details can be found here:
  11. /// <list type="bullet">
  12. /// <item><description><see href="https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.defaultproxy?view=net-6.0">HttpClient.DefaultProxy Property</see></description></item>
  13. /// </list>
  14. /// </remarks>
  15. public sealed class FrameworkProxyDetector : IProxyDetector
  16. {
  17. Proxy IProxyDetector.GetProxy(HTTPRequest request)
  18. {
  19. var detectedProxy = System.Net.WebRequest.GetSystemWebProxy() as System.Net.WebProxy;
  20. if (detectedProxy != null && detectedProxy.Address != null)
  21. {
  22. var proxyUri = detectedProxy.GetProxy(request.CurrentUri);
  23. if (proxyUri != null && !proxyUri.Equals(request.CurrentUri))
  24. {
  25. if (proxyUri.Scheme.StartsWith("socks", StringComparison.OrdinalIgnoreCase))
  26. {
  27. return SetExceptionList(new SOCKSProxy(proxyUri, null), detectedProxy);
  28. }
  29. else if (proxyUri.Scheme.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  30. {
  31. return SetExceptionList(new HTTPProxy(proxyUri), detectedProxy);
  32. }
  33. else
  34. {
  35. HTTPManager.Logger.Warning(nameof(FrameworkProxyDetector), $"{nameof(IProxyDetector.GetProxy)} - FindFor returned with unknown format. proxyUri: '{proxyUri}'", request.Context);
  36. }
  37. }
  38. }
  39. return null;
  40. }
  41. private Proxy SetExceptionList(Proxy proxy, System.Net.WebProxy detectedProxy)
  42. {
  43. if (detectedProxy.BypassProxyOnLocal)
  44. {
  45. proxy.Exceptions = proxy.Exceptions ?? new System.Collections.Generic.List<string>();
  46. proxy.Exceptions.Add("localhost");
  47. proxy.Exceptions.Add("127.0.0.1");
  48. }
  49. // TODO: use BypassList to put more entries to the Exceptions list.
  50. // But because BypassList contains regex strings, we either
  51. // 1.) store and use regex strings in the Exception list (not backward compatible)
  52. // 2.) store non-regex strings but create a new list for regex
  53. // 3.) detect if the stored entry in the Exceptions list is regex or not and use it accordingly
  54. // "^.*\\.httpbin\\.org$"
  55. // https://github.com/Benedicht/BestHTTP-Issues/issues/141
  56. return proxy;
  57. }
  58. }
  59. }
  60. #endif