Пример #1
0
        /// <summary>
        /// Sends the specified <see cref="AK.Net.Dns.DnsQuery"/> to the specified
        /// end point and return the <see cref="AK.Net.Dns.DnsReply"/>.
        /// </summary>
        /// <param name="query">The query to send.</param>
        /// <param name="endpoint">The transport end point.</param>
        /// <returns>
        /// The <see cref="AK.Net.Dns.DnsReply"/> to the <see cref="AK.Net.Dns.DnsQuery"/>.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when <paramref name="endpoint"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="AK.Net.Dns.DnsTransportException">
        /// Thrown when a transport error occurs.
        /// </exception>
        public override DnsReply Send(DnsQuery query, IPEndPoint endpoint)
        {
            Guard.NotNull(endpoint, "endpoint");

            DnsReply      reply     = null;
            IDnsTransport transport = SelectTransport(query);

            try {
                reply = transport.Send(query, endpoint);
            } catch (DnsTransportException exc) {
                // If the selected transport was TCP, we cannot fail over.
                // NOTE this comparison is not thread safe, but at worst it would mean
                // the query being sent again.
                if (transport == this.TcpTransport)
                {
                    throw;
                }
                this.Log.Warn("UDP transport failure, failing over to TCP:", exc);
            }

            if (reply != null)
            {
                if (!reply.Header.IsTruncated)
                {
                    return(reply);
                }
                this.Log.InfoFormat("message truncated, failing over to TCP, question={0}", query.Question);
            }

            return(this.TcpTransport.Send(query, endpoint));
        }
Пример #2
0
        static void Main(string[] args)
        {
            DnsQuery.RegisterImplementation(new PlatformIndependentDnsClient());

            var assembly = Path.GetFileNameWithoutExtension(Process.GetCurrentProcess().ProcessName);

            string loadingModule = null;

            if (!"bruce".Equals(assembly, StringComparison.InvariantCultureIgnoreCase))
            {
                loadingModule = assembly;
            }

            var    argvIndex = Environment.CommandLine.IndexOf(' ');
            string argv      = null;

            if (argvIndex >= 0)
            {
                argv = Environment.CommandLine.Substring(argvIndex + 1);
            }

            var shell = new BruceConsoleShell()
            {
                CommandLine   = argv,
                LoadingModule = loadingModule,
                Verbose       = args.Any(a => string.Equals("--verbose", a, StringComparison.InvariantCultureIgnoreCase)),
                Silent        = args.Any(a => string.Equals("--silent", a, StringComparison.InvariantCultureIgnoreCase))
            };

            shell.Start().Wait();
        }
Пример #3
0
        internal ARecord GetARecord(string domainName)
        {
            try
            {
                DnsQuery _dnsQuery = new DnsQuery(_dnsServers, domainName);

                if (Object.Equals(null, _dnsQuery))
                {
                    ExceptionExtensions.LogError(new ArgumentNullException("dnsQuery is NULL"), "Dig.GetARecord", "dns servers count: " + _dnsServers.Count);
                    return(null);
                }

                DnsAnswer answer = _dnsQuery.QueryServers(RecordType.A);

                if (!Object.Equals(answer, null) && answer.Answers.Count > 0)
                {
                    foreach (Answer item in answer.Answers)
                    {
                        if (!Object.Equals(null, item) && item.RecType == RecordType.A && !Object.Equals(null, item.Data))
                        {
                            return(item.Data as ARecord);
                        }
                    }

                    return(null);
                }
            }
            catch (Exception e)
            {
                ExceptionExtensions.LogError(e, "Dig.GetARecord", "Domain: " + domainName);
            }

            return(null);
        }
        internal string ResolveEndpointToIpAddress(bool flushCache)
        {
            DnsResult dnsResult = null;
            DnsQuery  query     = new DnsQuery(DnsRecordType.A, this.endpointHostName);

            if (flushCache || LocatorServiceClientAdapter.lastCacheUpdate + 300000 < Environment.TickCount)
            {
                LocatorServiceClientAdapter.dnsCache.FlushCache();
                LocatorServiceClientAdapter.lastCacheUpdate = Environment.TickCount;
            }
            dnsResult = LocatorServiceClientAdapter.dnsCache.Find(query);
            if (dnsResult == null)
            {
                try
                {
                    IPHostEntry hostEntry   = Dns.GetHostEntry(this.endpointHostName);
                    IPAddress[] addressList = hostEntry.AddressList;
                    if (addressList.Length > 0)
                    {
                        dnsResult = new DnsResult(DnsStatus.Success, addressList[0], TimeSpan.FromMinutes(1.0));
                        LocatorServiceClientAdapter.dnsCache.Add(query, dnsResult);
                    }
                }
                catch (SocketException)
                {
                }
            }
            if (dnsResult != null)
            {
                return(dnsResult.Server.ToString());
            }
            return(string.Empty);
        }
Пример #5
0
            public static DnsResponse From(byte[] buffer, int length)
            {
                if (buffer == null || length <= 0)
                {
                    return null;
                }

                DnsQuery query = new DnsQuery(string.Empty, Types.A);
                query.data = buffer;
                query.length = length;
                query.ReadResponse();

                return new DnsResponse
                {
                    AdditionalRecords = query.Response.AdditionalRecords,
                    Answers = query.Response.Answers,
                    AuthorativeAnswer = query.Response.AuthorativeAnswer,
                    Authorities = query.Response.Authorities,
                    IsTruncated = query.Response.IsTruncated,
                    QueryID = query.Response.QueryID,
                    ResponseCode = query.Response.ResponseCode,
                    RecursionRequested = query.Response.RecursionRequested,
                    RecursionAvailable = query.Response.RecursionAvailable,
                    Questions = query.Response.Questions
                };
            }
Пример #6
0
        private static IPAddress GetAnswer()
        {
            try
            {
                var dnsClient = new DnsQuery
                {
                    Servers = new ArrayList {
                        new IPEndPoint(IPAddress.Parse(@"8.8.8.8"), 53)
                    },
                    Domain = @"www.google.com",
                };
                if (dnsClient.Send())
                {
                    if (dnsClient.Response.Answers[0] is Address ip)
                    {
                        return(ip.IP);
                    }
                }

                return(null);
            }
            catch
            {
                return(null);
            }
        }
Пример #7
0
        private async Task QueryDns(string domain, string servicePrefix, List <DnsRecord> records)
        {
            var lookup = Invariant($"{servicePrefix}.{domain}");

            bool skipLookup = false;

            if (DomainServiceNegativeCache.TryGetValue(lookup, out DateTimeOffset expires))
            {
                if (DateTimeOffset.UtcNow > expires)
                {
                    DomainServiceNegativeCache.TryRemove(lookup, out _);
                }
                else
                {
                    skipLookup = true;
                }
            }

            if (!skipLookup)
            {
                this.logger.LogDebug("Querying DNS {Lookup}", lookup);

                var dnsResults = await DnsQuery.QuerySrv(lookup);

                if (!dnsResults.Any())
                {
                    DomainServiceNegativeCache[lookup] = DateTimeOffset.UtcNow.AddMinutes(5);

                    this.logger.LogDebug("DNS failed {Lookup} so negative caching", lookup);
                }

                records.AddRange(dnsResults);
            }
        }
Пример #8
0
        /// <summary>
        /// Queries asn.cymru.com for a TXT record
        /// {Reverse-IPaddress}.origin.asn.cymru.com
        /// </summary>
        /// <param name="ipAddress"></param>
        /// <returns></returns>
        //internal string GetASN(string ipAddress)
        //{
        //    string asnResult = string.Empty;
        //    try
        //    {
        //        Response resp = _resolver.Query(string.Join(".", ipAddress.Split('.').Reverse()) + ".origin.asn.cymru.com", QType.TXT, QClass.IN);

        //        if (resp.Answers.Count > 0)
        //        {
        //            RecordTXT txtRecord = resp.Answers[0].RECORD as RecordTXT;
        //            if (!Object.Equals(txtRecord, null))
        //                asnResult = txtRecord.ASN;
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        ExceptionExtensions.LogError(e, "Dig.GetASN", "IPAddress: " + ipAddress);
        //    }


        //    return asnResult;
        //}
        internal string GetASN(string ipAddress)
        {
            string asnResult = string.Empty;

            try
            {
                DnsQuery _dnsQuery = new DnsQuery(_dnsServers, string.Join(".", ipAddress.Split('.').Reverse()) + ".origin.asn.cymru.com");
                if (Object.Equals(null, _dnsQuery))
                {
                    ExceptionExtensions.LogError(new ArgumentNullException("dnsQuery is NULL"), "Dig.GetASN", "dns servers count: " + _dnsServers.Count);
                    return(null);
                }

                DnsAnswer resp = _dnsQuery.QueryServers(RecordType.TXT);

                if (!Object.Equals(null, resp) && resp.Answers.Count > 0)
                {
                    TxtRecord txtRecord = resp.Answers[0].Data as TxtRecord;
                    if (!Object.Equals(txtRecord, null))
                    {
                        asnResult = txtRecord.ASN;
                    }
                }
            }
            catch (Exception e)
            {
                ExceptionExtensions.LogError(e, "Dig.GetASN", "IPAddress: " + ipAddress);
            }


            return(asnResult);
        }
Пример #9
0
        /// <summary>
        /// Get an empty error response with the given status code
        /// </summary>
        /// <param name="query"></param>
        /// <param name="statusCode"></param>
        /// <returns></returns>
        private static DnsResponse GetErrorResponse(DnsQuery query, DnsQueryStatusCode statusCode)
        {
            var response = new DnsResponse(query, null);

            response.StatusCode = statusCode;
            return(response);
        }
Пример #10
0
        public void GoodDomainTest()
        {
            var names = DnsQuery.GetMxNames("microsoft.com");

            Assert.AreNotEqual(0, names.Count);

            names = DnsQuery.GetMxNames("live.com");
            Assert.AreNotEqual(0, names.Count);

            names = DnsQuery.GetMxNames("live.com.au");
            Assert.AreNotEqual(0, names.Count);

            names = DnsQuery.GetMxNames("hotmail.com");
            Assert.AreNotEqual(0, names.Count);

            names = DnsQuery.GetMxNames("gmail.com");
            Assert.AreNotEqual(0, names.Count);

            names = DnsQuery.GetMxNames("yahoo.com");
            Assert.AreNotEqual(0, names.Count);

            names = DnsQuery.GetMxNames("bigpond.com.au");
            Assert.AreNotEqual(0, names.Count);

            names = DnsQuery.GetMxNames("bigpond.com");
            Assert.AreNotEqual(0, names.Count);

            names = DnsQuery.GetMxNames("student.monash.edu");
            Assert.AreNotEqual(0, names.Count);
        }
Пример #11
0
 public SrvLookup(ServiceDnsName name, ServiceFactory <TService> factory)
 {
     Name       = name;
     Factory    = factory;
     SrvQuery   = new DnsQuery(name.DnsName, DnsRecordType.SRV);
     Completion = new TaskCompletionSource <Func <TService> >(this);
 }
Пример #12
0
        public void TestFailedLookup()
        {
            DnsQuery.Debug = true;

            var records = DnsQuery.QuerySrv(UnknownSrvRecord);

            Assert.AreEqual(0, records.Count());
        }
Пример #13
0
        public async Task FailedLookup()
        {
            DnsQuery.Debug = true;

            var records = await DnsQuery.QuerySrv(UnknownSrvRecord);

            Assert.AreEqual(0, records.Count());
        }
Пример #14
0
 //[ExpectedException(typeof(Win32Exception), ExpectedMessage="DNS name does not exist")]
 public void TestQueryInvalidDomain()
 {
     Assert.Throws <Win32Exception>(() =>
     {
         const string domain = "thisdomaindoesnotexist123456.net";
         DnsQuery.QueryMx(domain);
     });
 }
Пример #15
0
        public async Task SRV_Fail_Test()
        {
            var query = new DnsQuery("_unknown._tcp.imprezzio.org", DnsRecordType.SRV);

            DnsEntry[] records = await query.TryResolve();

            Assert.AreEqual(0, records.Length);
            Assert.AreEqual(DnsQueryStatus.NotFound, query.QueryStatus);
        }
Пример #16
0
        /// <summary>
        /// Encodes and returns the specified <see cref="AK.Net.Dns.DnsQuery"/>.
        /// </summary>
        /// <param name="query">The query to encode.</param>
        /// <returns>The encoded <see cref="AK.Net.Dns.DnsQuery"/>.</returns>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when <paramref name="query"/> is <see langword="null"/>.
        /// </exception>
        protected ArraySegment <byte> WriteQuery(DnsQuery query)
        {
            Guard.NotNull(query, "query");

            using (DnsWireWriter writer = new DnsWireWriter()) {
                query.Write(writer);
                return(writer.GetBuffer());
            }
        }
Пример #17
0
        private static bool GetHostStatus(string domainName)
        {
            if (RuntimeEnvironment.Environment == ApplicationEnvironment.Dev && domainName == RuntimeEnvironment.TestEmailDomain)
            {
                return(true);
            }

            var exchangeNames = DnsQuery.GetMxNames(domainName);

            return(exchangeNames.Count > 0);
        }
Пример #18
0
        public void BadDomainTest()
        {
            var names = DnsQuery.GetMxNames("hotmai.com");

            Assert.AreEqual(0, names.Count);

            names = DnsQuery.GetMxNames("yahoo.co.au");
            Assert.AreEqual(0, names.Count);

            names = DnsQuery.GetMxNames("bigpand.net");
            Assert.AreEqual(0, names.Count);
        }
Пример #19
0
        public void TestQueryMxGoogle()
        {
            const string domain = "google.com";

            Log.InfoFormat("Query domain '{0}'", domain);
            var mailExchangers = DnsQuery.QueryMx(domain);

            LogMxs(domain, mailExchangers);

            Assert.IsNotNull(mailExchangers);
            Assert.AreEqual(5, mailExchangers.Count());
        }
Пример #20
0
        public void TestQueryMxTrademe()
        {
            const string domain = "trademe.co.nz";

            Log.InfoFormat("Query domain '{0}'", domain);
            var mailExchangers = DnsQuery.QueryMx(domain);

            LogMxs(domain, mailExchangers);

            Assert.IsNotNull(mailExchangers);
            Assert.AreEqual(mailExchangers.Count(), 8);
        }
Пример #21
0
        public void TestQueryMxSlashdot()
        {
            const string domain = "slashdot.org";

            Log.InfoFormat("Query domain '{0}'", domain);
            var mailExchangers = DnsQuery.QueryMx(domain);

            LogMxs(domain, mailExchangers);

            Assert.IsNotNull(mailExchangers);
            Assert.AreEqual(mailExchangers.Count(), 1);
        }
Пример #22
0
        /// <summary>
        /// Creates a query containing the specified <paramref name="question"/>.
        /// </summary>
        /// <param name="question">The DNS question.</param>
        /// <returns>A new <see cref="AK.Net.Dns.DnsQuery"/>.</returns>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when <paramref name="question"/> is <see langword="null"/>.
        /// </exception>
        protected virtual DnsQuery CreateQuery(DnsQuestion question)
        {
            Guard.NotNull(question, "question");

            DnsQuery query = new DnsQuery();

            query.Header.Id = DnsResolver.GenerateQueryId();
            query.Header.IsRecursionDesired = true;
            query.Questions.Add(question);

            return(query);
        }
Пример #23
0
        public async Task SRV_Query_Speed_Test()
        {
            for (int i = 0; i < 20; i++)
            {
                DateTime start = DateTime.UtcNow;
                var      query = new DnsQuery("_ldap._tcp.imprezzio.org", DnsRecordType.SRV);
                await query.Resolve();

                double ms = DateTime.UtcNow.Subtract(start).TotalMilliseconds;
                Console.WriteLine($"[{i}] = {ms}ms");
            }
        }
Пример #24
0
        public void TestQueryMxGoogle()
        {
            const string domain = "google.com";

            Log.Info("Query domain '{0}'", domain);
            var mailExchangers = DnsQuery.QueryMx(domain);

            LogMxs(domain, mailExchangers);

            mailExchangers.ShouldNotBeNull();
            5.ShouldEqual(mailExchangers.Count());
        }
Пример #25
0
        public void TestQueryMxSlashdot()
        {
            const string domain = "slashdot.org";

            Log.Info("Query domain '{0}'", domain);
            var mailExchangers = DnsQuery.QueryMx(domain);

            LogMxs(domain, mailExchangers);

            mailExchangers.ShouldNotBeNull();
            mailExchangers.Count().ShouldEqual(1);
        }
Пример #26
0
        public void TestQueryMxTrademe()
        {
            const string domain = "trademe.co.nz";

            Log.Info("Query domain '{0}'", domain);
            var mailExchangers = DnsQuery.QueryMx(domain);

            LogMxs(domain, mailExchangers);

            mailExchangers.ShouldNotBeNull();
            mailExchangers.ShouldNotBeEmpty();
            mailExchangers.Count().ShouldBeGreaterThanOrEqualTo(3);
        }
Пример #27
0
        public static ArrayList GetListNameServers()
        {
            ArrayList nameServers = new ArrayList();

            IList <IPAddress> machineDnsServers = DnsQuery.GetMachineDnsServers();

            foreach (IPAddress ipAddress in machineDnsServers)
            {
                nameServers.Add(ipAddress.ToString());
            }

            return(nameServers);
        }
Пример #28
0
        public void TestQuerySrvRecordHittingInternet()
        {
            DnsQuery.Debug = true;

            var records = DnsQuery.QuerySrv(ExternalSrvRecord);

            Assert.IsTrue(records.Count() > 0);

            var srv = records.Single(r => r.Type == DnsRecordType.SRV);

            Assert.AreEqual("sipdir.online.lync.com", srv.Target);
            Assert.AreEqual(443, srv.Port);
        }
Пример #29
0
        public void TestDNsQuery()
        {
            var DNSquery = new DnsQuery("www.google.com", id: 0x00003245);

            var actual = DNSquery.GetBytes();

            var expected = new byte[] {
                0x32, 0x45, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x77, 0x77, 0x77,
                06, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x03, 0x63, 0x6f, 0x6d, 0x00, 0x00, 0x01, 0x00, 0x01
            };

            Assert.Equal(expected, actual);
        }
Пример #30
0
        public static void Main(string[] args)
        {
            var nameServers = AKDns.GetNameServers("rcmap.co.uk.");
            var mxInfo      = AKDns.GetMXInfo("rcmap.co.uk.");

            IDnsTransport transport = new DnsUdpTransport();

            DnsQuery query = new DnsQuery();

            query.Questions.Add(new DnsQuestion("rcmap.co.uk.", DnsQueryType.A, DnsQueryClass.IN));

            DnsReply reply = transport.Send(query, new IPEndPoint(IPAddress.Parse("8.8.8.8"), DnsTransport.DnsPort));
        }
        public static DnsResponse Resolver(DnsQuery query)
        {
            const uint TimeToLive = 300;
            var response = query.CreateResponse();

            switch (query.QueryType)
            {
                // Resolve all A queries to localhost
                case RecordType.A:
                    var aResourceRecord = new AResourceRecord(query, TimeToLive, IPAddress.Loopback);
                    response.AnswerRecords.Add(aResourceRecord);
                    break;

                // Resolve all TXT to "Hello World"
                case RecordType.TXT:
                    var txtResourceRecord = new TxtResourceRecord(query, TimeToLive, new []{ "Hello world"});
                    response.AnswerRecords.Add(txtResourceRecord);
                    break;
            }

            return response;
        }
 /// <summary>
 /// Get an empty error response with the given status code
 /// </summary>
 /// <param name="query"></param>
 /// <param name="statusCode"></param>
 /// <returns></returns>
 private static DnsResponse GetErrorResponse(DnsQuery query, DnsQueryStatusCode statusCode)
 {
     var response = new DnsResponse(query, null);
     response.StatusCode = statusCode;
     return response;
 }
 public void Send(DnsQuery query)
 {
     System.Net.Dns.GetHostAddresses("");
 }
 public DnsResponse(DnsQuery query) :
     this(query.MessageId, query.QueryName, query.QueryType, query.QueryClass)
 {
 }
 public AResourceRecord(DnsQuery query, uint timeToLive, IPAddress ipAddress)
     :base(query, timeToLive)
 {
     this.ipAddress = ipAddress;
 }
 public CnameResourceRecord(DnsQuery query, uint timeToLive, DnsName dnsName)
     : base(query, timeToLive)
 {
     this.dnsName = dnsName;
 }
Пример #37
0
        public void Extracts_TransactionId_Correctly_From_Well_Formed_Question()
        {
            var dnsQuery = new DnsQuery(test_dot_cocktail_dot_local_A_Record);

            Assert.That(dnsQuery.Header.TransactionId, Is.EqualTo(1));
        }
 protected ResourceRecordBase(DnsQuery query, uint timeToLive)
     : this(query.QueryName, query.QueryType, query.QueryClass, timeToLive)
 {
 }
 public TxtResourceRecord(DnsQuery query, uint timeToLive, string[] strings)
     : base(query, timeToLive)
 {
     this.strings = strings;
 }