コード例 #1
0
        public void TestPACParsingUrlAsyncNoProxy()
        {
            TestRuntime.IgnoreInCI("CI bots might have proxies setup and will mean that the test will fail when trying to assert they are empty.");
            CFProxy [] proxies   = null;
            NSError    error     = null;
            NSObject   cbClient  = null;
            bool       done      = false;
            string     pacPath   = Path.Combine(NSBundle.MainBundle.BundlePath, "example.pac");
            var        pacUri    = new Uri(pacPath);
            var        targetUri = new Uri("http://docs.google.com");

            Exception ex;
            bool      foundProxies;

            // similar to the other tests, but we want to ensure that the async/await API works
            TestRuntime.RunAsync(DateTime.Now.AddSeconds(30), async() => {
                try {
                    CancellationTokenSource cancelSource = new CancellationTokenSource();
                    CancellationToken cancelToken        = cancelSource.Token;
                    var result = await CFNetwork.ExecuteProxyAutoConfigurationUrlAsync(pacUri, targetUri, cancelToken);
                    proxies    = result.proxies;
                    error      = result.error;
                } catch (Exception e) {
                    ex = e;
                } finally {
                    done = true;
                }
            }, () => done);
            Assert.IsNull(cbClient, "Null client");
            Assert.IsNull(error, "Null error");
            Assert.IsNotNull(proxies, "Not null proxies");
            Assert.AreEqual(1, proxies.Length, "Proxies length");
            Assert.AreEqual(CFProxyType.None, proxies [0].ProxyType);
        }
コード例 #2
0
        public void TestPACParsingAsync()
        {
            CFProxy [] proxies  = null;
            NSError    error    = null;
            NSObject   cbClient = null;
            bool       done     = false;
            string     pacPath  = Path.Combine(NSBundle.MainBundle.BundlePath, "example.pac");

            var script    = File.ReadAllText(pacPath);
            var targetUri = new Uri("http://docs.xamarin.com");

            Exception ex;
            bool      foundProxies;

            // similar to the other tests, but we want to ensure that the async/await API works
            TestRuntime.RunAsync(DateTime.Now.AddSeconds(30), async() => {
                try {
                    CancellationTokenSource cancelSource = new CancellationTokenSource();
                    CancellationToken cancelToken        = cancelSource.Token;
                    var result = await CFNetwork.ExecuteProxyAutoConfigurationScriptAsync(script, targetUri, cancelToken);
                    proxies    = result.proxies;
                    error      = result.error;
                } catch (Exception e) {
                    ex = e;
                } finally {
                    done = true;
                }
            }, () => done);
            Assert.IsNull(cbClient, "Null client");
            Assert.IsNull(error, "Null error");
            Assert.IsNotNull(proxies, "Not null proxies");
            Assert.AreEqual(1, proxies.Length, "Length");
            // assert the data of the proxy, although we are really testing the js used
            Assert.AreEqual(8080, proxies [0].Port, "Port");
        }
コード例 #3
0
        public void WebProxy()
        {
            IWebProxy proxy = CFNetwork.GetDefaultProxy();

            Assert.True(proxy.IsBypassed(uri), "IsBypassed");
            Assert.That(proxy.GetProxy(uri), Is.SameAs(uri), "GetProxy");
        }
コード例 #4
0
ファイル: Forms.cs プロジェクト: zxyang178/Xamarin.Forms
            public void StartTimer(TimeSpan interval, Func <bool> callback)
            {
                NSTimer timer = null;

#if __UNIFIED__
                timer = NSTimer.CreateRepeatingScheduledTimer(interval, t =>
                {
#else
                timer = NSTimer.CreateRepeatingScheduledTimer(interval, () => {
                                #endif
                    if (!callback())
#if __UNIFIED__
                    { t.Invalidate(); }
#else
                    { timer.Invalidate(); }
                                                #endif
                });
                NSRunLoop.Main.AddTimer(timer, NSRunLoopMode.Common);
            }

            HttpClient GetHttpClient()
            {
                var proxy   = CFNetwork.GetSystemProxySettings();
                var handler = new HttpClientHandler();

                if (!string.IsNullOrEmpty(proxy.HTTPProxy))
                {
                    handler.Proxy    = CFNetwork.GetDefaultProxy();
                    handler.UseProxy = true;
                }
                return(new HttpClient(handler));
            }
コード例 #5
0
        public void TestPACParsingScriptError()
        {
            NSError error     = null;
            var     script    = "Not VALID js";
            var     targetUri = new Uri("http://google.com");
            var     proxies   = CFNetwork.ExecuteProxyAutoConfigurationScript(script, targetUri, out error);

            Assert.IsNotNull(error, "Not null error");
            Assert.IsNull(proxies, "Null proxies");
        }
コード例 #6
0
        public WebProxy GetProxySettings()
        {
            var systemProxySettings = CFNetwork.GetSystemProxySettings();

            var proxyPort = systemProxySettings.HTTPPort;
            var proxyHost = systemProxySettings.HTTPProxy;

            return(!string.IsNullOrEmpty(proxyHost) && proxyPort != 0
                ? new WebProxy($"{proxyHost}:{proxyPort}")
                : null);
        }
コード例 #7
0
 public IOSRequestBuilder()
 {
     //NOTE: DO NOT USE YOUR MASTER CREDENTIALS HERE
     BuildApplicationCredentials = () => new NetworkCredential("ApplicationName", "ApplicationSecret");
     ConfigureRequest = request =>
         {
             request.Proxy = CFNetwork.GetDefaultProxy();
             //only a suggested timeout
             request.Timeout = 30000;
         };
 }
コード例 #8
0
            HttpClient GetHttpClient()
            {
                var proxy   = CFNetwork.GetSystemProxySettings();
                var handler = new HttpClientHandler();

                if (!string.IsNullOrEmpty(proxy.HTTPProxy))
                {
                    handler.Proxy    = CFNetwork.GetDefaultProxy();
                    handler.UseProxy = true;
                }
                return(new HttpClient(handler));
            }
コード例 #9
0
        public void TestPACParsingUrl()
        {
            NSError error;
            string  pacPath   = Path.Combine(NSBundle.MainBundle.BundlePath, "example.pac");
            var     pacUri    = new Uri(pacPath);
            var     targetUri = new Uri("http://docs.xamarin.com");
            var     proxies   = CFNetwork.ExecuteProxyAutoConfigurationUrl(pacUri, targetUri, out error);

            Assert.IsNull(error, "Null error");
            Assert.AreEqual(1, proxies.Length, "Length");
            // assert the data of the proxy, although we are really testing the js used
            Assert.AreEqual(8080, proxies [0].Port, "Port");
        }
コード例 #10
0
        public void TestPACParsingScriptNoProxy()
        {
            string  pacPath   = Path.Combine(NSBundle.MainBundle.BundlePath, "example.pac");
            NSError error     = null;
            var     script    = File.ReadAllText(pacPath);
            var     targetUri = new Uri("http://google.com");
            var     proxies   = CFNetwork.ExecuteProxyAutoConfigurationScript(script, targetUri, out error);

            Assert.IsNull(error, "Null error");
            Assert.IsNotNull(proxies, "Not null proxies");
            Assert.AreEqual(1, proxies.Length, "Proxies length");
            Assert.AreEqual(CFProxyType.None, proxies [0].ProxyType);
        }
コード例 #11
0
        public WebProxy GetWebProxy()
        {
            CFProxySettings systemProxySettings = CFNetwork.GetSystemProxySettings();
            string          proxyHost           = systemProxySettings.HTTPProxy;
            int             proxyPort           = systemProxySettings.HTTPPort;

            if (!string.IsNullOrWhiteSpace(proxyHost) &&
                proxyPort != 0)
            {
                return(new WebProxy(proxyHost, proxyPort));
            }

            return(null);
        }
コード例 #12
0
        public void GetProxiesForUri()
        {
            var proxies = CFNetwork.GetProxiesForUri(uri, settings);

            Assert.That(proxies.Length, Is.EqualTo(1), "single");
            var p = proxies [0];

            Assert.Null(p.AutoConfigurationJavaScript, "AutoConfigurationJavaScript");
            Assert.Null(p.AutoConfigurationUrl, "AutoConfigurationUrl");
            Assert.Null(p.HostName, "HostName");
            Assert.That(p.Port, Is.EqualTo(0), "Port");
            Assert.Null(p.Password, "Password");
            Assert.That(p.ProxyType, Is.EqualTo(CFProxyType.None), "Type");
            Assert.Null(p.Username, "Username");
        }
コード例 #13
0
        public void TestPACParsingScript()
        {
            // get the path for the pac file, try to parse it and ensure that
            // our cb was called
            string  pacPath   = Path.Combine(NSBundle.MainBundle.BundlePath, "example.pac");
            NSError error     = null;
            var     script    = File.ReadAllText(pacPath);
            var     targetUri = new Uri("http://docs.xamarin.com");
            var     proxies   = CFNetwork.ExecuteProxyAutoConfigurationScript(script, targetUri, out error);

            Assert.IsNull(error, "Null error");
            Assert.AreEqual(1, proxies.Length, "Length");
            // assert the data of the proxy, although we are really testing the js used
            Assert.AreEqual(8080, proxies [0].Port, "Port");
        }
コード例 #14
0
        public void Bug_7923()
        {
            // Bug #7923 - crash when proxy is in effect.
            var uri = new Uri("http://www.google.com");

            if (CFNetwork.GetProxiesForUri(uri, settings).Length <= 1)
            {
                Assert.Ignore("Only run when proxy is configured.");
            }

            var req = new HttpWebRequest(uri);

            using (var rsp = req.GetResponse())
                using (var str = new StreamReader(rsp.GetResponseStream()))
                    Console.WriteLine(str.ReadToEnd());
        }
コード例 #15
0
            static Uri GetProxyUriFromScript(IntPtr script, Uri targetUri, out NetworkCredential credentials)
            {
                CFProxy[] proxies = CFNetwork.GetProxiesForAutoConfigurationScript(script, targetUri);

                if (proxies == null)
                {
                    credentials = null;
                    return(targetUri);
                }

                for (int i = 0; i < proxies.Length; i++)
                {
                    switch (proxies[i].ProxyType)
                    {
                    case CFProxyType.HTTPS:
                    case CFProxyType.HTTP:
                    case CFProxyType.FTP:
                        // create a Uri based on the hostname/port/etc info
                        return(GetProxyUri(proxies[i], out credentials));

                    case CFProxyType.SOCKS:
                    default:
                        // unsupported proxy type, try the next one
                        break;

                    case CFProxyType.None:
                        // no proxy should be used
                        credentials = null;
                        return(targetUri);
                    }
                }

                credentials = null;

                return(null);
            }
コード例 #16
0
 public void WebProxy_Leak()
 {
     // note: needs to be executed under Instrument to verify it does not leak
     Assert.NotNull(CFNetwork.GetSystemProxySettings(), "should not leak");
 }
コード例 #17
0
        public static IWebProxy GetSystemWebProxy()
        {
#if MONOTOUCH
            return(CFNetwork.GetDefaultProxy());
#else
#if MONODROID
            // Return the system web proxy.  This only works for ICS+.
            var androidProxy = AndroidPlatform.GetDefaultProxy();
            if (androidProxy != null)
            {
                return(androidProxy);
            }
#endif
#if !NET_2_1 && !SSHARP
            if (IsWindows())
            {
                int iProxyEnable =
                    (int)Microsoft.Win32.Registry.GetValue("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", "ProxyEnable", 0);

                if (iProxyEnable > 0)
                {
                    string    strHttpProxy   = "";
                    bool      bBypassOnLocal = false;
                    ArrayList al             = new ArrayList();

                    string strProxyServer =
                        (string)Microsoft.Win32.Registry.GetValue("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", "ProxyServer", null);
                    string strProxyOverrride =
                        (string)Microsoft.Win32.Registry.GetValue("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", "ProxyOverride", null);

                    if (strProxyServer.Contains("="))
                    {
                        foreach (string strEntry in strProxyServer.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
                        {
                            if (strEntry.StartsWith("http="))
                            {
                                strHttpProxy = strEntry.Substring(5);
                                break;
                            }
                        }
                    }
                    else
                    {
                        strHttpProxy = strProxyServer;
                    }

                    if (strProxyOverrride != null)
                    {
                        string[] bypassList = strProxyOverrride.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

                        foreach (string str in bypassList)
                        {
                            if (str != "<local>")
                            {
                                al.Add(str);
                            }
                            else
                            {
                                bBypassOnLocal = true;
                            }
                        }
                    }

                    return(new WebProxy(strHttpProxy, bBypassOnLocal, al.ToArray(typeof(string)) as string[]));
                }
            }
            else
            {
#endif
#if !NETCF
            if (Platform.IsMacOS)
            {
                return(CFNetwork.GetDefaultProxy());
            }
#endif
#if !SSHARP
            string address = Environment.GetEnvironmentVariable("http_proxy");

            if (address == null)
            {
                address = Environment.GetEnvironmentVariable("HTTP_PROXY");
            }

            if (address != null)
            {
                try
                {
                    if (!address.StartsWith("http://"))
                    {
                        address = "http://" + address;
                    }

                    Uri       uri = new Uri(address);
                    IPAddress ip;

                    if (IPAddress.TryParse(uri.Host, out ip))
                    {
                        if (IPAddress.Any.Equals(ip))
                        {
                            UriBuilder builder = new UriBuilder(uri);
                            builder.Host = "127.0.0.1";
                            uri          = builder.Uri;
                        }
                        else if (IPAddress.IPv6Any.Equals(ip))
                        {
                            UriBuilder builder = new UriBuilder(uri);
                            builder.Host = "[::1]";
                            uri          = builder.Uri;
                        }
                    }

                    bool      bBypassOnLocal = false;
                    ArrayList al             = new ArrayList();
                    string    bypass         = Environment.GetEnvironmentVariable("no_proxy");

                    if (bypass == null)
                    {
                        bypass = Environment.GetEnvironmentVariable("NO_PROXY");
                    }

                    if (bypass != null)
                    {
                        string[] bypassList = bypass.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                        foreach (string str in bypassList)
                        {
                            if (str != "*.local")
                            {
                                al.Add(str);
                            }
                            else
                            {
                                bBypassOnLocal = true;
                            }
                        }
                    }

                    return(new WebProxy(uri, bBypassOnLocal, al.ToArray(typeof(string)) as string[]));
                }
                catch (UriFormatException)
                {
                }
            }
#if !NET_2_1
        }
#endif
#endif
            return(new WebProxy());
#endif // MONOTOUCH
        }
コード例 #18
0
 static Uri GetProxyUriFromScript(IntPtr script, Uri targetUri, out NetworkCredential credentials)
 {
     CFProxy[] proxies = CFNetwork.GetProxiesForAutoConfigurationScript(script, targetUri);
     return(SelectProxy(proxies, targetUri, out credentials));
 }
コード例 #19
0
 static Uri ExecuteProxyAutoConfigurationURL(IntPtr proxyAutoConfigURL, Uri targetUri, out NetworkCredential credentials)
 {
     CFProxy[] proxies = CFNetwork.ExecuteProxyAutoConfigurationURL(proxyAutoConfigURL, targetUri);
     return(SelectProxy(proxies, targetUri, out credentials));
 }
コード例 #20
0
            public Uri GetProxy(Uri targetUri)
            {
                NetworkCredential credentials = null;
                Uri proxy = null;

                if (targetUri == null)
                {
                    throw new ArgumentNullException("targetUri");
                }

                try {
                    CFProxySettings settings = CFNetwork.GetSystemProxySettings();
                    CFProxy[]       proxies  = CFNetwork.GetProxiesForUri(targetUri, settings);

                    if (proxies != null)
                    {
                        for (int i = 0; i < proxies.Length && proxy == null; i++)
                        {
                            switch (proxies[i].ProxyType)
                            {
                            case CFProxyType.AutoConfigurationJavaScript:
                                proxy = GetProxyUriFromScript(proxies[i].AutoConfigurationJavaScript, targetUri, out credentials);
                                break;

                            case CFProxyType.AutoConfigurationUrl:
                                proxy = ExecuteProxyAutoConfigurationURL(proxies[i].AutoConfigurationUrl, targetUri, out credentials);
                                break;

                            case CFProxyType.HTTPS:
                            case CFProxyType.HTTP:
                            case CFProxyType.FTP:
                                // create a Uri based on the hostname/port/etc info
                                proxy = GetProxyUri(proxies[i], out credentials);
                                break;

                            case CFProxyType.SOCKS:
                                // unsupported proxy type, try the next one
                                break;

                            case CFProxyType.None:
                                // no proxy should be used
                                proxy = targetUri;
                                break;
                            }
                        }

                        if (proxy == null)
                        {
                            // no supported proxies for this Uri, fall back to trying to connect to targetUri directly
                            proxy = targetUri;
                        }
                    }
                    else
                    {
                        proxy = targetUri;
                    }
                } catch {
                    // ignore errors while retrieving proxy data
                    proxy = targetUri;
                }

                if (!userSpecified)
                {
                    this.credentials = credentials;
                }

                return(proxy);
            }