示例#1
0
        public void TestNetworkServiceOneWayCommunication()
        {
            int networkServicePort1 = NetworkUtils.GenerateRandomPort(6000, 7000);
            int networkServicePort2 = NetworkUtils.GenerateRandomPort(7001, 8000);

            BlockingCollection <string> queue = new BlockingCollection <string>();

            using (INameServer nameServer = new NameServer(0))
            {
                IPEndPoint endpoint       = nameServer.LocalEndpoint;
                int        nameServerPort = endpoint.Port;
                string     nameServerAddr = endpoint.Address.ToString();
                using (INetworkService <string> networkService1 = BuildNetworkService(networkServicePort1, nameServerPort, nameServerAddr, null))
                    using (INetworkService <string> networkService2 = BuildNetworkService(networkServicePort2, nameServerPort, nameServerAddr, new MessageHandler(queue)))
                    {
                        IIdentifier id1 = new StringIdentifier("service1");
                        IIdentifier id2 = new StringIdentifier("service2");
                        networkService1.Register(id1);
                        networkService2.Register(id2);

                        using (IConnection <string> connection = networkService1.NewConnection(id2))
                        {
                            connection.Open();
                            connection.Write("abc");
                            connection.Write("def");
                            connection.Write("ghi");

                            Assert.AreEqual("abc", queue.Take());
                            Assert.AreEqual("def", queue.Take());
                            Assert.AreEqual("ghi", queue.Take());
                        }
                    }
            }
        }
        public Snapshot Create(IPiosResult piosResult)
        {
            var snapshot = new Snapshot();

            Domain d = _domains.FindOrAdd(piosResult.Domain);

            snapshot.Domain = d != null ? d : piosResult.Domain;

            if (piosResult.IsRegistered)
            {
                Registrar r = _registrars.FindOrAdd(piosResult.Registrar);
                snapshot.Registrar = r != null ? r : piosResult.Registrar;

                foreach (var ns in piosResult.NameServers)
                {
                    NameServer n = _nameServers.FindOrAdd(ns);

                    if (n != null)
                    {
                        snapshot.SnapshotNameServers.Add(new SnapshotNameServer {
                            NameServer = n
                        });
                    }
                    else
                    {
                        snapshot.SnapshotNameServers.Add(new SnapshotNameServer {
                            NameServer = ns
                        });
                    }
                }
            }

            return(snapshot);
        }
示例#3
0
        public IPEndPoint[] GetEndpointsValue()
        {
            if (ServerArg.HasValue())
            {
                var values = ServerArg.Values.Select(p => p.Split('#').ToArray());
                var result = new List <IPEndPoint>();
                foreach (var serverPair in values)
                {
                    var server = serverPair[0];
                    var port   = serverPair.Length > 1 ? int.Parse(serverPair[1]) : 53;

                    IPAddress ip;
                    if (!IPAddress.TryParse(server, out ip))
                    {
                        var lookup  = new LookupClient();
                        var lResult = lookup.QueryAsync(server, QueryType.A).Result;
                        ip = lResult.Answers.OfType <ARecord>().FirstOrDefault()?.Address;
                    }

                    if (ip == null)
                    {
                        throw new ArgumentException($"Invalid address or hostname '{server}'.");
                    }

                    result.Add(new IPEndPoint(ip, port));
                }

                return(result.ToArray());
            }
            else
            {
                return(NameServer.ResolveNameServers().ToArray());
            }
        }
示例#4
0
        static void Main(string[] args)
        {
            IEnumerable <string> readLines = File.ReadLines(args[0]);

            File.AppendAllText($"output.csv",
                               "domain,domain-ttl,ns,ns-ttl,soa,soa-ttl,mx,mx-priority,mx-ttl,txt,txt-ttl,dkim,dkim-ttl,dmarc,dmarc-ttl\n");

            foreach (string host in readLines)
            {
                Console.WriteLine("Processing " + host);
                // string resolver = "103.245.91.248";
                // string resolver = "8.8.8.8";
                // string soa = DigThis("A", host, resolver);
                // string mxs = DigThis("MX", host, resolver);
                // string nss = DigThis("NS", host, resolver);
                // string txts = DigThis("TXT", host, resolver);


                client          = new LookupClient(nameServer);
                client.UseCache = false;
                IDnsQueryResponse nsResponse = client.Query(host, QueryType.NS);

                string result = "";
                try
                {
                    IDnsQueryResponse nsAResponse =
                        client.Query((nsResponse.Answers[0] as NsRecord)?.NSDName, QueryType.A);
                    NameServer ns = new NameServer((nsAResponse.Answers[0] as ARecord)?.Address);

                    client          = new LookupClient(ns);
                    client.UseCache = false;
                    IDnsQueryResponse aResponse   = client.Query(host, QueryType.A);
                    IDnsQueryResponse mxResponse  = client.Query(host, QueryType.MX);
                    IDnsQueryResponse soaResponse = client.Query(host, QueryType.SOA);
                    IDnsQueryResponse txtResponse = client.Query(host, QueryType.TXT);

                    //
                    IDnsQueryResponse ucResponse = client.Query("uckey._domainkey." + host, QueryType.TXT);
                    IDnsQueryResponse dmResponse = client.Query("_dmarc." + host, QueryType.TXT);

                    //
                    string doa  = ParseRecord(aResponse, isA: true);
                    string soa  = ParseRecord(soaResponse);
                    string mxs  = ParseRecord(mxResponse, isMx: true);
                    string nss  = ParseRecord(nsResponse);
                    string txts = ParseRecord(txtResponse);
                    string ucs  = ParseRecord(ucResponse);
                    string dmr  = ParseRecord(dmResponse);

                    // string result = $"{host} | {soa}NS\n{nss}MX\n{mxs}TXT\n{txts}\n";
                    result = $"{host},{doa},{nss},{soa},{mxs},{txts},{ucs},{dmr}\n";
                }
                catch (Exception e)
                {
                    result = $"{host},No record,No record,No record,No record,No record,No record,No record,No record,No record,No record,No record,No record\n";
                }

                File.AppendAllText($"output.csv", result);
            }
        }
        public void TestConnection()
        {
            var signallingCloudPort = 20000;
            var signallingCloud     = new SignallingCloud(signallingCloudPort);
            var nameServer          = new NameServer("127.0.0.1", signallingCloudPort);

            var sspcs1Address = new NetworkAddress("1");
            var sspcs2Address = new NetworkAddress("2");
            var hpcs1Address  = new NetworkAddress("1.1");
            var hpcs2Address  = new NetworkAddress("1.2");

            var sspcs1 = new StepByStepPathComputationServer(sspcs1Address, "127.0.0.1", signallingCloudPort);

            sspcs1.UpdateState += OnUpdateState;

            var sspcs2 = new StepByStepPathComputationServer(sspcs2Address, "127.0.0.1", signallingCloudPort);

            sspcs2.UpdateState += OnUpdateState;

            sspcs1.Initialize();
            sspcs2.Initialize();

            var hpcs1 = new HierarchicalPathComputationServer(hpcs1Address, "127.0.0.1", signallingCloudPort);

            hpcs1.UpdateState += OnUpdateState;

            var hpcs2 = new HierarchicalPathComputationServer(hpcs2Address, "127.0.0.1", signallingCloudPort);

            hpcs2.UpdateState += OnUpdateState;

            hpcs1.Initialize();
            hpcs2.Initialize();

            Thread.Sleep(5000);
        }
示例#6
0
 protected virtual void OnNextAuthorities(NameServer ns, NameServerCollection authorities)
 {
     foreach (IGrouping <int, NameServer> nsg in authorities.Groupings)
     {
         LogMessageCreate(Logging.LogMessageText.RESPONSE.INFO.NextAuthoritiesReceived(
                              ns.Name, nsg.First().Zone, authorities));
     }
 }
示例#7
0
 public void TestNameServerMultipleRequestsTwoClients()
 {
     using (var server = new NameServer(0))
     {
         var nameClient  = new NameClient(server.LocalEndpoint);
         var nameClient2 = new NameClient(server.LocalEndpoint);
         nameClient.Register("1", new IPEndPoint(IPAddress.Any, 8080));
         nameClient2.Lookup("1");
     }
 }
示例#8
0
        static STUNDns()
        {
            var nameServers = NameServer.ResolveNameServers(skipIPv6SiteLocal: true, fallbackToGooglePublicDns: true);
            LookupClientOptions clientOptions = new LookupClientOptions(nameServers.ToArray())
            {
                Retries        = DNS_RETRIES_PER_SERVER,
                Timeout        = TimeSpan.FromSeconds(DNS_TIMEOUT_SECONDS),
                UseCache       = true,
                UseTcpFallback = false
            };

            _lookupClient = new LookupClient(clientOptions);
        }
        public void ToString_should_return_XX()
        {
            // arrange.
            const string ipAddress     = "10.1.1.10";
            const int    port          = 53;
            string       toStringValue = $"{ipAddress}:{port} (Udp: 512)";

            // Act.
            NameServer ns = new NameServer(IPAddress.Parse(ipAddress));

            // Assert.
            Assert.AreEqual(toStringValue, ns.ToString());
        }
示例#10
0
        /// <summary>
        ///   Creates a new instance of the <see cref="UdpDnsServer"/> with
        ///   the specified DNS master file.
        /// </summary>
        /// <param name="zone">
        ///   The path to the DNS master file.
        /// </param>
        public UdpDnsServer(string zone)
        {
            var catalog = new Catalog();

            using (var reader = new StreamReader(zone))
            {
                catalog.Include(new PresentationReader(reader), authoritative: true);
            }

            Resolver = new NameServer {
                Catalog = catalog
            };
        }
示例#11
0
        static SIPDns()
        {
            var nameServers = NameServer.ResolveNameServers(skipIPv6SiteLocal: true, fallbackToGooglePublicDns: true);
            LookupClientOptions clientOptions = new LookupClientOptions(nameServers.ToArray())
            {
                Retries                    = DNS_RETRIES_PER_SERVER,
                Timeout                    = TimeSpan.FromSeconds(DNS_TIMEOUT_SECONDS),
                UseCache                   = true,
                CacheFailedResults         = true,
                FailedResultsCacheDuration = TimeSpan.FromSeconds(CACHE_FAILED_RESULTS_DURATION)
            };

            _lookupClient = new LookupClient(clientOptions);
        }
示例#12
0
        static SIPDns()
        {
            var nameServers = NameServer.ResolveNameServers(skipIPv6SiteLocal: true, fallbackToGooglePublicDns: true);
            LookupClientOptions clientOptions = new LookupClientOptions(nameServers.ToArray())
            {
                Retries  = DNS_RETRIES_PER_SERVER,
                Timeout  = TimeSpan.FromSeconds(DNS_TIMEOUT_SECONDS),
                UseCache = true,
                // TODO: Re-enable when DnsClient adds cache querying.
                //UseCacheForFailures = true,
            };

            _lookupClient = new LookupClient(clientOptions);
        }
        public void Implicit_should_be_able_to_return_a_non_null_NameServer_object_when_newedup_using_IPAddress()
        {
            // Arrange.
            const string ipAddressString = "10.1.1.10";
            const int    port            = 53;

            // Act.
            NameServer tempServer = IPAddress.Parse(ipAddressString);

            // Assert.

            Assert.IsNotNull(tempServer);
            Assert.AreEqual(ipAddressString, tempServer.IPEndPoint.Address.ToString());
            Assert.AreEqual(port, tempServer.Port);
        }
        public void Equals_should_return_true(NameServer ns2, bool expectedResult)
        {
            // Arrange.
            const string ipAddress = "10.1.1.10";
            const int    port      = 53;

            NameServer ns = new NameServer(IPAddress.Parse(ipAddress));

            // Act.

            bool result = ns.Equals(ns2);

            // Assert.

            Assert.AreEqual(expectedResult, result);
        }
示例#15
0
        public async Task ResolveService_WithCnameRef()
        {
            var    ns          = new NameServer(IPAddress.Loopback, 8600);
            var    serviceName = "myservice";
            var    baseName    = "service.consul";
            var    fullQuery   = $"{serviceName}.{baseName}";
            ushort prio        = 99;
            ushort weight      = 69;
            ushort port        = 88;

            var response = new DnsResponseMessage(new DnsResponseHeader(1234, (int)DnsResponseCode.NoError, 0, 0, 0, 0), 0);

            response.AddAnswer(
                new SrvRecord(
                    new ResourceRecordInfo(fullQuery, ResourceRecordType.SRV, QueryClass.IN, 1000, 0),
                    prio,
                    weight,
                    port,
                    DnsString.Parse(serviceName)));

            var targetHost = DnsString.Parse("myservice.localhost.net");

            response.AddAdditional(
                new CNameRecord(
                    new ResourceRecordInfo(serviceName, ResourceRecordType.CNAME, QueryClass.IN, 1000, 0),
                    targetHost));

            var client = new LookupClient(ns);

            var mock = new Mock <IDnsQuery>();

            mock.Setup(p => p.QueryAsync(It.IsAny <string>(), It.IsAny <QueryType>(), It.IsAny <QueryClass>(), It.IsAny <CancellationToken>()))
            .Returns(() => Task.FromResult <IDnsQueryResponse>(response.AsQueryResponse(ns, client.Settings)));

            var mockClient = mock.Object;

            var result = await mockClient.ResolveServiceAsync(baseName, serviceName);

            Assert.Single(result);
            var first = result.First();

            Assert.Equal(targetHost.ToString(), first.HostName);
            Assert.Equal((int)port, first.Port);
            Assert.Equal((int)prio, first.Priority);
            Assert.Equal((int)weight, first.Weight);
        }
示例#16
0
        public void TestConstructorInjection()
        {
            int port = 6666;

            using (INameServer server = new NameServer(port))
            {
                IConfiguration nameClientConfiguration = NamingConfiguration.ConfigurationModule
                                                         .Set(NamingConfiguration.NameServerAddress, server.LocalEndpoint.Address.ToString())
                                                         .Set(NamingConfiguration.NameServerPort, port + string.Empty)
                                                         .Build();

                ConstructorInjection c = TangFactory.GetTang()
                                         .NewInjector(nameClientConfiguration)
                                         .GetInstance <ConstructorInjection>();

                Assert.IsNotNull(c);
            }
        }
示例#17
0
        public void Lookup_Query_SettingsCannotBeNull()
        {
            IDnsQuery client   = new LookupClient(NameServer.GooglePublicDns);
            var       question = new DnsQuestion("query", QueryType.A);
            var       servers  = new NameServer[] { NameServer.GooglePublicDns };

            Assert.Throws <ArgumentNullException>("queryOptions", () => client.Query(question, null));
            Assert.ThrowsAsync <ArgumentNullException>("queryOptions", () => client.QueryAsync(question, null));

            Assert.Throws <ArgumentNullException>("queryOptions", () => client.QueryServer(servers, question, null));
            Assert.ThrowsAsync <ArgumentNullException>("queryOptions", () => client.QueryServerAsync(servers, question, null));

            Assert.Throws <ArgumentNullException>("queryOptions", () => client.QueryReverse(IPAddress.Loopback, null));
            Assert.ThrowsAsync <ArgumentNullException>("queryOptions", () => client.QueryReverseAsync(IPAddress.Loopback, null));

            Assert.Throws <ArgumentNullException>("queryOptions", () => client.QueryServerReverse(servers, IPAddress.Loopback, null));
            Assert.ThrowsAsync <ArgumentNullException>("queryOptions", () => client.QueryServerReverseAsync(servers, IPAddress.Loopback, null));
        }
示例#18
0
        public bool MoveNext(NameServer selected = null)
        {
            // Verify the selected name server occurs within the NextAuthorities in the previous result.
            if (!object.ReferenceEquals(null, selected))
            {
                DnsDomain selectedName = selected.Name;
                try
                {
                    // Throws if either NullReferenceException or InvalidOperationException on failure.
                    selected = CurrentResult.NextAuthorities.First(n => n.Name.Equals(selectedName));
                }
                catch (Exception ex)
                {
                    throw new ArgumentException(String.Format(
                                                    "The selected name server was not taken from the NextAuthorities in the precious result: {0}",
                                                    selectedName.ToString()), "selected", ex);
                }
            }

            if (IsCompleted)
            {
                return(false);
            }

            // Apply loop control.
            if (_Resolver.Options.IterationLoopControl > 0)
            {
                if (_IterationCount >= Resolver.Options.IterationLoopControl)
                {
                    throw new ResolverException("Maximum number of iterations has been reached.");
                }
            }

            // next
            try
            {
                CurrentResult = GetNextResult(out IsCompleted, selected);
            }
            finally
            {
                _IterationCount++;
            }
            return(true);
        }
示例#19
0
        public static void Main(string[] args)
        {
            if (args.Length > 2 || args.Length == 0 || args[0] == "-h" || args[0] == "/?" || args[0] == "/h" || args[0] == "--help")
            {
                Console.WriteLine("WinBinReplacements: nslookup.exe <hostname> [dns_server]");
                return;
            }
            LookupClient      client = new LookupClient();
            IDnsQueryResponse result = null;
            NameServer        ns     = null;

            if (args.Length == 2)
            {
                try
                {
                    ns     = new NameServer(IPAddress.Parse(args[1]));
                    client = new LookupClient(ns);
                }
                catch
                {
                    Console.WriteLine("[!] Error: nameserver is not an IP address: " + args[1]);
                    return;
                }
            }
            try
            {
                result = client.Query(args[0], QueryType.A);
            }
            catch (DnsResponseException)
            {
                Console.WriteLine("[!] Error: DNS server could not be contacted");
                return;
            }

            foreach (var answer in result.Answers)
            {
                Console.WriteLine(answer);
            }
            if (result.Answers.Count == 0)
            {
                Console.WriteLine("[!] Error: no matching records found for " + args[0]);
            }
        }
示例#20
0
        private List <IPEndPoint> GetDnsServer()
        {
            List <IPEndPoint> dnsServers = new List <IPEndPoint>();

            if (UseCustomDNSServer)
            {
                foreach (var dnsServer in CustomDNSServer.Servers)
                {
                    dnsServers.Add(new IPEndPoint(IPAddress.Parse(dnsServer), CustomDNSServer.Port));
                }
            }
            else
            {
                foreach (var dnsServer in NameServer.ResolveNameServers(true, false))
                {
                    dnsServers.Add(dnsServer);
                }
            }

            return(dnsServers);
        }
示例#21
0
        public void TestNameClientRestart()
        {
            int         oldPort = 6666;
            int         newPort = 6662;
            INameServer server  = new NameServer(oldPort);

            using (INameClient client = BuildNameClient(server.LocalEndpoint))
            {
                IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse("100.0.0.1"), 100);

                client.Register("a", endpoint);
                Assert.AreEqual(endpoint, client.Lookup("a"));

                server.Dispose();

                server = new NameServer(newPort);
                client.Restart(server.LocalEndpoint);

                client.Register("b", endpoint);
                Assert.AreEqual(endpoint, client.Lookup("b"));

                server.Dispose();
            }
        }
 public NamingUnregisterRequestObserver(NameServer server)
 {
     _server = server;
 }
示例#23
0
文件: Program.cs 项目: stachupl/MNFS
        static void Main(string[] args)
        {
            string[]    command;
            string[]    incorrectChar = { " ", "" };
            HttpChannel c             = new HttpChannel();

            ChannelServices.RegisterChannel(c, true);
            Type   ServerType = typeof(nameServerClass.NameServer);
            string url        = "http://localhost:3300/Object";

            RemotingConfiguration.RegisterWellKnownClientType(ServerType, url);
            nameServer = new NameServer();

            while (true)
            {
                Console.Write(path + " ");
                command = Console.ReadLine().Split(' ').Except(incorrectChar).ToArray();

                if (command.Count() == 0)
                {
                    continue;
                }

                switch (command[0])
                {
                case "ls":
                    if (command.Count() == 1)
                    {
                        ls(path);
                    }
                    else
                    {
                        ls(makeAbsolutePath(command[1]));
                    }
                    break;

                case "mkdir":
                    if (command.Count() > 1)
                    {
                        mkdir(makeAbsolutePath(command[1]));
                    }
                    else
                    {
                        Console.WriteLine("Wrong number of parameter!");
                    }
                    break;

                case "rename":
                    if (command.Count() >= 3)
                    {
                        rename(makeAbsolutePath(command[1]), command[2]);
                    }
                    else
                    {
                        Console.WriteLine("Wrong number of parameter!");
                    }
                    break;

                case "renamedir":
                    if (command.Count() >= 3)
                    {
                        renamedir(makeAbsolutePath(command[1]), command[2]);
                    }
                    else
                    {
                        Console.WriteLine("Wrong number of parameter!");
                    }
                    break;

                case "rmdir":
                    if (command.Count() >= 2)
                    {
                        rmdir(makeAbsolutePath(command[1]));
                    }
                    else
                    {
                        Console.WriteLine("Wrong number of parameter!");
                    }
                    break;

                case "mv":
                    if (command.Count() >= 3)
                    {
                        mv(makeAbsolutePath(command[1]), makeAbsolutePath(command[2]));
                    }
                    else
                    {
                        Console.WriteLine("Wrong number of parameter!");
                    }
                    break;

                case "find":
                    if (command.Count() >= 3)
                    {
                        find(makeAbsolutePath(command[1]), makeAbsolutePath(command[2]));
                    }
                    else
                    {
                        Console.WriteLine("Wrong number of parameter!");
                    }
                    break;

                case "finddir":
                    if (command.Count() >= 3)
                    {
                        finddir(makeAbsolutePath(command[1]), command[2]);
                    }
                    else
                    {
                        Console.WriteLine("Wrong number of parameter!");
                    }
                    break;

                case "rm":
                    if (command.Count() >= 2)
                    {
                        rm(makeAbsolutePath(command[1]));
                    }
                    else
                    {
                        Console.WriteLine("Wrong number of parameter!");
                    }
                    break;

                case "touch":
                    if (command.Count() >= 2)
                    {
                        touch(makeAbsolutePath(command[1]));
                    }
                    else
                    {
                        Console.WriteLine("Wrong number of parameter!");
                    }
                    break;

                case "read":
                    if (command.Count() >= 4)
                    {
                        read(makeAbsolutePath(command[1]), command[2], command[3]);
                    }
                    else
                    {
                        Console.WriteLine("Wrong number of parameter!");
                    }
                    break;
                }
            }
        }
示例#24
0
 public static LogMessage ResolvingNameServer(NameServer unresolved)
 {
     return Create(Resources.LogMessages.ResolvingNameServer, new object[] { unresolved.Name });
 }
示例#25
0
        protected override Results.ResolutionResult GetNextResult(out bool isCompleted, NameServer selected)
        {
            Results.ResolutionResult result = base.GetNextResult(out isCompleted, selected);
            if (isCompleted)
            {
                IEnumerable <DnsClient.DNS.RR> rrset = null;
                switch (result.QueryState)
                {
                case QueryState.AuthoritativeAnswer:
                    rrset = result.Response.AnswerRecords;
                    break;

                case QueryState.NonAuthoritativeAnswer:
                    rrset = result.Response.AdditionalRecords;
                    break;
                }
                if (!object.ReferenceEquals(null, rrset))
                {
                    this.Addresses = rrset.Select <DnsClient.DNS.Records.Address>().Where(
                        a => this.Resolver.Domain.Equals(a.Base.NAME));
                }
            }
            return(result);
        }
示例#26
0
        public void CreateBasicNetworkTest()
        {
            var localhost = "127.0.0.1";
            var maxAtmCellsInCableCloudMessage = 100;

            var portA = 1;
            var port1 = 2;
            var port2 = 3;
            var port3 = 4;
            var port4 = 5;
            var portB = 6;

            var cableCloud = new CableCloud(10000);

            cableCloud.UpdateState += (sender, state) => Console.WriteLine("CC: " + state);
            cableCloud.StartListening();

            var signallingCloud = new SignallingCloud(20000);

            signallingCloud.UpdateState += (sender, state) => Console.WriteLine("SC: " + state);
            signallingCloud.StartListening();

            var nms = new NetworkManagementSystem(6666);

            nms.UpdateState += (sender, state) => Console.WriteLine("NMS:" + state);
            nms.StartListening();

            Thread.Sleep(1000);

            var nameServer = new NameServer(localhost, 20000);

            nameServer.UpdateState += (sender, state) => Console.WriteLine("NS " + state);
            nameServer.Initialize();

            var sspcs1 = new StepByStepPathComputationServer(
                new NetworkAddress(1),
                localhost,
                20000
                );

            sspcs1.UpdateState += (sender, state) => Console.WriteLine("SSPCS1: " + state);
            sspcs1.Initialize();

            var sspcs2 = new StepByStepPathComputationServer(
                new NetworkAddress(2),
                localhost,
                20000
                );

            sspcs2.UpdateState += (sender, state) => Console.WriteLine("SSPCS2: " + state);
            sspcs2.Initialize();

            var clientNodeA = new ClientNode(new ClientNodeModel {
                NetworkAddress = new NetworkAddress("1.1"),
                MaxAtmCellsNumberInCableCloudMessage = maxAtmCellsInCableCloudMessage,
                ClientName = "A",
                CableCloudListeningPort      = 10000,
                SignallingCloudListeningPort = 20000,
                IpAddress = localhost
            });

            //clientNodeA.OnMessageReceived += (sender, state) => Console.WriteLine(state);
            clientNodeA.UpdateState += (sender, state) => Console.WriteLine("ClientNode A: " + state);
            clientNodeA.Initialize();
            nameServer.UpdateDirectory("A", clientNodeA.NetworkAddress, new SubnetworkPointPool(clientNodeA.NetworkAddress.Append(1)));

            var clientNodeB = new ClientNode(new ClientNodeModel {
                NetworkAddress = new NetworkAddress("2.2"),
                MaxAtmCellsNumberInCableCloudMessage = maxAtmCellsInCableCloudMessage,
                ClientName = "B",
                CableCloudListeningPort      = 10000,
                SignallingCloudListeningPort = 20000,
                IpAddress = localhost
            });

            //clientNodeB.OnMessageReceived += (sender, state) => Console.WriteLine(state);
            clientNodeB.UpdateState += (sender, state) => Console.WriteLine("ClientNode B: " + state);
            clientNodeB.Initialize();
            nameServer.UpdateDirectory("B", clientNodeB.NetworkAddress, new SubnetworkPointPool(clientNodeB.NetworkAddress.Append(1)));

            var networkNode1 = new NetworkNode(new NetworkNodeModel {
                NetworkAddress = new NetworkAddress("1.2"),
                MaxAtmCellsNumberInCableCloudMessage = maxAtmCellsInCableCloudMessage,
                NumberOfPorts           = 8,
                CableCloudListeningPort = 10000,
                IpAddress = localhost,
                NetworkManagmentSystemListeningPort = 6666,
                SignallingCloudListeningPort        = 20000
            });

            networkNode1.UpdateState += (sender, state) => Console.WriteLine("NetworkNode 1.2: " + state);
            networkNode1.Initialize();

            var networkNode2 = new NetworkNode(new NetworkNodeModel {
                NetworkAddress = new NetworkAddress("2.1"),
                MaxAtmCellsNumberInCableCloudMessage = maxAtmCellsInCableCloudMessage,
                NumberOfPorts           = 8,
                CableCloudListeningPort = 10000,
                IpAddress = localhost,
                NetworkManagmentSystemListeningPort = 6666,
                SignallingCloudListeningPort        = 20000
            });

            networkNode2.UpdateState += (sender, state) => Console.WriteLine("NetworkNode 2.1: " + state);
            networkNode2.Initialize();

            Thread.Sleep(1000);

            var socketNodePortPair1 = new NetworkAddressNodePortPair(clientNodeA.NetworkAddress, portA);
            var socketNodePortPair2 = new NetworkAddressNodePortPair(networkNode1.NetworkAddress, port1);
            var socketNodePortPair3 = new NetworkAddressNodePortPair(networkNode1.NetworkAddress, port2);
            var socketNodePortPair4 = new NetworkAddressNodePortPair(networkNode2.NetworkAddress, port3);
            var socketNodePortPair5 = new NetworkAddressNodePortPair(networkNode2.NetworkAddress, port4);
            var socketNodePortPair6 = new NetworkAddressNodePortPair(clientNodeB.NetworkAddress, portB);

            cableCloud.AddLink(socketNodePortPair1, socketNodePortPair2);
            cableCloud.AddLink(socketNodePortPair3, socketNodePortPair4);
            cableCloud.AddLink(socketNodePortPair5, socketNodePortPair6);

            Thread.Sleep(1000);

            //var sb = new StringBuilder();

            //for (var i = 0; i < 5000; i++) sb.Append("0123456789");

            clientNodeA.Connect("B", 10);

            //Thread.Sleep(1000);

            //clientNodeA.SendMessage("Message", "B");

            Thread.Sleep(1000);
        }
示例#27
0
 public void ValidateAnyAddressIPv6()
 {
     Assert.ThrowsAny <InvalidOperationException>(() => NameServer.ValidateNameServers(new[] { new NameServer(IPAddress.IPv6Any) }));
 }
示例#28
0
 public static LogMessage NameServerResolved(NameServer resolved, DnsDomain domain)
 {
     return Create(Resources.LogMessages.NameServerResolved, new object[] { resolved.Name, domain });
 }
示例#29
0
        protected override Results.ResolutionResult GetNextResult(out bool isCompleted, NameServer selected)
        {
            Results.ResolutionResult result = base.GetNextResult(out isCompleted, selected);
              if (isCompleted)
              {

            IEnumerable<DnsClient.DNS.RR> rrset = null;
            switch (result.QueryState)
            {
              case QueryState.AuthoritativeAnswer:
            rrset = result.Response.AnswerRecords;
            break;

              case QueryState.NonAuthoritativeAnswer:
            rrset = result.Response.AdditionalRecords;
            break;
            }
            if (!object.ReferenceEquals(null, rrset))
            {
              this.Addresses = rrset.Select<DnsClient.DNS.Records.Address>().Where(
            a => this.Resolver.Domain.Equals(a.Base.NAME));
            }

              }
              return result;
        }
示例#30
0
        protected override Results.ResolutionResult GetNextResult(out bool isCompleted, NameServer selected)
        {
            // Iteration may be delegated to CNameIterator if the requested name
              // has been identified as alias.
              if (!object.ReferenceEquals(null, CNameIterator))
              {
            CNameIterator.EnsureConnection(Resolver.Client);
            return CNameIterator.GetNextResult(out isCompleted, selected);
              }

              // A subsequent iteration may be running if a name server address needs to be resolved.
              if (!object.ReferenceEquals(null, AddressIterator))
              {
            AddressIterator.EnsureConnection(Resolver.Client);

            bool isAddressIteratorCompleted;
            Results.ResolutionResult addressResult = AddressIterator.GetNextResult(out isAddressIteratorCompleted, selected);
            if (isAddressIteratorCompleted)
            {
              // remember the last result from the subsequent iteration
              ResolvedAddresses = AddressIterator.GetAddresses(addressResult).ToArray();
              if (!ResolvedAddresses.Any())
              {
            // Failed to resolve
            isCompleted = true;
              }

              LastAddressResult = addressResult;

              AddressIterator.Dispose();
              AddressIterator = null;
            }
            isCompleted = false;
            return addressResult;
              }

              // Apply address result from previous step.
              if (!object.ReferenceEquals(null, LastAddressResult))
              {
            // An address iteration has been completed in the previous step.
            try
            {
              // Apply the resulting address records to the selected authority.
              IEnumerable<DnsClient.DNS.Records.Address> addresses;
              if (LastAddressResult.Response.Header.AA)
              {
            // fetch addresses from authoritative respone
            addresses = LastAddressResult.Response.AnswerRecords.OfType<
              DnsClient.DNS.Records.Address>().Where(a => StoredAuthorities.Selected.Name.Equals(a.Base.NAME));
              }
              else
              {
            // fetch address from additional records
            addresses = LastAddressResult.Response.AdditionalRecords.OfType<
              DnsClient.DNS.Records.Address>().Where(a => StoredAuthorities.Selected.Name.Equals(a.Base.NAME));
              }
              if (addresses.Any())
              {
            StoredAuthorities.Selected.ApplyAddresses(addresses);
            OnNameServerResolved(StoredAuthorities.Selected);
              }
            }
            finally
            {
              LastAddressResult = null;
            }
              }

              else
              {
            // The standard case
            // Ensure StoredAuthorities with a resolved selected name server.

            if (object.ReferenceEquals(null, StoredAuthorities)) // initial state
            {
              StoredAuthorities = GetStartAuthorities();
              OnResolutionStart(StoredAuthorities);
            }
            else
            {
              OnResolutionContinue(StoredAuthorities);
            }

            // apply cached address records to the set of authorities
            StoredAuthorities.ApplyCache(AddressCache);

            // Select randomly any name server unless one was explicitly chosen.
            if (!object.ReferenceEquals(null, selected))
            {
              StoredAuthorities.SelectOne(selected);
            }
            else
            {
              selected = StoredAuthorities.SelectAny();
            }
            OnAuthoritySelected(StoredAuthorities);

            if (!selected.IsResolved)
            {
              // start a subsequent iteration to resolve the selected name server
              OnNameServerResolution(selected);
              AddressIterator = CreateAddressIterator(selected.Name);

              return GetNextResult(out isCompleted, null);
            }
              }

              // Perform the actual name server request.
              Results.ResolutionResult result = Request(StoredAuthorities, out isCompleted);

              try // Internal.QueryException
              {
            Internal.QueryProcessor query = new Internal.QueryProcessor(Resolver.Domain, Question, result.Response);
            Internal.QueryResult qr = query.Process();
            result.QueryState = qr.State;
            switch (qr.State)
            {

              case QueryState.NextAuthorities:
            //StoredAuthorities = GetResultAuthorities(result);
            isCompleted = false;
            OnNextAuthorities(StoredAuthorities.Selected, qr.NextAuthorities);

            StoredAuthorities = qr.NextAuthorities;
            result.NextAuthorities = StoredAuthorities;

            // "Received {1} '{0}' authorities from '{2}'."
            //LogMessageCreate(Logging.LogMessageText.RESPONSE.INFO.NextAuthoritiesReceived(  StoredAuthorities.Selected, result.NextAuthorities));
            break;

              case QueryState.FollowCName:
            // CNAME found.
            isCompleted = true;
            OnCNameFound(qr.CanonicalName);

            // Follow, if it's configured.
            if (Resolver.Options.FollowCanonical)
            {
              // Start a new iteration with the canonical name and the same question.
              // Name servers may or may not be given.
              CNameIterator = CreateCNameIterator(qr.CanonicalName, qr.NextAuthorities);
              isCompleted = false;
            }
            break;

              case QueryState.NonAuthoritativeAnswer:
            isCompleted = true;
            OnResolutionSucceeded(result.Response, qr.Answers);
            break;

              case QueryState.AuthoritativeAnswer:
            // At least one record of the requested type was found.
            isCompleted = true;
            OnResolutionSucceeded(result.Response, qr.Answers);
            break;

              case QueryState.NxDomain:
            isCompleted = true;
            LogMessageCreate(Logging.LogMessageText.RESPONSE.ERROR.NameNotExisting(qr.CanonicalName ?? Resolver.Domain));
            break;

              case QueryState.NoData:
              case QueryState.EmptyResponse:
            isCompleted = true;
            LogMessageCreate(Logging.LogMessageText.RESPONSE.ERROR.NegativeResponse(qr.State));
            break;

              case QueryState.UnexpectedRCode:
            isCompleted = true;
            OnRCodeNonZero(result.Response);
            break;

            }
              }
              catch (Internal.QueryException ex)
              {
            isCompleted = true;
            result.QueryState = ex.State;
            LogMessageCreate(Logging.LogMessageText.RESPONSE.ERROR.ResponseInvalid(ex.State));
              }

              return result;

              // =====================================================================

              #region hidden
              //// Dealing with non-Zero RCODE.
              //if (isCompleted && result.Response.Header.RCODE != DnsClient.DNS.RCODE.NoError)
              //{
              //  OnRCodeNonZero(result.Response);
              //  return result;
              //}

              //// cache response address records
              //AddressCache.Set(result.Response.AnswerRecords.OfType<DnsClient.DNS.Records.Address>());
              //if (!Resolver.Options.StrictAuhtoritative) // optionally cache also additional address records
              //{
              //  AddressCache.Set(result.Response.AdditionalRecords.Select<DnsClient.DNS.Records.Address>());
              //}

              //if (result.Response.Header.TC)
              //{
              //  // If the result was truncated, the request can be repeated once.
              //  if (Resolver.Options.RepeatTruncated && !TCRepeating)
              //  {
              //    TCRepeating = true;
              //    isCompleted = false;
              //    OnRepeatTruncated();
              //    return result;
              //  }
              //}
              //TCRepeating = false;

              //if (isCompleted)
              //{
              //  // There was an authoritative response.

              //  DnsClient.DNS.Records.SOA soa = result.Response.AnswerRecords.OfType<DnsClient.DNS.Records.SOA>().FirstOrDefault();

              //  // answer records matching the question
              //  IEnumerable<DnsClient.DNS.RR> requested = result.Response.AnswerRecords;
              //  if (Question != DnsClient.DNS.QTYPE.ANY)
              //  {
              //    // A particular record type has been queried (not ANY).
              //    requested = requested.OfQuestion(Question);
              //  }

              //  if (requested.Any())
              //  {
              //    // At least one record of the requested type was found.
              //    OnResolutionSucceeded(result.Response, requested);
              //  }

              //  // check for CNAME
              //  //
              //  // [RFC 1034], 5.2.2. Aliases
              //  //
              //  // In most cases a resolver simply restarts the query at the new name when
              //  // it encounters a CNAME.  However, when performing the general function,
              //  // the resolver should not pursue aliases when the CNAME RR matches the
              //  // query type.  This allows queries which ask whether an alias is present.
              //  // For example, if the query type is CNAME, the user is interested in the
              //  // CNAME RR itself, and not the RRs at the name it points to.
              //  DnsClient.DNS.Records.CNAME cname;
              //  if (!object.ReferenceEquals(null, (
              //    cname = result.Response.AnswerRecords.FirstOrDefault<DnsClient.DNS.Records.CNAME>())))
              //  {
              //    // CNAME found.
              //    //OnCNameFound(cname);

              //    if (Question != DnsClient.DNS.QTYPE.CNAME)
              //    {
              //      // A CNAME can lead to the zone itself.
              //      if (!object.ReferenceEquals(null, soa) &&
              //        DnsDomain.Equals(soa.Base.NAME, cname.CANONICAL))
              //      {

              //        // TODO

              //      }

              //    }

              //    // Follow, if it's configured and the question was not CNAME.
              //    if (!Question.Equals(DnsClient.DNS.QTYPE.CNAME) &&
              //      Resolver.Options.FollowCanonical)
              //    {
              //      // Start a new iteration with the canonical name and the same question.
              //      CNameIterator = CreateCNameIterator((DnsDomain)cname.CANONICAL);
              //      isCompleted = false;
              //    }
              //  }

              //  else
              //  {
              //    // no matching CNAME found
              //    if (!requested.Any())
              //    {
              //      // Neither an appropriate CNAME nor the requested RR type was found.
              //      OnMissingRecords(result.Response);
              //    }
              //  }

              //  if (NestingLevel == 0)
              //  {
              //    // "Resolution finished."
              //    LogMessageCreate(Logging.LogMessageText.RESPONSE.INFO.ResolutionFinished(IterationCount));
              //  }

              //}

              //else
              //{
              //  // The iteration is not yet completed: get authorities for the next step.
              //  StoredAuthorities = GetResultAuthorities(result);
              //  result.NextAuthorities = StoredAuthorities;
              //  if (StoredAuthorities.IsEmpty)
              //    throw new ResolverException(
              //      "No authority name servers were found although the respone is non-authoritative.");

              //  // "Received {1} '{0}' authorities from '{2}'."
              //  LogMessageCreate(Logging.LogMessageText.RESPONSE.INFO.NextAuthoritiesReceived(result.Authorities.Selected, result.NextAuthorities));
              //}

              //return result;
              #endregion
        }
示例#31
0
 protected virtual void OnNameServerResolved(NameServer ns)
 {
     // "Name server '{0}' has been resolved, continuing with '{1}'."
     LogMessageCreate(Logging.LogMessageText.REQUEST.INFO.NameServerResolved(ns, Resolver.Domain));
 }
示例#32
0
 protected virtual void OnNameServerResolution(NameServer ns)
 {
     // "Name server '{0}' needs to be resolved first."
     LogMessageCreate(Logging.LogMessageText.REQUEST.INFO.ResolvingNameServer(ns));
 }
示例#33
0
 protected virtual void OnNameServerResolution(NameServer ns)
 {
     // "Name server '{0}' needs to be resolved first."
       LogMessageCreate(Logging.LogMessageText.REQUEST.INFO.ResolvingNameServer(ns));
 }
示例#34
0
        public void NativeDnsServerResolution()
        {
            var ex = Record.Exception(() => NameServer.ResolveNameServersNative());

            Assert.Null(ex);
        }
示例#35
0
 public NamingGetAllRequestObserver(NameServer server)
 {
     _server = server;
 }
示例#36
0
 protected virtual void OnNameServerResolved(NameServer ns)
 {
     // "Name server '{0}' has been resolved, continuing with '{1}'."
       LogMessageCreate(Logging.LogMessageText.REQUEST.INFO.NameServerResolved(ns, Resolver.Domain));
 }
示例#37
0
 protected virtual void OnNextAuthorities(NameServer ns, NameServerCollection authorities)
 {
     foreach (IGrouping<int, NameServer> nsg in authorities.Groupings)
       {
     LogMessageCreate(Logging.LogMessageText.RESPONSE.INFO.NextAuthoritiesReceived(
       ns.Name, nsg.First().Zone, authorities));
       }
 }