Exemplo n.º 1
0
 public DnsResourceRecord(string name, DnsRecordType recordType, UInt32 timeToLive, byte[] data)
 {
     this.Name = name;
     this.RecordType = recordType;
     this.TimeToLive = timeToLive;
     this.Data = data;
 }
Exemplo n.º 2
0
        /// <summary>
        /// rec_edit
        /// </summary>
        /// <param name="dnsRecordId"></param>
        /// <param name="domainName"></param>
        /// <param name="dnsRecordName"></param>
        /// <param name="dnsRecordType"></param>
        /// <param name="dnsRecordContent"></param>
        /// <param name="ttl">1 = auto</param>
        /// <param name="enableCloudFront"></param>
        /// <returns></returns>
        public CloudFlareApiResponseBase EditDnsRecord(
            int?dnsRecordId, string domainName, string dnsRecordName, DnsRecordType dnsRecordType,
            string dnsRecordContent, int ttl = Constants.AutomaticTtl, bool enableCloudFront = true)
        {
            try
            {
                if (dnsRecordId == null)
                {
                    dnsRecordId = GetDnsRecordId(domainName, dnsRecordName, dnsRecordType);
                }

                var postData = new HttpPostDataCollection()
                {
                    { ApiParameter.DnsRecordId, dnsRecordId.Value.ToString() },
                    { ApiParameter.DomainName, domainName },
                    { ApiParameter.DnsRecordName, dnsRecordName },
                    { ApiParameter.DnsRecordType, EnumerationUtility.GetStringValue(dnsRecordType) },
                    { ApiParameter.DnsRecordContent, dnsRecordContent },
                    { ApiParameter.Ttl, ttl.ToString() },
                    { ApiParameter.ServiceMode, enableCloudFront ? "1" : "0" }
                };

                var request = CreatePostHttpWebRequest(credentials, ApiAction.EditDnsRecord, postData);

                var response = GetResponse <DnsRecordApiResponse>(request);

                return(response);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                throw;
            }
        }
Exemplo n.º 3
0
 public static PhpArray GetRecord(string host, DnsRecordType type, out PhpArray authNS, out PhpArray additional)
 {
     PhpException.FunctionNotSupported();
     authNS     = null;
     additional = null;
     return(null);
 }
Exemplo n.º 4
0
 public int UpdateDnsZoneRecord(int domainId,
                                string originalRecordName, string originalRecordData,
                                string recordName, DnsRecordType recordType, string recordData, int mxPriority)
 {
     return(ServerController.UpdateDnsZoneRecord(domainId, originalRecordName, originalRecordData,
                                                 recordName, recordType, recordData, mxPriority));
 }
        public async Task <IReadOnlyCollection <DnsRecord> > Query(string query, DnsRecordType type)
        {
            if (WindowsDns.IsSupported)
            {
                return(await WindowsDns.Query(query, type));
            }

            var client = new LookupClient();

            var response = await client.QueryAsync(query, (QueryType)type);

            var srvRecords = response.Answers.SrvRecords().Select(a => new DnsRecord
            {
                Name       = a.DomainName,
                Port       = a.Port,
                Priority   = a.Priority,
                Target     = a.Target,
                TimeToLive = a.TimeToLive,
                Type       = DnsRecordType.SRV,
                Weight     = a.Weight
            }).ToList();

            var merged = srvRecords.GroupBy(r => r.Name);

            foreach (var srv in srvRecords)
            {
                var c1 = merged.Where(m => m.Key.Equals(srv.Target, StringComparison.InvariantCultureIgnoreCase));

                var canon = c1.SelectMany(r => r);

                srv.Canonical = canon.ToList();
            }

            return(srvRecords);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Determines whether or not this <see cref="DnsWrapper"/>
        /// instance is equal to a specific <see cref="DnsRecordType"/>
        /// by comparing the <see cref="RecordType"/> property of the
        /// current <see cref="DnsWrapper"/> against the
        /// <see cref="DnsRecordType"/> argument.
        /// </summary>
        /// <param name="type">The <see cref="DnsRecordType"/> to compare to.</param>
        /// <returns>A boolean indicating whether or not this <see cref="DnsWrapper"/>
        /// object contains a DNS record matching the entered type.</returns>
        /// <remarks>
        /// Determines if this <see cref="DnsWrapper"/> is of a specific
        /// <see cref="DnsRecordType"/>. The comparison does not test the
        /// <see cref="RecordData"/> field.
        /// </remarks>
        public bool Equals(DnsRecordType type)
        {
            if (RecordType == type)
                return true;

            return false;
        }
Exemplo n.º 7
0
        private static IResourceRecord Create(Domain domain, IPAddress ip, TimeSpan ttl)
        {
            byte[]        data = ip.GetAddressBytes();
            DnsRecordType type = data.Length == 4 ? DnsRecordType.A : DnsRecordType.AAAA;

            return(new ResourceRecord(domain, data, type, DnsRecordClass.IN, ttl));
        }
Exemplo n.º 8
0
        public IList <IPAddress> Lookup(string domain, DnsRecordType type = DnsRecordType.A)
        {
            if (string.IsNullOrWhiteSpace(domain))
            {
                throw new ArgumentNullException(nameof(domain));
            }

            if (type != DnsRecordType.A && type != DnsRecordType.AAAA)
            {
                throw new ArgumentException("Invalid record type " + type);
            }

            var response = Resolve(domain, type);
            var ips      = response.AnswerRecords
                           .Where(r => r.Type == type)
                           .Cast <DnsIPAddressResourceRecord>()
                           .Select(r => r.IPAddress)
                           .ToList();

            if (ips.Count == 0)
            {
                throw new DnsQueryException(response, "No matching records");
            }

            return(ips);
        }
Exemplo n.º 9
0
        /// <summary>
        /// 获取服务器输出
        /// </summary>
        /// <param name="qname">记录名称</param>
        /// <param name="type">Query type</param>
        /// <returns></returns>
        private DnsServerResponse GetResponse(String qname, DnsRecordType type)
        {
            DnsServerResponse rlt = null;

            using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                var buffer     = new byte[512];
                var sendLength = CreateQuery(buffer, requestID++, qname, type, 1);
                socket.ReceiveTimeout = 15000;
                foreach (var serverIP in serverIPs)
                {
                    try
                    {
                        socket.Connect(serverIP, 53);
                        if (socket.Send(buffer, sendLength, SocketFlags.None) > 0)
                        {
                            var response = new byte[1024];
                            if (socket.Receive(response) > 0)
                            {
                                rlt = ParseQuery(response);
                                socket.Shutdown(SocketShutdown.Both);
                                socket.Dispose();
                                break;
                            }
                        }
                    }
                    catch { }
                }
            }
            return(rlt);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Wrapper method to perform DNS Query.
        /// </summary>
        /// <remarks>Makes DnsQuery a little more palatable.</remarks>
        /// <param name="domain">The domain.</param>
        /// <param name="dnsServerAddress">IPAddress of DNS server (may be null) </param>
        /// <param name="recordType">Type of DNS dnsRecord.</param>
        /// <param name="ppQueryResults">Pointer to pointer to query results.</param>
        /// <returns>Win32 status code.</returns>
        internal static int DnsQuery(
            string domain,
            IPAddress dnsServerAddress,
            DnsRecordType recordType,
            ref IntPtr ppQueryResults)
        {
            Debug.Assert(!string.IsNullOrEmpty(domain), "domain cannot be null.");

            IntPtr pServerList = IntPtr.Zero;

            try
            {
                pServerList = DnsNativeMethods.AllocDnsServerList(dnsServerAddress);

                return(DnsNativeMethods.DnsQuery(
                           domain,
                           recordType,
                           DnsQueryOptions.DNS_QUERY_STANDARD,
                           pServerList,
                           ref ppQueryResults,
                           0));
            }
            finally
            {
                // Note: if pServerList is IntPtr.Zero, FreeHGlobal does nothing.
                Marshal.FreeHGlobal(pServerList);
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Wrapper method to perform DNS Query.
        /// </summary>
        /// <remarks>Makes DnsQuery a little more palatable.</remarks>
        /// <param name="domain">The domain.</param>
        /// <param name="dnsServerAddress">IPAddress of DNS server (may be null) </param>
        /// <param name="recordType">Type of DNS dnsRecord.</param>
        /// <param name="ppQueryResults">Pointer to pointer to query results.</param>
        /// <returns>Win32 status code.</returns>
        internal static int DnsQuery(
            string domain,
            IPAddress dnsServerAddress,
            DnsRecordType recordType,
            ref IntPtr ppQueryResults)
        {
            Debug.Assert(!string.IsNullOrEmpty(domain), "domain cannot be null.");

            IntPtr pServerList = IntPtr.Zero;

            try
            {
                pServerList = AllocDnsServerList(dnsServerAddress);

                return(DnsQuery(
                           domain,
                           recordType,
                           DnsQueryOptions.DNS_QUERY_STANDARD,

                           /*  TODO: Experiment with these:
                            *  DnsQueryOptions.DNS_QUERY_WIRE_ONLY |
                            *  DnsQueryOptions.DNS_QUERY_NO_HOSTS_FILE |
                            *  DnsQueryOptions.DNS_QUERY_NO_NETBT |
                            *  DnsQueryOptions.DNS_QUERY_NO_MULTICAST |
                            *  DnsQueryOptions.DNS_QUERY_TREAT_AS_FQDN,*/
                           pServerList,
                           ref ppQueryResults,
                           0));
            }
            finally
            {
                // Note: if pServerList is IntPtr.Zero, FreeHGlobal does nothing.
                Marshal.FreeHGlobal(pServerList);
            }
        }
Exemplo n.º 12
0
        public async Task ValidDns_ReturnsQueryDns(DnsRecordType dnsRecordType)
        {
            try
            {
                var records = await Network.QueryDnsAsync(GoogleDnsFqdn, dnsRecordType);

                Assert.IsFalse(records.IsAuthoritativeServer, $"IsAuthoritativeServer, Testing with {dnsRecordType}");
                Assert.IsFalse(records.IsTruncated, $"IsTruncated, Testing with {dnsRecordType}");
                Assert.IsTrue(records.IsRecursionAvailable, $"IsRecursionAvailable, Testing with {dnsRecordType}");
                Assert.AreEqual("Query",
                                records.OperationCode.ToString(),
                                $"OperationCode, Testing with {dnsRecordType}");
                Assert.AreEqual(DnsResponseCode.NoError,
                                records.ResponseCode,
                                $"{GoogleDnsFqdn} {dnsRecordType} Record has no error");
                Assert.AreEqual(dnsRecordType == DnsRecordType.TXT,
                                records.AnswerRecords.Any(),
                                $"AnswerRecords, Testing with {dnsRecordType}");

                await Task.Delay(100);
            }
            catch (DnsQueryException)
            {
                Assert.Ignore("Timeout");
            }
        }
Exemplo n.º 13
0
        public IDnsRecord DecodeRecord(IByteBuffer inputBuffer)
        {
            int    startOffset = inputBuffer.ReaderIndex;
            string name        = DecodeName(inputBuffer);

            int endOffset = inputBuffer.WriterIndex;

            if (endOffset - startOffset < 10)
            {
                inputBuffer.SetReaderIndex(startOffset);
                return(null);
            }

            DnsRecordType type        = DnsRecordType.From(inputBuffer.ReadUnsignedShort());
            var           recordClass = (DnsRecordClass)inputBuffer.ReadUnsignedShort();
            long          ttl         = inputBuffer.ReadUnsignedInt();
            int           length      = inputBuffer.ReadUnsignedShort();
            int           offset      = inputBuffer.ReaderIndex;

            if (endOffset - offset < length)
            {
                inputBuffer.SetReaderIndex(startOffset);
                return(null);
            }

            IDnsRecord record = DecodeRecord(name, type, recordClass, ttl, inputBuffer, offset, length);

            inputBuffer.SetReaderIndex(offset + length);
            return(record);
        }
 internal static void EnsureIsDataType(this DnsRecordType dnsRecordType)
 {
     if (!dnsRecordType.IsDataType())
     {
         throw new NotSupportedException($"{dnsRecordType} is not data type");
     }
 }
Exemplo n.º 15
0
 /// <summary>
 /// Queries the DNS server for the specified record type.
 /// </summary>
 /// <param name="query">The query.</param>
 /// <param name="recordType">Type of the record.</param>
 /// <param name="ct">The cancellation token.</param>
 /// <returns>Queries the DNS server for the specified record type of the result produced by this Task</returns>
 public static Task <DnsQueryResult> QueryDnsAsync(
     string query,
     DnsRecordType recordType,
     CancellationToken ct = default)
 {
     return(Task.Factory.StartNew(() => QueryDns(query, recordType), ct));
 }
Exemplo n.º 16
0
 public int UpdateDnsZoneRecord(int domainId,
                                string originalRecordName, string originalRecordData,
                                string recordName, DnsRecordType recordType, string recordData, int mxPriority, int srvPriority, int srvWeight, int srvPortNumber)
 {
     return(ServerController.UpdateDnsZoneRecord(domainId, originalRecordName, originalRecordData,
                                                 recordName, recordType, recordData, mxPriority, srvPriority, srvWeight, srvPortNumber));
 }
Exemplo n.º 17
0
 private static extern int DnsQuery(
     [In] string pszName,
     DnsRecordType wType,
     DnsQueryOptions options,
     IntPtr aipServers,
     ref IntPtr ppQueryResults,
     int pReserved);
 public DnsResourceRecord(string name, DnsRecordType recordType, UInt32 timeToLive, byte[] data)
 {
     this.Name       = name;
     this.RecordType = recordType;
     this.TimeToLive = timeToLive;
     this.Data       = data;
 }
Exemplo n.º 19
0
        public static PhpArray dns_get_record(string host, DnsRecordType type, out PhpArray authNS, out PhpArray additional)
        {
            authNS = null;

            additional = null;
            throw new NotImplementedException();
        }
Exemplo n.º 20
0
        /// <summary>
        /// Returns a value indicating if the bulider is capable of building
        /// records of the specified <paramref name="type"/>.
        /// </summary>
        /// <param name="type">The requested type.</param>
        /// <returns>
        /// <see langword="true"/> if the bulider can build records of the
        /// specified <paramref name="type"/>, otherwise; <see langword="false"/>.
        /// </returns>
        public bool CanBuild(DnsRecordType type)
        {
            switch (type)
            {
            case DnsRecordType.A:
            case DnsRecordType.Aaaa:
            case DnsRecordType.NS:
            case DnsRecordType.CName:
            case DnsRecordType.Soa:
            case DnsRecordType.Null:
            case DnsRecordType.Wks:
            case DnsRecordType.Ptr:
            case DnsRecordType.HInfo:
            case DnsRecordType.MB:
            case DnsRecordType.MG:
            case DnsRecordType.MInfo:
            case DnsRecordType.MR:
            case DnsRecordType.MX:
            case DnsRecordType.Txt:
            case DnsRecordType.DN:
            case DnsRecordType.Spf:
            case DnsRecordType.Srv:
                return(true);

            default:
                return(false);
            }
        }
Exemplo n.º 21
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);
Exemplo n.º 22
0
        /// <summary>
        /// rec_new
        /// </summary>
        /// <param name="domainName"></param>
        /// <param name="dnsRecordName"></param>
        /// <param name="dnsRecordType"></param>
        /// <param name="dnsRecordContent"></param>
        /// <param name="ttl"></param>
        /// <param name="enableCloudFront"></param>
        /// <returns></returns>
        public CloudFlareApiResponseBase AddDnsRecord(string domainName, string dnsRecordName, DnsRecordType dnsRecordType,
            string dnsRecordContent, int ttl = Constants.AutomaticTtl, bool enableCloudFront = true)
        {
            try
            {
                var postData = new HttpPostDataCollection()
                               	{
                               		{ApiParameter.DomainName, domainName},
                               		{ApiParameter.DnsRecordName, dnsRecordName},
                               		{ApiParameter.DnsRecordType, EnumerationUtility.GetStringValue(dnsRecordType)},
                               		{ApiParameter.DnsRecordContent, dnsRecordContent},
                               		{ApiParameter.Ttl, ttl.ToString()},
                               		{ApiParameter.ServiceMode, enableCloudFront ? "1" : "0"}
                               	};

                var request = CreatePostHttpWebRequest(credentials, ApiAction.AddDnsRecord, postData);

                var response = GetResponse<DnsRecordApiResponse>(request);

                return response;
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                throw;
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// Initialises a new instance of the NSRecord class and specifies the owner name,
        /// the resource record class, the TTL of the record and the record data.
        /// </summary>
        /// <param name="owner">The owner name.</param>
        /// <param name="type">The type of resource record.</param>
        /// <param name="cls">The class of resource record.</param>
        /// <param name="ttl">The TTL.</param>
        /// <param name="data">The resource record data.</param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when <paramref name="owner"/> <paramref name="data"/> is
        /// <see langword="null"/>.
        /// </exception>
        /// <exception cref="System.ArgumentException">
        /// Thrown when <paramref name="address"/> is not of the
        /// <see cref="System.Net.Sockets.AddressFamily.InterNetwork"/> family.
        /// </exception>
        public XRecord(DnsName owner, DnsRecordType type, DnsRecordClass cls, TimeSpan ttl, byte[] data)
            : base(owner, type, cls, ttl)
        {
            Guard.NotNull(data, "data");

            _data = data;
        }
Exemplo n.º 24
0
 public DnsResourceRecord(DnsDomain domain, byte[] data, DnsRecordType type, DnsRecordClass klass = DnsRecordClass.IN, TimeSpan ttl = default)
 {
     Name       = domain;
     Type       = type;
     Class      = klass;
     TimeToLive = ttl;
     Data       = data;
 }
Exemplo n.º 25
0
        public IDnsQuestion DecodeQuestion(IByteBuffer inputBuffer)
        {
            string        name        = DecodeName(inputBuffer);
            DnsRecordType type        = DnsRecordType.From(inputBuffer.ReadUnsignedShort());
            var           recordClass = (DnsRecordClass)inputBuffer.ReadUnsignedShort();

            return(new DefaultDnsQuestion(name, type, recordClass));
        }
Exemplo n.º 26
0
        /// <summary>
        /// Initialises a new instance of the XRecord class and specifies the owner name,
        /// the resource record class, the TTL of the record and the reply reader from
        /// which the RDLENGTH and RDATA section of the resource record will be read.
        /// </summary>
        /// <param name="owner">The owner name.</param>
        /// <param name="type">The type of resource record.</param>
        /// <param name="cls">The class of resource record.</param>
        /// <param name="ttl">The TTL.</param>
        /// <param name="reader">The reply reader.</param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when <paramref name="owner"/> or <paramref name="reader"/> is
        /// <see langword="null"/>.
        /// </exception>
        /// <exception cref="AK.Net.Dns.DnsFormatException">
        /// Thrown when the RDATA section of the record could not be read from the
        /// <paramref name="reader"/>.
        /// </exception>
        public XRecord(DnsName owner, DnsRecordType type, DnsRecordClass cls, TimeSpan ttl,
                       IDnsReader reader)
            : base(owner, type, cls, ttl)
        {
            Guard.NotNull(reader, "reader");

            _data = reader.ReadBytes(reader.ReadUInt16());
        }
Exemplo n.º 27
0
        /// <summary>
        /// Resolves the specified name.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="recordType">Type of the record.</param>
        /// <param name="recordClass">The record class.</param>
        /// <returns>Task&lt;DnsMessage&gt;.</returns>
        public async Task <DnsMessage> Resolve(string name, DnsRecordType recordType,
                                               DnsRecordClass recordClass = DnsRecordClass.IN)
        {
            var dnsMessage = await GetDnsClient().ResolveAsync(DomainName.Parse(name), (RecordType)recordType.IntValue,
                                                               (RecordClass)(int)recordClass);

            return(dnsMessage);
        }
Exemplo n.º 28
0
            public CacheNode(DnsResponseCode responseCode, DnsRecordType recordType,
                             ICollection <DnsRecord> records, CacheNodeSource source)
            {
                Guard.NotNull(records, "records");

                _records = records;
                _source  = source;
            }
Exemplo n.º 29
0
 private static extern int DnsQuery(
     [In] string pszName,
     DnsRecordType wType,
     DnsQueryOptions options,
     IntPtr pExtra,
     [Out] out IntPtr ppQueryResults,
     IntPtr pReserved
     );
Exemplo n.º 30
0
        private const int MAX_TIMEOUT = 10 * 1000;  // 10 sec

        public WDnsQuery(string query, DnsRecordType type)
        {
            Query = query;
            Type  = type;

            _callback    = QueryComplete;
            _runningWait = new ManualResetEvent(true);
        }
Exemplo n.º 31
0
 public DnsResponse(DnsResponseCode responseCode, DnsRecordType queryType, string queryName, DnsResourceRecord[] answerRecords, DnsResourceRecord[] authorityRecords, DnsResourceRecord[] additionalInformationRecords)
 {
     this.ResponseCode = responseCode;
     this.QueryType = queryType;
     this.QueryName = queryName;
     this.AnswerRecords = answerRecords;
     this.AuthorityRecords = authorityRecords;
     this.AdditionalInformationRecords = additionalInformationRecords;
 }
Exemplo n.º 32
0
 /// <summary>
 /// Queries the DNS server for the specified record type.
 /// </summary>
 /// <param name="query">The query.</param>
 /// <param name="recordType">Type of the record.</param>
 /// <param name="dnsServer">The DNS server.</param>
 /// <param name="port">The port.</param>
 /// <param name="ct">The ct.</param>
 /// <returns>Queries the DNS server for the specified record type of the result produced by this Task</returns>
 public static Task <DnsQueryResult> QueryDnsAsync(
     string query,
     DnsRecordType recordType,
     IPAddress dnsServer,
     int port,
     CancellationToken ct = default)
 {
     return(Task.Factory.StartNew(() => QueryDns(query, recordType, dnsServer, port), ct));
 }
        /* this function returns the number of bytes processed */
        Int32 ParseResourceRecord(byte[] buffer, Int32 offset, out DnsResourceRecord resourceRecord)
        {
            Int32 bytesProcessed = 0;
            // Name
            string name;
            int    dnsNameBytesProcessed = ParseDnsName(buffer, offset, out name);

            bytesProcessed += dnsNameBytesProcessed;
            offset         += bytesProcessed;
            // Type
            DnsRecordType recordType = (DnsRecordType)(
                (UInt16)(buffer[offset++] << 8) +
                (UInt16)(buffer[offset++])
                );

            bytesProcessed += 2;
            // Class
            UInt16 recordClass = (UInt16)(
                (UInt16)(buffer[offset++] << 8) +
                (UInt16)(buffer[offset++])
                );

            bytesProcessed += 2;
            // TTL
            UInt32 timeToLive = (
                (UInt32)(buffer[offset++] << 24) +
                (UInt32)(buffer[offset++] << 16) +
                (UInt32)(buffer[offset++] << 8) +
                (UInt32)(buffer[offset++])
                );

            bytesProcessed += 4;
            // RDLENGTH
            UInt16 dataLength = (UInt16)(
                (UInt16)(buffer[offset++] << 8) +
                (UInt16)(buffer[offset++])
                );

            bytesProcessed += 2;
            // RDATA
            byte[] data = new byte[dataLength];
            Array.Copy(buffer, offset, data, 0, dataLength);
            offset         += dataLength;
            bytesProcessed += dataLength;

            if (recordClass == DNS_RECORD_CLASS_INTERNET)
            {
                resourceRecord = new DnsResourceRecord(name, recordType, timeToLive, data);
            }
            else
            {
                /* filter out the current query */
                resourceRecord = new DnsResourceRecord();
            }

            return(bytesProcessed);
        }
 public DnsResponse(DnsResponseCode responseCode, DnsRecordType queryType, string queryName, DnsResourceRecord[] answerRecords, DnsResourceRecord[] authorityRecords, DnsResourceRecord[] additionalInformationRecords)
 {
     this.ResponseCode                 = responseCode;
     this.QueryType                    = queryType;
     this.QueryName                    = queryName;
     this.AnswerRecords                = answerRecords;
     this.AuthorityRecords             = authorityRecords;
     this.AdditionalInformationRecords = additionalInformationRecords;
 }
Exemplo n.º 35
0
        public DnsQuestion(string name, DnsRecordType type, DnsRecordClass cls, bool unique)
        {
            if (string.IsNullOrEmpty(name))
                throw new ArgumentNullException("name");

            _name = name;
            _type = type;
            _class = cls;
            _unique = unique;
        }
Exemplo n.º 36
0
        private IDnsQueryAnswer GetDnsQueryAnswer(IDnsNameParser parser, DnsName name, DnsRecordType recordType, DnsRecordClass recordClass, UInt32 ttl, short recordDataLength, int recordDataOffset, byte[] packetContent)
        {
            var answer = GetDnsQueryAnswer(parser, recordType, recordDataLength, null, packetContent, recordDataOffset);
            answer.Name = name;
            answer.RecordType = recordType;
            answer.RecordClass = recordClass;
            answer.Ttl = ttl;
            answer.RecordDataLength = recordDataLength;
            //answer.RecordData = recordData;

            return answer;
        }
Exemplo n.º 37
0
 private IDnsQueryAnswer GetDnsQueryAnswer(IDnsNameParser parser, DnsRecordType recordType, short recordDataLength, byte[] recordData, byte[] packetContent, int recordDataOffset)
 {
     switch (recordType)
     {
         case DnsRecordType.A:
             return new DnsQueryAnswerA(parser, recordDataLength, recordDataOffset, packetContent);
         case DnsRecordType.CNAME:
             return new DnsQueryAnswerCName(parser, recordDataLength, recordDataOffset, packetContent);
         case DnsRecordType.MX:
             return new DnsQueryAnswerMx(parser, recordDataLength, recordDataOffset, packetContent);
         case DnsRecordType.NS:
             return new DnsQueryAnswerNS(parser, recordDataLength, recordDataOffset, packetContent);
         case DnsRecordType.AAAA:
         case DnsRecordType.SRV:
         default:
             return new DnsQueryAnswerGeneric();
     }
 }
Exemplo n.º 38
0
        internal IRecordStruct[] Resolve(Type structType, string name, DnsRecordType type, DnsQueryOptions options)
        {
            var result = DnsQuery(ref name, type, options, IntPtr.Zero, ref _queryResultsPtr, IntPtr.Zero);

            if (result != 0)
                throw new DnsQueryException(result);

            var records = new List<IRecordStruct>();
            dynamic record;

            for (var recordPtr = _queryResultsPtr; recordPtr != IntPtr.Zero; recordPtr = record.pNext)
            {
                record = (dynamic)Marshal.PtrToStructure(recordPtr, structType);

                records.Add(record);
            }

            return records.ToArray();
        }
Exemplo n.º 39
0
        public DnsQuery GetDnsEntries(string host, string server, DnsRecordType recordType)
        {
            using (var client = new UdpClient())
            {
                IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Parse(server), 53);
                client.Connect(RemoteIpEndPoint);
                var query = new DnsQuery(transactionId, host, recordType);
                transactionId++;
                var bytes = query.ToByteArray();
                client.Send(bytes, bytes.Length);

                // Get response
                Byte[] receiveBytes = client.Receive(ref RemoteIpEndPoint);

                var result = new DnsQuery(receiveBytes);

                return result;
            }
        }
Exemplo n.º 40
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DnsRecord"/> class.
        /// </summary>
        public DnsRecord(
            IdentifierTag id,
            DateTimeOffset? createdOn,
            DateTimeOffset modifiedOn,
            DnsRecordType type,
            string name,
            bool proxiable,
            bool proxied,
            int ttl,
            bool locked,
            IdentifierTag zoneId,
            int priority,
            string content = null,
            string zoneName = null,
            JObject data = null,
            JObject meta = null)
        {
            if (id == null)
                throw new ArgumentNullException(nameof(id));
            if (name == null)
                throw new ArgumentNullException(nameof(name));
            if (zoneId == null)
                throw new ArgumentNullException(nameof(zoneId));

            Id = id;
            CreatedOn = createdOn;
            ModifiedOn = modifiedOn;
            Type = type;
            Name = name;
            Content = content ?? string.Empty;
            Proxiable = proxiable;
            Proxied = proxied;
            Ttl = ttl;
            Locked = locked;
            ZoneId = zoneId;
            ZoneName = zoneName ?? string.Empty;
            Data = data ?? new JObject();
            Meta = meta ?? new JObject();
            Priority = priority;
        }
Exemplo n.º 41
0
        internal static DnsRecord Create(string name, DnsRecordType type, DnsRecordClass cls, bool unique, byte[] body, byte[] fullPacket)
        {
            switch(type)
            {
                case DnsRecordType.A:
                case DnsRecordType.AAAA:
                    return new DnsRecordAddress(name, type, cls, unique, body);

                case DnsRecordType.TXT:
                    return new DnsRecordText(name, type, cls, unique, body);

                case DnsRecordType.CNAME:
                case DnsRecordType.PTR:
                    return new DnsRecordAlias(name, type, cls, unique, body, fullPacket);

                case DnsRecordType.SRV:
                    return new DnsRecordServer(name, type, cls, unique, body, fullPacket);

                default:
                    return new DnsRecord(name, type, cls, unique, body);
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="DnsDomainRecordConfiguration"/> class
        /// with the specified values.
        /// </summary>
        /// <param name="type">The DNS record type.</param>
        /// <param name="name">The DNS record name.</param>
        /// <param name="data">The data to associate with the DNS record.</param>
        /// <param name="timeToLive">The time-to-live for the DNS record. If not specified, a provider-specific default value will be used.</param>
        /// <param name="comment">An optional comment to associate with the DNS record.</param>
        /// <param name="priority">The priority of the DNS record. This is only specified for <see cref="DnsRecordType.Mx"/> and <see cref="DnsRecordType.Srv"/> records.</param>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="type"/> is <see langword="null"/>.
        /// <para>-or-</para>
        /// <para>If <paramref name="name"/> is <see langword="null"/>.</para>
        /// <para>-or-</para>
        /// <para>If <paramref name="data"/> is <see langword="null"/>.</para>
        /// </exception>
        /// <exception cref="ArgumentException">
        /// If <paramref name="name"/> is empty.
        /// <para>-or-</para>
        /// <para>If <paramref name="data"/> is empty.</para>
        /// <para>-or-</para>
        /// <para>If <paramref name="priority"/> is specified and <paramref name="type"/> is <em>not</em> <see cref="DnsRecordType.Mx"/> or <see cref="DnsRecordType.Srv"/>.</para>
        /// <para>-or-</para>
        /// <para>If <paramref name="priority"/> is <em>not</em> specified and <paramref name="type"/> is <see cref="DnsRecordType.Mx"/> or <see cref="DnsRecordType.Srv"/>.</para>
        /// </exception>
        /// <exception cref="ArgumentOutOfRangeException">
        /// If <paramref name="timeToLive"/> is negative.
        /// <para>-or-</para>
        /// <para>If <paramref name="priority"/> is less than 0.</para>
        /// </exception>
        public DnsDomainRecordConfiguration(DnsRecordType type, string name, string data, TimeSpan? timeToLive, string comment, int? priority)
        {
            if (type == null)
                throw new ArgumentNullException("type");
            if (name == null)
                throw new ArgumentNullException("name");
            if (data == null)
                throw new ArgumentNullException("data");
            if (string.IsNullOrEmpty(name))
                throw new ArgumentException("name cannot be empty");
            if (string.IsNullOrEmpty(data))
                throw new ArgumentException("data cannot be empty");
            if (timeToLive <= TimeSpan.Zero)
                throw new ArgumentOutOfRangeException("timeToLive cannot be negative or zero");
            if (priority < 0)
                throw new ArgumentOutOfRangeException("priority");

            if (type == DnsRecordType.Mx || type == DnsRecordType.Srv)
            {
                if (!priority.HasValue)
                    throw new ArgumentException("A priority must be specified for MX and SRV records.");
            }
            else
            {
                if (priority.HasValue)
                    throw new ArgumentException(string.Format("A priority cannot be specified for {0} records.", type));
            }

            _name = name;
            _type = type;
            _data = data;
            _comment = comment;
            _priority = priority;
            if (timeToLive != null)
                _timeToLive = (int)timeToLive.Value.TotalSeconds;
        }
Exemplo n.º 43
0
        /// <summary>
        /// Returns a collection of DNS records of a specified
        /// <see cref="DnsRecordType"/>. The collection's data type
        /// is determined by the type of record being sought in the
        /// type argument.
        /// </summary>
        /// <param name="type">A <see cref="DnsRecordType"/> enumeration
        /// value indicating the type of DNS record to get from the list of
        /// all DNS records (available in the <see cref="RawRecords"/>
        /// property.</param>
        /// <returns>an <see cref="ArrayList"/> of one of the types
        /// specified in the <see cref="netlib.Dns.Records"/> namespace based
        /// on the <see cref="DnsRecordType"/> argument representing the
        /// type of DNS record desired.
        /// </returns>
        /// <remarks>
        /// It is recommended that you loop through the results of this
        /// method as follows for maximum convenience:
        /// <code>
        /// foreach (<see cref="netlib.Dns.Records"/> record in obj.GetRecords(<see cref="DnsRecordType"/>))
        /// {
        ///     string s = record.ToString();
        /// }
        /// </code>
        /// The following table indicates the DNS record type you can expect to get
        /// back based on the <see cref="DnsRecordType"/> requested. Any items returning
        /// null are not currently supported.
        /// <list type="table">
        ///     <listheader>
        ///         <term>DnsRecordType enumeration value</term>
        ///         <term>GetRecords() returns</term>
        ///     </listheader>
        ///     <item>
        ///         <term>A</term>
        ///         <description><see cref="netlib.Dns.Records.ARecord"/></description>
        ///     </item>
        ///     <item>
        ///         <term>CNAME</term>
        ///         <description><see cref="netlib.Dns.Records.PTRRecord"/></description>
        ///     </item>
        ///     <item>
        ///         <term>PTR</term>
        ///         <description><see cref="netlib.Dns.Records.PTRRecord"/></description>
        ///     </item>
        ///     <item>
        ///         <term>MX</term>
        ///         <description><see cref="netlib.Dns.Records.MXRecord"/></description>
        ///     </item>
        ///     <item>
        ///         <term>SRV</term>
        ///         <description><see cref="netlib.Dns.Records.SRVRecord"/></description>
        ///     </item>
        ///     <item>
        ///         <term>TEXT</term>
        ///         <description><see cref="netlib.Dns.Records.TXTRecord"/></description>
        ///     </item>
        /// </list>
        /// </remarks>
        public ArrayList GetRecords(DnsRecordType type)
        {
            ArrayList arr = new ArrayList();
            foreach(DnsWrapper dnsentry in rawrecords)
                if (dnsentry.Equals(type))
                    arr.Add(dnsentry.RecordData);

            return arr;
        }
Exemplo n.º 44
0
		public static PhpArray GetRecord(string host, DnsRecordType type)
		{
			PhpException.FunctionNotSupported();
			return null;
		}
Exemplo n.º 45
0
		public static PhpArray GetRecord(string host, DnsRecordType type, out PhpArray authNS, out PhpArray additional)
		{
			PhpException.FunctionNotSupported();
			authNS = null;
			additional = null;
			return null;
		}
Exemplo n.º 46
0
 public DnsQuery GetDnsEntries(string host, DnsRecordType recordType)
 {
     return GetDnsEntries(host, DnsServers.First().ToString(), recordType);
 }
Exemplo n.º 47
0
 public int DeleteDnsZoneRecord(int domainId, string recordName, DnsRecordType recordType, string recordData)
 {
     return ServerController.DeleteDnsZoneRecord(domainId, recordName, recordType, recordData);
 }
Exemplo n.º 48
0
        public static int DeleteDnsZoneRecord(int domainId, string recordName, DnsRecordType recordType,
            string recordData)
        {
            // check account
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
            if (accountCheck < 0) return accountCheck;

            // load domain info
            DomainInfo domain = GetDomain(domainId);

            // check package
            int packageCheck = SecurityContext.CheckPackage(domain.PackageId, DemandPackage.IsActive);
            if (packageCheck < 0) return packageCheck;

            // get DNS service
            DnsZone zoneItem = (DnsZone)PackageController.GetPackageItem(domain.ZoneItemId);

            if (zoneItem == null)
                return 0;

            try
            {
                // place log record
                TaskManager.StartTask("DNS_ZONE", "DELETE_RECORD", domain.DomainName);
                TaskManager.ItemId = domain.ZoneItemId;

                DNSServer dns = new DNSServer();
                ServiceProviderProxy.Init(dns, zoneItem.ServiceId);

                DnsRecord record = GetDnsZoneRecord(domainId, recordName, recordType, recordData); 
                dns.DeleteZoneRecord(zoneItem.Name, record);

                return 0;
            }
            catch (Exception ex)
            {
                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
Exemplo n.º 49
0
 public int UpdateDnsZoneRecord(int domainId,
     string originalRecordName, string originalRecordData,
     string recordName, DnsRecordType recordType, string recordData, int mxPriority, int srvPriority, int srvWeight, int srvPortNumber)
 {
     return ServerController.UpdateDnsZoneRecord(domainId, originalRecordName, originalRecordData,
         recordName, recordType, recordData, mxPriority, srvPriority, srvWeight, srvPortNumber);
 }
Exemplo n.º 50
0
 public DnsRecordServer(string name, DnsRecordType type, DnsRecordClass cls, bool unique, byte[] body, byte[] fullPacket)
     : base(name, type, cls, unique, body)
 {
     using (MemoryStream ms = new MemoryStream(body, false))
     using (BinaryReader br = new BinaryReader(ms))
     {
         _prio = unchecked((ushort)IPAddress.NetworkToHostOrder(br.ReadInt16()));
         _weight = unchecked((ushort)IPAddress.NetworkToHostOrder(br.ReadInt16()));
         _port = unchecked((ushort)IPAddress.NetworkToHostOrder(br.ReadInt16()));
         _name = ReadName(br, fullPacket);
     }
 }
Exemplo n.º 51
0
 public DnsQuery(int transactionId, string hostname, DnsRecordType recordType)
 {
     Header = new DnsQueryHeader(transactionId, 1, DnsQueryType.Query, true);
     Questions = new List<DnsQueryQuestion> { new DnsQueryQuestion(hostname, recordType) };
 }
Exemplo n.º 52
0
        /// <summary>
        /// Provides a default TTLs for records.
        /// </summary>
        /// <param name="recordType"></param>
        /// <returns></returns>
        public string GetDefaultRecordTTL(DnsRecordType recordType)
        {
            string ttl = string.Empty;

            switch (recordType)
            {
                case DnsRecordType.SOA:
                    ttl = SOAMinimumTTL;
                    break;

                case DnsRecordType.NS:
                    ttl = "3600";
                    break;

                default:
                    ttl = "120";
                    break;
            }

            return ttl;
        }
Exemplo n.º 53
0
        public static int UpdateDnsZoneRecord(int domainId,
            string originalRecordName, string originalRecordData,
            string recordName, DnsRecordType recordType, string recordData, int mxPriority)
        {
            // place log record
            DomainInfo domain = GetDomain(domainId);
            TaskManager.StartTask("DNS_ZONE", "UPDATE_RECORD", domain.DomainName);
            TaskManager.ItemId = domain.ZoneItemId;

            try
            {

                // delete existing record
                DeleteDnsZoneRecord(domainId, originalRecordName, recordType, originalRecordData);

                // add new record
                AddDnsZoneRecord(domainId, recordName, recordType, recordData, mxPriority);

                return 0;
            }
            catch (Exception ex)
            {
                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
Exemplo n.º 54
0
        public string ConvertDnsRecordTypeToString(DnsRecordType recordType)
        {
            string result = string.Empty;

            switch (recordType)
            {
                case DnsRecordType.A:
                    result = "A";
                    break;
				
				case DnsRecordType.AAAA:
					result = "AAAA";
					break;
                
                case DnsRecordType.CNAME:
                    result = "CNAME";
                    break;

                case DnsRecordType.MX:
                    result = "MX";
                    break;

                case DnsRecordType.NS:
                    result = "NS";
                    break;

                case DnsRecordType.SOA:
                    result = "SOA";
                    break;

                case DnsRecordType.TXT:
                    result = "TXT";
                    break;

                case DnsRecordType.Other:
                default:
                    throw new NotSupportedException("Record type not supported.");
            }

            return result;
        }
Exemplo n.º 55
0
 public DnsRecordText(string name, DnsRecordType type, DnsRecordClass cls, bool unique, byte[] body)
     : base(name, type, cls, unique, body)
 {
     _text = Encoding.UTF8.GetString(body);
 }
Exemplo n.º 56
0
 public static DnsRecord GetDnsZoneRecord(int domainId, string recordName, DnsRecordType recordType,
     string recordData)
 {
     // get all zone records
     DnsRecord[] records = GetDnsZoneRecords(domainId);
     foreach (DnsRecord record in records)
     {
         if (String.Compare(recordName, record.RecordName, true) == 0
             && String.Compare(recordData, record.RecordData, true) == 0
             && recordType == record.RecordType)
             return record;
     }
     return null;
 }
Exemplo n.º 57
0
        private IEnumerable<DnsRecordInfo> ParseNsLookupResult(string raw, string dnsServer, DnsRecordType recordType)
        {
            var records = new List<DnsRecordInfo>();

            var recordTypePattern = string.Empty;

            switch (recordType)
            {
                case DnsRecordType.NS:
                    {
                        recordTypePattern = NsRecordPattern;
                        break;
                    }
                case DnsRecordType.MX:
                    {
                        recordTypePattern = MxRecordPattern;
                        break;
                    }
            }

            var regex = new Regex(recordTypePattern, RegexOptions.IgnoreCase);

            foreach (Match match in regex.Matches(raw))
            {
                if (match.Groups.Count != 2)
                {
                    continue;
                }

                var dnsRecord = new DnsRecordInfo
                {
                    Value = match.Groups[1].Value != null ? match.Groups[1].Value.Replace("\r\n", "").Replace("\r", "").Replace("\n", "").ToLowerInvariant().Trim() : null,
                    RecordType = recordType,
                    DnsServer = dnsServer
                };

                records.Add(dnsRecord);
            }

            return records;
        }
Exemplo n.º 58
0
        public List<DnsRecordInfo> GetDomainDnsRecords(WindowsServer winServer, string domain, string dnsServer, DnsRecordType recordType, int pause)
        {
            Thread.Sleep(pause);

            //nslookup -type=mx google.com 195.46.39.39
            var command = "nslookup";
            var args = string.Format("-type={0} {1} {2}", recordType, domain, dnsServer);

            // execute system command
            var raw  = string.Empty;
            int triesCount = 0;

            do
            {
                raw = winServer.ExecuteSystemCommand(command, args);
            } 
            while (raw.ToLowerInvariant().Contains(DnsTimeOutMessage) && ++triesCount < DnsTimeOutRetryCount);

            //timeout check 
            if (raw.ToLowerInvariant().Contains(DnsTimeOutMessage))
            {
                return null;
            }

            var records = ParseNsLookupResult(raw, dnsServer, recordType);

            return records.ToList();
        }
Exemplo n.º 59
0
        /// <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);
            }
        }
Exemplo n.º 60
0
 public static IDataReader GetDomainDnsRecords(int domainId, DnsRecordType recordType)
 {
     return SqlHelper.ExecuteReader(
         ConnectionString,
         CommandType.StoredProcedure,
         "GetDomainDnsRecords",
         new SqlParameter("@DomainId", domainId),
         new SqlParameter("@RecordType", recordType)
     );
 }