FrameworkProxyDetector.cs 2.6 KB

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