示例#1
0
        public void Init()
        {
            TestRuntime.AssertXcodeVersion(10, 0);
            // we want to use a single connection, since it is expensive
            connectedEvent = new AutoResetEvent(false);
            host           = "www.google.com";
            using (var parameters = NWParameters.CreateTcp())
                using (var endpoint = NWEndpoint.Create(host, "80")) {
                    connection = new NWConnection(endpoint, parameters);
                    connection.SetQueue(DispatchQueue.DefaultGlobalQueue);              // important, else we will get blocked
                    connection.SetStateChangeHandler(ConnectionStateHandler);
                    connection.Start();
                    Assert.True(connectedEvent.WaitOne(20000), "Connection timed out.");
                    stack = parameters.ProtocolStack;
                    using (var ipOptions = stack.InternetProtocol) {
                        if (ipOptions != null)
                        {
#if NET
                            ipOptions.SetVersion(NWIPVersion.Version4);
#else
                            ipOptions.IPSetVersion(NWIPVersion.Version4);
#endif
                            stack.PrependApplicationProtocol(ipOptions);
                        }
                    }
                }
        }
示例#2
0
        public void AddServerAddressTest()
        {
            using var secondEndpoint = NWEndpoint.Create("https://github.com");
            using var resolver       = new NWResolverConfig(endpoint, NWResolverConfigEndpointType.Https);

            Assert.DoesNotThrow(() => resolver.AddServerAddress(secondEndpoint));
        }
示例#3
0
 public void Init()
 {
     TestRuntime.AssertXcodeVersion(11, 0);
     // connect so that we can later when the report and test with it
     connectedEvent = new AutoResetEvent(false);
     reportEvent    = new AutoResetEvent(false);
     host           = NetworkResources.MicrosoftUri.Host;
     // we create a connection which we are going to use to get the availabe
     // interfaces, that way we can later test protperties of the NWParameters class.
     using (var parameters = NWParameters.CreateUdp())
         using (var endpoint = NWEndpoint.Create(host, "80"))
         {
             using (var protocolStack = parameters.ProtocolStack) {
                 var ipOptions = protocolStack.InternetProtocol;
                 ipOptions.IPSetVersion(NWIPVersion.Version4);
             }
             connection = new NWConnection(endpoint, parameters);
             connection.SetQueue(DispatchQueue.DefaultGlobalQueue);              // important, else we will get blocked
             connection.SetStateChangeHandler(ConnectionStateHandler);
             connection.Start();
             Assert.True(connectedEvent.WaitOne(20000), "Connection timed out.");
             connection.GetEstablishmentReport(DispatchQueue.DefaultGlobalQueue, (r) => {
                 report = r;
                 reportEvent.Set();
             });
             Assert.True(reportEvent.WaitOne(20000), "Connection timed out.");
         }
 }
示例#4
0
        public void Init()
        {
            TestRuntime.AssertXcodeVersion(10, 0);
            // we want to use a single connection, since it is expensive
            connectedEvent = new AutoResetEvent(false);
            interfaces     = new List <NWInterface> ();
            host           = NetworkResources.MicrosoftUri.Host;
            // we create a connection which we are going to use to get the availabe
            // interfaces, that way we can later test protperties of the NWParameters class.
            using (var parameters = NWParameters.CreateUdp())
                using (var endpoint = NWEndpoint.Create(host, "80"))
                {
                    using (var protocolStack = parameters.ProtocolStack) {
                        var ipOptions = protocolStack.InternetProtocol;
#if NET
                        ipOptions.SetVersion(NWIPVersion.Version4);
#else
                        ipOptions.IPSetVersion(NWIPVersion.Version4);
#endif
                    }
                    connection = new NWConnection(endpoint, parameters);
                    connection.SetQueue(DispatchQueue.DefaultGlobalQueue);              // important, else we will get blocked
                    connection.SetStateChangeHandler(ConnectionStateHandler);
                    connection.Start();
                    Assert.True(connectedEvent.WaitOne(20000), "Connection timed out.");
                }
        }
示例#5
0
    static NWConnection CreateOutboundConnection(string name, string port)
    {
        NWEndpoint endpoint;

        if (bonjour)
        {
            endpoint = NWEndpoint.CreateBonjourService(name, GetServiceType(), "local");
        }
        else
        {
            endpoint = NWEndpoint.Create(name, port);
        }

        Action <NWProtocolOptions> configureTls = SetupTls();
        NWParameters parameters;

        if (useUdp)
        {
            if (useTls)
            {
                parameters = NWParameters.CreateSecureUdp(configureTls: configureTls, configureUdp: null);
            }
            else
            {
                parameters = NWParameters.CreateUdp(configureUdp: null);
            }
        }
        else
        {
            if (useTls)
            {
                parameters = NWParameters.CreateSecureTcp(configureTls: configureTls, configureTcp: null);
            }
            else
            {
                parameters = NWParameters.CreateTcp(configureTcp: null);
            }
        }

        using (NWProtocolStack protocolStack = parameters.ProtocolStack){
            if (ipv4 || ipv6)
            {
                NWProtocolOptions ipOptions = protocolStack.InternetProtocol;
                ipOptions.IPSetVersion(ipv4 ? NWIPVersion.Version4 : NWIPVersion.Version6);
            }
        }

        if (localAddr != null || localPort != null)
        {
            using (NWEndpoint localEndpoint = NWEndpoint.Create(localAddr != null ? localAddr : "::", port == null ? "0" : port))
                parameters.LocalEndpoint = localEndpoint;
        }

        var connection = new NWConnection(endpoint, parameters);

        endpoint.Dispose();
        parameters.Dispose();
        return(connection);
    }
 public void SetSpecificSourceTest()
 {
     Assert.DoesNotThrow(() => {
         // create new endpoint and later ensure that it is present in the enumeration
         var newEndpoint = NWEndpoint.Create("224.0.0.252", "5454");
         descriptor.SetSpecificSource(newEndpoint);
     });
 }
 public void SetUp()
 {
     TestRuntime.AssertXcodeVersion(12, TestRuntime.MinorXcode12APIMismatch);
     endpoint        = NWEndpoint.Create("224.0.0.251", "5353");
     parameters      = NWParameters.CreateUdp();
     descriptor      = new NWMulticastGroup(endpoint);
     connectionGroup = new NWConnectionGroup(descriptor, parameters);
 }
        public void CreateSecureTcpTestDoNotSetUpTls()
        {
            var setUpProtocol = CreateConfigureProtocolHandler();

            using (var parameters = NWParameters.CreateSecureTcp(configureTls: null, configureTcp: setUpProtocol))
                using (var endpoint = NWEndpoint.Create(NetworkResources.MicrosoftUri.Host, "80")) {
                    configureEvent.WaitOne();
                    Assert.False(secureConnectionWasSet, "Configure TLS handler was called.");
                    Assert.True(protocolConfigured, "Protocol configure handler was not called.");
                }
        }
        public void CreateCustomIP()
        {
            TestRuntime.AssertXcodeVersion(11, 0);
            byte ipVersion     = 10;
            var  setUpProtocol = CreateConfigureProtocolHandler();

            using (var parameters = NWParameters.CreateCustomIP(ipVersion, setUpProtocol))
                using (var endpoint = NWEndpoint.Create("wwww.google.com", "80")) {
                    configureEvent.WaitOne();
                    Assert.True(protocolConfigured, "Protocol configure handler was not called.");
                }
        }
 public void LocalEndpointPropertyTest()
 {
     Assert.Ignore("nw_parameters_copy_local_endpoint always return null. Rdar filled 44095278.");
     using (var parameters = NWParameters.CreateUdp())
         using (var endpoint = NWEndpoint.Create(NetworkResources.MicrosoftUri.Host, "80"))
         {
             var defaultValue = parameters.LocalEndpoint;
             Assert.IsNull(defaultValue, "Default value changed.");
             parameters.LocalEndpoint = endpoint;
             Assert.IsNotNull(parameters.LocalEndpoint, "New value was not stored.");
         }
 }
示例#11
0
        public void CreateSecureTcpTestDoNotSetUpTls()
        {
            var setUpProtocol = CreateConfigureProtocolHandler();

            using (var parameters = NWParameters.CreateSecureTcp(configureTls: null, configureTcp: setUpProtocol))
                using (var endpoint = NWEndpoint.Create("wwww.google.com", "80"))
                    using (var connection = new NWConnection(endpoint, parameters)) {
                        connection.SetQueue(DispatchQueue.MainQueue);
                        connection.Start();
                        configureEvent.WaitOne();
                        connection.Cancel();
                        Assert.False(secureConnectionWasSet, "Configure TLS handler was called.");
                        Assert.True(protocolConfigured, "Protocol configure handler was not called.");
                    }
        }
        public void AddEndpointTest()
        {
            Assert.Throws <ArgumentNullException> (() => {
                descriptor.AddEndpoint(null);
            }, "Null argument.");

            // create new endpoint and later ensure that it is present in the enumeration
            var newEndpoint = NWEndpoint.Create("224.0.0.252", "5454");

            descriptor.AddEndpoint(newEndpoint);

            var e = new AutoResetEvent(false);

            descriptor.EnumerateEndpoints((endPoint) => {
                Assert.IsNotNull(endPoint);
                e.Set();
                return(true);
            });
            e.WaitOne(10000);
        }
 public void Init()
 {
     TestRuntime.AssertXcodeVersion(10, 0);
     // we want to use a single connection, since it is expensive
     connectedEvent = new AutoResetEvent(false);
     host           = NetworkResources.MicrosoftUri.Host;
     interfaces     = new List <NWInterface> ();
     using (var parameters = NWParameters.CreateUdp())
         using (var endpoint = NWEndpoint.Create(host, "80")) {
             connection = new NWConnection(endpoint, parameters);
             connection.SetQueue(DispatchQueue.DefaultGlobalQueue);              // important, else we will get blocked
             connection.SetStateChangeHandler(ConnectionStateHandler);
             connection.Start();
             Assert.True(connectedEvent.WaitOne(20000), "Connection timed out.");
             using (var path = connection.CurrentPath)
             {
                 path.EnumerateInterfaces(EnumerateInterfacesHandler);
             }
         }
 }
示例#14
0
 public void SetUp()
 {
     // connect and once the connection is done, deal with the diff tests
     connectedEvent = new AutoResetEvent(false);
     host           = NetworkResources.MicrosoftUri.Host;
     // we create a connection which we are going to use to get the availabe
     // interfaces, that way we can later test protperties of the NWParameters class.
     using (var parameters = NWParameters.CreateUdp())
         using (var endpoint = NWEndpoint.Create(host, "80"))
         {
             using (var protocolStack = parameters.ProtocolStack) {
                 var ipOptions = protocolStack.InternetProtocol;
                 ipOptions.IPSetVersion(NWIPVersion.Version4);
             }
             connection = new NWConnection(endpoint, parameters);
             connection.SetQueue(DispatchQueue.DefaultGlobalQueue);              // important, else we will get blocked
             connection.SetStateChangeHandler(ConnectionStateHandler);
             connection.Start();
             Assert.True(connectedEvent.WaitOne(20000), "Connection timed out.");
         }
 }
 public void SetUp()
 {
     TestRuntime.AssertXcodeVersion(12, TestRuntime.MinorXcode12APIMismatch);
     endpoint   = NWEndpoint.Create("224.0.0.251", "5353");
     descriptor = new NWMulticastGroup(endpoint);
 }
        public void TlsDefaults()
        {
            using (var ep = NWEndpoint.Create("www.microsoft.com", "https"))
                using (var parameters = NWParameters.CreateSecureTcp())
                    using (var queue = new DispatchQueue(GetType().FullName)) {
                        var connection = new NWConnection(ep, parameters);

                        var ready = new ManualResetEvent(false);
                        connection.SetStateChangeHandler((state, error) => {
                            Console.WriteLine(state);
                            switch (state)
                            {
                            case NWConnectionState.Cancelled:
                            case NWConnectionState.Failed:
                                // We can't dispose until the connection has been closed or it failed.
                                connection.Dispose();
                                break;

                            case NWConnectionState.Invalid:
                            case NWConnectionState.Preparing:
                            case NWConnectionState.Waiting:
                                break;

                            case NWConnectionState.Ready:
                                ready.Set();
                                break;

                            default:
                                break;
                            }
                        });

                        connection.SetQueue(queue);
                        connection.Start();

                        // Wait until the connection is ready.
                        Assert.True(ready.WaitOne(TimeSpan.FromSeconds(10)), "Connection is ready");

                        using (var m = connection.GetProtocolMetadata(NWProtocolDefinition.TlsDefinition)) {
                            var s = m.TlsSecProtocolMetadata;
                            Assert.False(s.EarlyDataAccepted, "EarlyDataAccepted");
                            Assert.That(s.NegotiatedCipherSuite, Is.Not.EqualTo(SslCipherSuite.SSL_NULL_WITH_NULL_NULL), "NegotiatedCipherSuite");
                            Assert.Null(s.NegotiatedProtocol, "NegotiatedProtocol");
                            Assert.That(s.NegotiatedProtocolVersion, Is.EqualTo(SslProtocol.Tls_1_2).Or.EqualTo(SslProtocol.Tls_1_3), "NegotiatedProtocolVersion");
                            Assert.NotNull(s.PeerPublicKey, "PeerPublicKey");

                            Assert.True(SecProtocolMetadata.ChallengeParametersAreEqual(s, s), "ChallengeParametersAreEqual");
                            Assert.True(SecProtocolMetadata.PeersAreEqual(s, s), "PeersAreEqual");

                            if (TestRuntime.CheckXcodeVersion(11, 0))
                            {
                                using (var d = s.CreateSecret("Xamarin", 128)) {
                                    Assert.That(d.Size, Is.EqualTo((nuint)128), "CreateSecret-1");
                                }
                                using (var d = s.CreateSecret("Microsoft", new byte [1], 256)) {
                                    Assert.That(d.Size, Is.EqualTo((nuint)256), "CreateSecret-2");
                                }

                                Assert.That(s.NegotiatedTlsProtocolVersion, Is.EqualTo(TlsProtocolVersion.Tls12).Or.EqualTo(TlsProtocolVersion.Tls13), "NegotiatedTlsProtocolVersion");
                                // we want to test the binding/API - not the exact value which can vary depending on the negotiation between the client (OS) and server...
                                Assert.That(s.NegotiatedTlsCipherSuite, Is.Not.EqualTo(0), "NegotiatedTlsCipherSuite");
                                Assert.That(s.ServerName, Is.EqualTo("www.microsoft.com"), "ServerName");
                                // we don't have a TLS-PSK enabled server to test this
                                Assert.False(s.AccessPreSharedKeys((psk, pskId) => { }), "AccessPreSharedKeys");
                            }
                        }

                        connection.Cancel();
                    }
        }
        protected INativeObject GetINativeInstance(Type t)
        {
            var ctor = t.GetConstructor(Type.EmptyTypes);

            if ((ctor != null) && !ctor.IsAbstract)
            {
                return(ctor.Invoke(null) as INativeObject);
            }

            if (!NativeObjectInterfaceType.IsAssignableFrom(t))
            {
                throw new ArgumentException("t");
            }
            switch (t.Name)
            {
            case "CFAllocator":
                return(CFAllocator.SystemDefault);

            case "CFBundle":
                var bundles = CFBundle.GetAll();
                if (bundles.Length > 0)
                {
                    return(bundles [0]);
                }
                else
                {
                    throw new InvalidOperationException(string.Format("Could not create the new instance for type {0}.", t.Name));
                }

            case "CFNotificationCenter":
                return(CFNotificationCenter.Darwin);

            case "CFReadStream":
            case "CFStream":
                CFReadStream  readStream;
                CFWriteStream writeStream;
                CFStream.CreatePairWithSocketToHost("www.google.com", 80, out readStream, out writeStream);
                return(readStream);

            case "CFWriteStream":
                CFStream.CreatePairWithSocketToHost("www.google.com", 80, out readStream, out writeStream);
                return(writeStream);

            case "CFUrl":
                return(CFUrl.FromFile("/etc"));

            case "CFPropertyList":
                return(CFPropertyList.FromData(NSData.FromString("<string>data</string>")).PropertyList);

            case "DispatchData":
                return(DispatchData.FromByteBuffer(new byte [] { 1, 2, 3, 4 }));

            case "AudioFile":
                var path = Path.GetFullPath("1.caf");
                var af   = AudioFile.Open(CFUrl.FromFile(path), AudioFilePermission.Read, AudioFileType.CAF);
                return(af);

            case "CFHTTPMessage":
                return(CFHTTPMessage.CreateEmpty(false));

            case "CFMutableString":
                return(new CFMutableString("xamarin"));

            case "CGBitmapContext":
                byte[] data = new byte [400];
                using (CGColorSpace space = CGColorSpace.CreateDeviceRGB()) {
                    return(new CGBitmapContext(data, 10, 10, 8, 40, space, CGBitmapFlags.PremultipliedLast));
                }

            case "CGContextPDF":
                var filename = Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments) + "/t.pdf";
                using (var url = new NSUrl(filename))
                    return(new CGContextPDF(url));

            case "CGColorConversionInfo":
                var cci = new GColorConversionInfoTriple()
                {
                    Space     = CGColorSpace.CreateGenericRgb(),
                    Intent    = CGColorRenderingIntent.Default,
                    Transform = CGColorConversionInfoTransformType.ApplySpace
                };
                return(new CGColorConversionInfo((NSDictionary)null, cci, cci, cci));

            case "CGDataConsumer":
                using (NSMutableData destData = new NSMutableData()) {
                    return(new CGDataConsumer(destData));
                }

            case "CGDataProvider":
                filename = "xamarin1.png";
                return(new CGDataProvider(filename));

            case "CGFont":
                return(CGFont.CreateWithFontName("Courier New"));

            case "CGPattern":
                return(new CGPattern(
                           new RectangleF(0, 0, 16, 16),
                           CGAffineTransform.MakeIdentity(),
                           16, 16,
                           CGPatternTiling.NoDistortion,
                           true,
                           (cgc) => {}));

            case "CMBufferQueue":
                return(CMBufferQueue.CreateUnsorted(2));

            case "CTFont":
                CTFontDescriptorAttributes fda = new CTFontDescriptorAttributes()
                {
                    FamilyName = "Courier",
                    StyleName  = "Bold",
                    Size       = 16.0f
                };
                using (var fd = new CTFontDescriptor(fda))
                    return(new CTFont(fd, 10));

            case "CTFontCollection":
                return(new CTFontCollection(new CTFontCollectionOptions()));

            case "CTFontDescriptor":
                fda = new CTFontDescriptorAttributes();
                return(new CTFontDescriptor(fda));

            case "CTTextTab":
                return(new CTTextTab(CTTextAlignment.Left, 2));

            case "CTTypesetter":
                return(new CTTypesetter(new NSAttributedString("Hello, world",
                                                               new CTStringAttributes()
                {
                    ForegroundColorFromContext = true,
                    Font = new CTFont("ArialMT", 24)
                })));

            case "CTFrame":
                var framesetter = new CTFramesetter(new NSAttributedString("Hello, world",
                                                                           new CTStringAttributes()
                {
                    ForegroundColorFromContext = true,
                    Font = new CTFont("ArialMT", 24)
                }));
                var bPath = UIBezierPath.FromRect(new RectangleF(0, 0, 3, 3));
                return(framesetter.GetFrame(new NSRange(0, 0), bPath.CGPath, null));

            case "CTFramesetter":
                return(new CTFramesetter(new NSAttributedString("Hello, world",
                                                                new CTStringAttributes()
                {
                    ForegroundColorFromContext = true,
                    Font = new CTFont("ArialMT", 24)
                })));

            case "CTGlyphInfo":
                return(new CTGlyphInfo("Zapfino", new CTFont("ArialMT", 24), "Foo"));

            case "CTLine":
                return(new CTLine(new NSAttributedString("Hello, world",
                                                         new CTStringAttributes()
                {
                    ForegroundColorFromContext = true,
                    Font = new CTFont("ArialMT", 24)
                })));

            case "CGImageDestination":
                var storage = new NSMutableData();
                return(CGImageDestination.Create(new CGDataConsumer(storage), "public.png", 1));

            case "CGImageMetadataTag":
                using (NSString name = new NSString("tagName"))
                    using (var value = new NSString("value"))
                        return(new CGImageMetadataTag(CGImageMetadataTagNamespaces.Exif, CGImageMetadataTagPrefixes.Exif, name, CGImageMetadataType.Default, value));

            case "CGImageSource":
                filename = "xamarin1.png";
                return(CGImageSource.FromUrl(NSUrl.FromFilename(filename)));

            case "SecPolicy":
                return(SecPolicy.CreateSslPolicy(false, null));

            case "SecIdentity":
                using (var options = NSDictionary.FromObjectAndKey(new NSString("farscape"), SecImportExport.Passphrase)) {
                    NSDictionary[] array;
                    var            result = SecImportExport.ImportPkcs12(farscape_pfx, options, out array);
                    if (result != SecStatusCode.Success)
                    {
                        throw new InvalidOperationException(string.Format("Could not create the new instance for type {0} due to {1}.", t.Name, result));
                    }
                    return(new SecIdentity(array [0].LowlevelObjectForKey(SecImportExport.Identity.Handle)));
                }

            case "SecTrust":
                X509Certificate x = new X509Certificate(mail_google_com);
                using (var policy = SecPolicy.CreateSslPolicy(true, "mail.google.com"))
                    return(new SecTrust(x, policy));

            case "SslContext":
                return(new SslContext(SslProtocolSide.Client, SslConnectionType.Stream));

            case "UIFontFeature":
                return(new UIFontFeature(CTFontFeatureNumberSpacing.Selector.ProportionalNumbers));

            case "NetworkReachability":
                return(new NetworkReachability(IPAddress.Loopback, null));

            case "VTCompressionSession":
            case "VTSession":
                return(VTCompressionSession.Create(1024, 768, CMVideoCodecType.H264, (sourceFrame, status, flags, buffer) => { }, null, (CVPixelBufferAttributes)null));

            case "VTFrameSilo":
                return(VTFrameSilo.Create());

            case "VTMultiPassStorage":
                return(VTMultiPassStorage.Create());

            case "CFString":
                return(new CFString("test"));

            case "DispatchBlock":
                return(new DispatchBlock(() => { }));

            case "DispatchQueue":
                return(new DispatchQueue("com.example.subsystem.taskXYZ"));

            case "DispatchGroup":
                return(DispatchGroup.Create());

            case "CGColorSpace":
                return(CGColorSpace.CreateDeviceCmyk());

            case "CGGradient":
                CGColor[] cArray = { UIColor.Black.CGColor, UIColor.Clear.CGColor, UIColor.Blue.CGColor };
                return(new CGGradient(null, cArray));

            case "CGImage":
                filename = "xamarin1.png";
                using (var dp = new CGDataProvider(filename))
                    return(CGImage.FromPNG(dp, null, false, CGColorRenderingIntent.Default));

            case "CGColor":
                return(UIColor.Black.CGColor);

            case "CMClock":
                CMClockError ce;
                CMClock      clock = CMClock.CreateAudioClock(out ce);
                if (ce == CMClockError.None)
                {
                    return(clock);
                }
                throw new InvalidOperationException(string.Format("Could not create the new instance for type {0}.", t.Name));

            case "CMTimebase":
                clock = CMClock.CreateAudioClock(out ce);
                if (ce == CMClockError.None)
                {
                    return(new CMTimebase(clock));
                }
                throw new InvalidOperationException(string.Format("Could not create the new instance for type {0}.", t.Name));

            case "CVPixelBufferPool":
                return(new CVPixelBufferPool(
                           new CVPixelBufferPoolSettings(),
                           new CVPixelBufferAttributes(CVPixelFormatType.CV24RGB, 100, 50)
                           ));

            case "NWAdvertiseDescriptor":
                return(NWAdvertiseDescriptor.CreateBonjourService("sampleName" + DateTime.Now, "_nfs._tcp"));

            case "NWConnection": {
                var endpoint   = NWEndpoint.Create("www.microsoft.com", "https");
                var parameters = NWParameters.CreateTcp(configureTcp: null);
                return(new NWConnection(endpoint, parameters));
            }

            case "NWContentContext":
                return(new NWContentContext("contentContext" + DateTime.Now));

            case "NWEndpoint":
                return(NWEndpoint.Create("www.microsoft.com", "https"));

            case "NWListener":
                return(NWListener.Create(NWParameters.CreateTcp(configureTcp: null)));

            case "NWParameters":
                return(NWParameters.CreateTcp(configureTcp: null));

            case "NWProtocolDefinition":
                // Makes a new instance every time
                return(NWProtocolDefinition.TcpDefinition);

            case "NWProtocolOptions":
                return(NWProtocolOptions.CreateTcp());

            case "SecCertificate":
                using (var cdata = NSData.FromArray(mail_google_com))
                    return(new SecCertificate(cdata));

            case "SecCertificate2":
                using (var cdata = NSData.FromArray(mail_google_com))
                    return(new SecCertificate2(new SecCertificate(cdata)));

            case "SecTrust2":
                X509Certificate x2 = new X509Certificate(mail_google_com);
                using (var policy = SecPolicy.CreateSslPolicy(true, "mail.google.com"))
                    return(new SecTrust2(new SecTrust(x2, policy)));

            case "SecIdentity2":
                using (var options = NSDictionary.FromObjectAndKey(new NSString("farscape"), SecImportExport.Passphrase)) {
                    NSDictionary[] array;
                    var            result = SecImportExport.ImportPkcs12(farscape_pfx, options, out array);
                    if (result != SecStatusCode.Success)
                    {
                        throw new InvalidOperationException(string.Format("Could not create the new instance for type {0} due to {1}.", t.Name, result));
                    }
                    return(new SecIdentity2(new SecIdentity(array [0].LowlevelObjectForKey(SecImportExport.Identity.Handle))));
                }

            case "SecKey":
                SecKey private_key;
                SecKey public_key;
                using (var record = new SecRecord(SecKind.Key)) {
                    record.KeyType       = SecKeyType.RSA;
                    record.KeySizeInBits = 512;                     // it's not a performance test :)
                    SecKey.GenerateKeyPair(record.ToDictionary(), out public_key, out private_key);
                    return(private_key);
                }

            case "SecAccessControl":
                return(new SecAccessControl(SecAccessible.WhenPasscodeSetThisDeviceOnly));

            default:
                throw new InvalidOperationException(string.Format("Could not create the new instance for type {0}.", t.Name));
            }
        }
示例#18
0
    static NWListener CreateAndStartListener(string host, string port)
    {
        Action <NWProtocolOptions> configureTls = SetupTls();
        NWParameters parameters;

        // Create the parameters, either TLS or no TLS, and with UDP or no UDP
        if (useUdp)
        {
            if (useTls)
            {
                parameters = NWParameters.CreateSecureUdp(configureTls: configureTls, configureUdp: null);
            }
            else
            {
                parameters = NWParameters.CreateUdp(configureUdp: null);
            }
        }
        else
        {
            if (useTls)
            {
                parameters = NWParameters.CreateSecureTcp(configureTls: configureTls, configureTcp: null);
            }
            else
            {
                parameters = NWParameters.CreateTcp(configureTcp: null);
            }
        }

        // If specified, set the IP version
        using (NWProtocolStack protocolStack = parameters.ProtocolStack){
            if (ipv4 || ipv6)
            {
                NWProtocolOptions ipOptions = protocolStack.InternetProtocol;
                ipOptions.IPSetVersion(ipv4 ? NWIPVersion.Version4 : NWIPVersion.Version6);
            }
        }

        // Bind to local address and port
        string address = bonjour ? null : host;

        if (address != null || port != null)
        {
            NWEndpoint localEndpoint = NWEndpoint.Create(address != null ? address : "::", port != null ? port : "0");
            Console.WriteLine("Getting {0} and {1}", address != null ? address : "::", port != null ? port : "0");
            parameters.LocalEndpoint = localEndpoint;
            Console.WriteLine("With port: " + localEndpoint.Port);
        }

        var listener = NWListener.Create(parameters);

        if (bonjour && host != null)
        {
            listener.SetAdvertiseDescriptor(NWAdvertiseDescriptor.CreateBonjourService(host, GetServiceType(), "local"));
            listener.SetAdvertisedEndpointChangedHandler((NWEndpoint advertisedEndpoint, bool added) => {
                if (verbose)
                {
                    var astr = added ? "added" : "removed";
                    warn($"Listener {astr} on {advertisedEndpoint.BonjourServiceName} on ({advertisedEndpoint.BonjourServiceName}.{GetServiceType()}.local");
                }
            });
        }

        listener.SetQueue(DispatchQueue.MainQueue);
        listener.SetStateChangedHandler((listenerState, error) => {
            var errno = (SslStatus)(error == null ? 0 : error.ErrorCode);
            switch (listenerState)
            {
            case NWListenerState.Waiting:
                if (verbose)
                {
                    warn($"Listener on port {listener.Port} udp={useUdp} waiting");
                }
                break;

            case NWListenerState.Failed:
                warn($"Listener on port {listener.Port} udp={useUdp} failed");
                break;

            case NWListenerState.Ready:
                if (verbose)
                {
                    warn($"Listener on port {listener.Port} udp={useUdp} ready");
                }
                break;

            case NWListenerState.Cancelled:
                listener = null;
                break;
            }
        });

        listener.SetNewConnectionHandler((connection) => {
            if (inboundConnection != null)
            {
                // We only support one connection at a time, so if we already
                // have one, reject the incoming connection.
                connection.Cancel();
            }
            else
            {
                if (verbose)
                {
                    warn($"New Connection on {connection.Handle} with {connection.Endpoint}");
                }
                // Accept the incoming connection and start sending  and receiving on it
                inboundConnection = connection;
                StartConnection(inboundConnection);
                StartSendReceiveLoop(inboundConnection);
            }
        });
        listener.Start();

        return(listener);
    }
示例#19
0
 public void SetUp()
 {
     TestRuntime.AssertXcodeVersion(13, 0);
     endpoint = NWEndpoint.Create("https://microsoft.com");
 }