Exemple #1
0
 internal static extern uint DnsQuery(
     [MarshalAs(UnmanagedType.VBByRefStr)] ref string name,
     [MarshalAs(UnmanagedType.U2)] DnsRecordType type,
     [MarshalAs(UnmanagedType.U4)] DnsQueryType opts,
     IntPtr Servers,
     [In, Out] ref IntPtr queryResults,
     IntPtr reserved);
        private bool GetSetting(DnsQueryType type)
        {
            DnsQueryType srchval = type;
            bool         isset   = (QueryType & srchval) == srchval;

            return(isset);
        }
Exemple #3
0
 /// <summary>
 /// Construct a DnsQuery for transmission to a DNS Server
 /// </summary>
 /// <param name="transactionId">The Id of the transaction with the server</param>
 /// <param name="questionCount">The number of questions being asked in this query</param>
 /// <param name="queryType">The type of query being performed</param>
 /// <param name="recursionDesired">Is recursion desired?</param>
 public DnsQueryHeader(int transactionId, int questionCount, DnsQueryType queryType, bool recursionDesired)
     : this()
 {
     QueryType = queryType;
     TransactionId = transactionId;
     QuestionCount = questionCount;
     RecursionDesired = recursionDesired;
 }
Exemple #4
0
        /// <summary>
        /// Initialises a new instance of the DnsQuestion class and specifies
        /// the class of query, the query type and the domain being queried.
        /// </summary>
        /// <param name="name">The domain to query.</param>
        /// <param name="type">The type of query.</param>
        /// <param name="cls">The class of the query.</param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when <paramref name="name"/> is <see langword="null"/>.
        /// </exception>
        public DnsQuestion(DnsName name, DnsQueryType type, DnsQueryClass cls)
        {
            Guard.NotNull(name, "name");

            _class = cls;
            _type  = type;
            _name  = name;
        }
        public void ctor_sets_correct_properties()
        {
            DnsQueryClass cls      = DnsQueryClass.IN;
            DnsQueryType  type     = DnsQueryType.A;
            DnsName       name     = DnsName.Parse("test.com");
            DnsQuestion   question = new DnsQuestion(name, type, cls);

            Assert.AreEqual(cls, question.Class);
            Assert.AreEqual(type, question.Type);
            Assert.AreEqual(name, question.Name);
        }
Exemple #6
0
        /// <summary>
        /// Initialises a new instance of the DnsQuestion class and the reply
        /// reader from which the question will be decoded.
        /// </summary>
        /// <param name="reader">The reader.</param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when <paramref name="reader"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="AK.Net.Dns.DnsFormatException">
        /// Thrown when question data could not be read from the
        /// <paramref name="reader"/>.
        /// </exception>
        public DnsQuestion(IDnsReader reader)
        {
            Guard.NotNull(reader, "reader");

            try {
                _name  = reader.ReadName();
                _type  = reader.ReadQueryType();
                _class = reader.ReadQueryClass();
            } catch (DnsException exc) {
                throw Guard.InvalidDnsQuestionFormat(exc);
            }
        }
 /// <summary>
 /// Create a DNS query using the specified host name and DNS query type.
 /// </summary>
 /// <param name="host">The DNS host to request in the query.</param>
 /// <param name="type">The type of DNS query to request.</param>
 /// <returns>The complete DNS query.</returns>
 public static DnsHeader CreateQuery(string host, DnsQueryType type = DnsQueryType.A)
 {
     return(new DnsHeader
     {
         Id = GenerateId(),
         Host = host,
         QueryType = type,
         QueryClass = DnsQueryClass.IN,
         OperationCode = DnsOperationCode.QUERY,
         QuestionCount = 1,
         RecusionDesired = true
     });
 }
        public async Task TestDelegatingHandler(bool isIpv4, DnsQueryType dnsQueryType, string address)
        {
            var dnsClient   = Repository.Create <IDnsClient>();
            var mockHandler = new Mock <MockHttpMessageHandler> {
                CallBase = true
            };
            var dnsHandler = new DnsDelegatingHandler(dnsClient.Object, isIpv4)
            {
                InnerHandler = mockHandler.Object
            };
            var httpClient = new HttpClient(dnsHandler);

            dnsClient.Setup(x => x.Query(It.Is <DnsHeader>(x => x.Host == "www.google.com" && x.QueryType == dnsQueryType), It.IsAny <CancellationToken>()))
            .ReturnsAsync(new DnsAnswer
            {
                Answers = new List <DnsResourceRecord>
                {
                    new DnsResourceRecord
                    {
                        Type     = dnsQueryType,
                        Resource = new DnsIpAddressResource {
                            IPAddress = IPAddress.Parse(address)
                        }
                    }
                }
            });

            var expectedResponse = new HttpResponseMessage();

            mockHandler.Setup(x => x.SendAsyncMock(It.IsAny <HttpRequestMessage>(), It.IsAny <CancellationToken>()))
            .Callback <HttpRequestMessage, CancellationToken>((request, CancellationToken) =>
            {
                Assert.Equal(HttpMethod.Get, request.Method);
                Assert.Equal("www.google.com", request.Headers.Host);
                Assert.Equal($"https://{address}/test", request.RequestUri.ToString());
            })
            .ReturnsAsync(expectedResponse);

            var request = new HttpRequestMessage(HttpMethod.Get, "https://www.google.com/test");

            Assert.Equal("https://www.google.com/test", request.RequestUri.ToString());
            Assert.Null(request.Headers.Host);

            var actualResponse = await httpClient.SendAsync(request);

            Assert.Same(expectedResponse, actualResponse);

            Assert.Equal("https://www.google.com/test", request.RequestUri.ToString());
            Assert.Null(request.Headers.Host);
        }
        private void SetSetting(DnsQueryType type, bool newvalue)
        {
            DnsQueryType srchval = type;
            bool         isset   = (QueryType & srchval) == srchval;
            bool         newset  = newvalue;

            //compare
            if (isset.CompareTo(newset) == 0)
            {
                return;
            }

            //toggle
            QueryType ^= srchval;
        }
        private static extern uint DnsQuery(
            [MarshalAs(UnmanagedType.LPStr)]
            string Name,

            [MarshalAs(UnmanagedType.U2)]
            DnsRecordType Type,

            [MarshalAs(UnmanagedType.U4)]
            DnsQueryType Options,

            IntPtr Servers,

            [In, Out]
            ref IntPtr QueryResultsSet,

            IntPtr Reserved
            );
Exemple #11
0
        public static async Task RunQuery(this IDnsClient client, string host, DnsQueryType queryType, DnsResponseCode expectedResponseCode = DnsResponseCode.NoError)
        {
            var query  = DnsQueryFactory.CreateQuery(host, queryType);
            var answer = await client.Query(query);

            Assert.Equal(host, answer.Header.Host);
            Assert.Equal(query.Id, answer.Header.Id);
            Assert.Equal(expectedResponseCode, answer.Header.ResponseCode);

            if (expectedResponseCode == DnsResponseCode.NoError && !answer.Header.Truncation)
            {
                Assert.True(answer.Answers.Count > 0);
            }
            else
            {
                Assert.Empty(answer.Answers);
            }
        }
Exemple #12
0
        private void DoQueryCommand(string[] args)
        {
            DnsName       qname;
            DnsQueryType  ttype;
            DnsQueryType  qtype = this.DefaultQueryType;
            DnsQueryClass tclass;
            DnsQueryClass qclass   = this.DefaultQueryClass;
            string        qnameArg = args[args.Length - 1];
            IPAddress     taddr;
            IPEndPoint    qserver = null;

            for (int i = 0; i < args.Length - 1; ++i)
            {
                if (args[i][0] == '@')
                {
                    int    serverIndex;
                    string arg = args[i].Substring(1);

                    if (int.TryParse(arg, out serverIndex))
                    {
                        if (serverIndex < 0 || serverIndex > this.Resolver.Servers.Count - 1)
                        {
                            WriteUsage("@server: {0} is not a valid forward server index (0-{1})",
                                       arg, this.Resolver.Servers.Count - 1);
                            return;
                        }
                        qserver = this.Resolver.Servers[serverIndex];
                    }
                    else if (IPAddress.TryParse(arg, out taddr) || TryGetHostAddress(arg, out taddr))
                    {
                        qserver = new IPEndPoint(taddr, DnsTransport.DnsPort);
                    }
                    else
                    {
                        WriteUsage("@server: '{0}' is not a valid server/ip/index or it could not be resolved", arg);
                        return;
                    }
                    continue;
                }
                if (TryParseEnum(args[i], out ttype))
                {
                    qtype = ttype;
                    continue;
                }
                if (TryParseEnum(args[i], out tclass))
                {
                    qclass = tclass;
                    continue;
                }
                WriteUsage("qtype,qclass: '{0}' is not a value qtype or qclass", args[i]);
                return;
            }

            if (qtype == DnsQueryType.Ptr)
            {
                if (!IPAddress.TryParse(qnameArg, out taddr))
                {
                    WriteUsage("qname: '{0}' is not a valid ip address", qnameArg);
                    return;
                }
                qname = PtrRecord.MakeName(taddr);
            }
            else if (DnsName.TryParse(qnameArg, out qname))
            {
                if (qname.Kind == DnsNameKind.Relative && this.NameSuffix != null)
                {
                    qname = qname.Concat(this.NameSuffix);
                }
            }
            else
            {
                WriteUsage("qname: '{0}' is not a valid qname", qnameArg);
                return;
            }

            DoQueryCommand(new DnsQuestion(qname, qtype, qclass), qserver);
        }
 public async Task TestLookupWithCloudFlare(string domain, DnsQueryType type)
 {
     using var client = new DnsTcpClient(new NullLogger <DnsTcpClient>(), IPAddress.Parse("1.1.1.1"));
     await client.RunQuery(domain, type, type == DnsQueryType.ANY?DnsResponseCode.NotImp : DnsResponseCode.NoError);
 }
Exemple #14
0
        /// <summary>
        /// Returns a <see cref="System.String"/> representation of the specified
        /// <see cref="AK.Net.Dns.DnsQueryType"/>.
        /// </summary>
        /// <param name="value">The type.</param>
        /// <returns>A <see cref="System.String"/> representation of the specified
        /// <see cref="AK.Net.Dns.DnsQueryType"/>.</returns>
        public static string ToString(DnsQueryType value)
        {
            switch (value)
            {
            case DnsQueryType.A:
                return("A");

            case DnsQueryType.NS:
                return("NS");

            case DnsQueryType.CName:
                return("CNAME");

            case DnsQueryType.Soa:
                return("SOA");

            case DnsQueryType.MB:
                return("MB");

            case DnsQueryType.MG:
                return("MG");

            case DnsQueryType.MR:
                return("MR");

            case DnsQueryType.Null:
                return("NULL");

            case DnsQueryType.Wks:
                return("WKS");

            case DnsQueryType.Ptr:
                return("PTR");

            case DnsQueryType.HInfo:
                return("HINFO");

            case DnsQueryType.MInfo:
                return("MINFO");

            case DnsQueryType.MX:
                return("MX");

            case DnsQueryType.Txt:
                return("TXT");

            case DnsQueryType.RP:
                return("RP");

            case DnsQueryType.AsfDB:
                return("ASFDB");

            case DnsQueryType.X25:
                return("X25");

            case DnsQueryType.Isdn:
                return("ISDN");

            case DnsQueryType.RT:
                return("RT");

            case DnsQueryType.Aaaa:
                return("AAAA");

            case DnsQueryType.Loc:
                return("LOC");

            case DnsQueryType.Srv:
                return("SRV");

            case DnsQueryType.DN:
                return("DN");

            case DnsQueryType.Spf:
                return("SPF");

            case DnsQueryType.Axfr:
                return("AXFR");

            case DnsQueryType.MailB:
                return("MAILB");

            case DnsQueryType.All:
                return("ALL");

            default:
#if DEBUG
                throw Guard.ArgumentOutOfRange("value");
#else
                return(value.ToString().ToUpperInvariant());
#endif
            }
        }
Exemple #15
0
 private void Initialize(string domain)
 {
     _domain=domain;
     QueryType = DnsQueryType.STANDARD|DnsQueryType.TREAT_AS_FQDN;
 }
Exemple #16
0
        private void SetSetting(DnsQueryType type, bool newvalue)
        {
            DnsQueryType srchval = type;
            bool isset = (QueryType & srchval) == srchval;
            bool newset = newvalue;

            //compare
            if (isset.CompareTo(newset) == 0)
                return;

            //toggle
            QueryType ^= srchval;
        }
Exemple #17
0
 private bool GetSetting(DnsQueryType type)
 {
     DnsQueryType srchval = type;
     bool isset = (QueryType & srchval) == srchval;
     return isset;
 }
 public async Task TestLookupWithGoogle(string domain, DnsQueryType type)
 {
     using var client = new DnsHttpClient(new HttpClient { BaseAddress = new Uri("https://dns.google/") });
     await client.RunQuery(domain, type);
 }
 public async Task TestLookupWithCloudFlare(string domain, DnsQueryType type)
 {
     using var client = new DnsHttpClient(new HttpClient { BaseAddress = new Uri("https://cloudflare-dns.com/") });
     await client.RunQuery(domain, type, type == DnsQueryType.ANY?DnsResponseCode.NotImp : DnsResponseCode.NoError);
 }
Exemple #20
0
 public static extern uint DnsQuery(string name, DnsRecordType type, DnsQueryType opts, IntPtr Servers, ref IntPtr queryResults, IntPtr reserved);
 public async Task TestLookupWithGoogle(string domain, DnsQueryType type)
 {
     using var client = new DnsTcpClient(new NullLogger <DnsTcpClient>(), IPAddress.Parse("8.8.8.8"));
     await client.RunQuery(domain, type);
 }
Exemple #22
0
        //public void QueryA(string domain)
        //{
        //    string error = null;
        //    this.Query(domain, DnsQueryType.A, out error);
        //}

        private List <DnsRecord> Query(string domain, DnsQueryType queryType, out string error)
        {
            error = null;

            var id = System.Threading.Interlocked.Increment(ref this.identity);

            byte[] recvBuf = null;
            using (UdpClient udpc = new UdpClient(this.server, 53))
            {
                //
                udpc.Client.ReceiveTimeout = this.timeout;

                // SEND REQUEST--------------------
                var reqBuf = this.BuildQuery(id, domain, (ushort)queryType);
                udpc.Send(reqBuf, reqBuf.Length);

                // RECEIVE RESPONSE--------------
                IPEndPoint ep = null;
                recvBuf = udpc.Receive(ref ep);
            }

            //Check the DNS reply
            //check if bit QR (Query response) is set
            if (recvBuf[2] < 128)
            {
                //response byte not set (probably a malformed packet)
                error = "Query response bit not set";
                return(null);
            }

            //check if RCODE field is 0
            if ((recvBuf[3] & 15) > 0)
            {
                //DNS server error, invalid reply
                var status = recvBuf[3];
                error = "DNS server error, invalid reply (" + status + ")";
                return(null);
            }

            //
            var answers = recvBuf[7];

            if (answers == 0)
            {
                //throw new Exception("No results");
                return(new List <DnsRecord>(0));
            }

            var recordList = new List <DnsRecord>(answers);
            //
            int pos = domain.Length + 18;

            if (queryType == DnsQueryType.MX) // MX record
            {
                while (answers > 0)
                {
                    /*
                     *                                   1  1  1  1  1  1
                     *    0  1  2  3  4  5  6  7  8  9  0  1  2  3  4  5
                     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
                     |                                               |
                     |  /                                               /
                     |  /                      NAME                     /
                     |                                               |
                     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
                     |                      TYPE                     |
                     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
                     |                     CLASS                     |
                     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
                     |                      TTL                      |
                     |                                               |
                     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
                     |                   RDLENGTH                    |
                     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--|
                     |  /                     RDATA                     /
                     |  /                                               /
                     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
                     */
                    //pos += 2;
                    //ushort recordType = Adf.BaseDataConverter.ToUInt16(recvBuf, pos);
                    //pos += 2;
                    //ushort recordClass = Adf.BaseDataConverter.ToUInt16(recvBuf, pos);
                    //pos += 2;
                    //int recordTTL = Adf.BaseDataConverter.ToInt32(recvBuf, pos);
                    //pos += 4;
                    //ushort blocklen = Adf.BaseDataConverter.ToUInt16(recvBuf, pos);
                    //pos += 2;
                    //ushort preference = 0;
                    //if (recordType == (ushort)DnsQueryType.MX)
                    //{
                    //    preference = Adf.BaseDataConverter.ToUInt16(recvBuf, pos);
                    //    pos += 2;
                    //}

                    int ttl        = Adf.BaseDataConverter.ToInt32(recvBuf, pos + 6);
                    var preference = Adf.BaseDataConverter.ToUInt16(recvBuf, pos + 12);
                    pos += 14; //offset
                    string value = this.GetMXRecord(recvBuf, pos, out pos);

                    //Console.WriteLine("MX:\t{0}\t{1}\t{2}\t{3}\n", domain, ttl, preference, value);

                    var record = new DnsRecord();
                    record.Preference = preference;
                    record.TTL        = ttl;
                    record.Value      = value;
                    record.Expired    = Environment.TickCount + (ttl * 1000);

                    answers--;

                    //
                    recordList.Add(record);
                }

                //else if (queryType == DnsQueryType.A) // A record
                //{
                //    while (answers > 0)
                //    {
                //        pos += 11; //offset
                //        string record = this.GetARecord(recvBuf, ref pos);

                //        Console.WriteLine("A :\t{0}\t{1}\n", domain, record);

                //        answers--;
                //    }
                //}
            }
            //
            return(recordList);
        }
 private void Initialize(string domain)
 {
     _domain   = domain;
     QueryType = DnsQueryType.STANDARD | DnsQueryType.TREAT_AS_FQDN;
 }
Exemple #24
0
 /// <summary>
 /// Writes a <see cref="AK.Net.Dns.DnsQueryType"/> to the underlying stream.
 /// </summary>
 /// <param name="value">The value to write.</param>
 /// <exception cref="System.ObjectDisposedException">
 /// Thrown when the writer has been disposed of.
 /// </exception>
 public void WriteQueryType(DnsQueryType value)
 {
     WriteUInt16((ushort)value);
 }
 /// <summary>
 /// Create a new <see cref="DnsDelegatingHandler"/> using the specified <see cref="IDnsClient"/>, optionally using IPv6.
 /// </summary>
 /// <param name="dnsClient"></param>
 /// <param name="internetProtocolV4"></param>
 public DnsDelegatingHandler(IDnsClient dnsClient, bool internetProtocolV4 = true)
 {
     _dnsClient = dnsClient;
     _queryType = internetProtocolV4 ? DnsQueryType.A : DnsQueryType.AAAA;
 }
        /// <summary>
        /// Queries the local DNS server for information about
        /// this instance of <see cref="DnsRequest"/> and returns
        /// the response as a <see cref="DnsResponse"/>
        /// </summary>
        /// <returns>A <see cref="DnsResponse"/> object containing the response
        /// from the DNS server.</returns>
        /// <exception cref="NotSupportedException">
        /// The code is running on a machine lesser than Windows 2000
        /// </exception>
        /// <exception cref="ArgumentNullException">
        /// The <see cref="_domain"/> property is null
        /// </exception>
        /// <exception cref="DnsException">
        /// The DNS query itself failed or parsing of the returned
        /// response failed
        /// </exception>
        /// <remarks>
        /// Returns a <see cref="DnsResponse"/> representing the response
        /// from the DNS server or one of the exceptions noted in the
        /// exceptions area, the most common of which is the
        /// <see cref="DnsException"/>.
        /// </remarks>
        public DnsResponse GetResponse(DnsRecordType dnstype)
        {
            if (Environment.OSVersion.Platform != PlatformID.Win32NT)
            {
                throw new NotSupportedException("This API is found only on Windows NT or better.");
            }

            if (_domain == null)
            {
                throw new ArgumentNullException();
            }

            string       strDomain = _domain;
            DnsQueryType querytype = QueryType;

            object Data = new object();

            IntPtr ppQueryResultsSet = IntPtr.Zero;

            try
            {
                uint ret = DnsQuery(strDomain, dnstype, querytype, IntPtr.Zero, ref ppQueryResultsSet, IntPtr.Zero);
                if (ret != 0)
                {
                    throw new DnsException("DNS query fails", ret);
                }

                DnsResponse resp = new DnsResponse();
                // Parse the records.
                // Call function to loop through linked list and fill an array of records
                do
                {
                    // Get the DNS_RECORD
                    DnsRecord dnsrec = (DnsRecord)Marshal.PtrToStructure(
                        ppQueryResultsSet,
                        typeof(DnsRecord)
                        );

                    // Get the Data part
                    GetData(ppQueryResultsSet, ref dnsrec, ref Data);

                    // Wrap data in a struct with the type and data
                    DnsWrapper wrapper = new DnsWrapper();
                    wrapper.RecordType = dnsrec.RecordType;
                    wrapper.RecordData = Data;

                    // Note: this is *supposed* to return many records of the same type.  Don't check for uniqueness.
                    // Add wrapper to array
                    //if (! resp.RawRecords.Contains(wrapper))
                    resp.RawRecords.Add(wrapper);

                    ppQueryResultsSet = dnsrec.Next;
                } while (ppQueryResultsSet != IntPtr.Zero);

                return(resp);
            }
            catch (DnsException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new DnsException("unspecified error", ex);
            }
            finally
            {
                //ensure unmanaged code cleanup occurs

                //free pointer to DNS record block
                DnsRecordListFree(ppQueryResultsSet, DnsFreeType.FreeRecordList);
            }
        }
Exemple #27
0
        private void DoSetCommand(string[] args)
        {
            switch (args[0].ToLowerInvariant())
            {
            case "suffix":
                DnsName suffix = null;

                if (args.Length == 2 && !DnsName.TryParse(args[1], out suffix))
                {
                    WriteUsage("value: '{0}' is not a valid name", args[1]);
                    return;
                }
                this.NameSuffix = suffix;
                WriteLine("suffix set: {0}", this.NameSuffix);
                break;

            case "qclass":
                DnsQueryClass qclass = DnsQueryClass.IN;

                if (args.Length == 2 && !TryParseEnum(args[1], out qclass))
                {
                    WriteUsage("value: '{0}' is not a valid qclass", args[1]);
                    return;
                }
                this.DefaultQueryClass = qclass;
                WriteLine("qclass set: {0}", DnsUtility.ToString(this.DefaultQueryClass));
                break;

            case "qtype":
                DnsQueryType qtype = DnsQueryType.A;

                if (args.Length == 2 && !TryParseEnum(args[1], out qtype))
                {
                    WriteUsage("value: '{0}' is not a valid qtype", args[1]);
                    return;
                }
                this.DefaultQueryType = qtype;
                WriteLine("qtype set: {0}", DnsUtility.ToString(this.DefaultQueryType));
                break;

            case "reverse":
                ParseBooleanOption(NDigOptions.ReverseAddrs, "reverse", args);
                break;

            case "sort":
                ParseBooleanOption(NDigOptions.SortRecords, "sort", args);
                break;

            case "header":
                ParseBooleanOption(NDigOptions.WriteHeader, "header", args);
                break;

            case "question":
                ParseBooleanOption(NDigOptions.WriteQuestion, "question", args);
                break;

            case "answer":
                ParseBooleanOption(NDigOptions.WriteAnswer, "answer", args);
                break;

            case "authority":
                ParseBooleanOption(NDigOptions.WriteAuthority, "authority", args);
                break;

            case "additional":
                ParseBooleanOption(NDigOptions.WriteAdditional, "additional", args);
                break;

            case "stats":
                ParseBooleanOption(NDigOptions.WriteStats, "stats", args);
                break;

            case "noempty":
                ParseBooleanOption(NDigOptions.SuppressEmptySections, "noempty", args);
                break;

            case "nologo":
                ParseBooleanOption(NDigOptions.SuppressLogo, "nologo", args);
                break;

            default:
                WriteUsage("opt: '{0}' is not a valid option", args[0]);
                return;
            }
        }