Beispiel #1
0
        internal static Uri EscapeUri(Uri uri)
        {
#if NETSTANDARD1_0
            return(uri);
#else
            var idn = new System.Globalization.IdnMapping();
            return(new Uri(uri.Scheme + "://" + idn.GetAscii(uri.DnsSafeHost) + uri.PathAndQuery));
#endif
        }
Beispiel #2
0
        /// <summary>
        /// 获取中文域名
        /// 中文域名会进行punycode编码 例如:www.九美.com   System.Web.HttpContext.Current.Request.Url.Host;实际拿到的是 www.xn--sjq221j.com
        /// </summary>
        /// <param name="domain"></param>
        /// <returns></returns>
        public static string GetUnicodeDomain(this string domain)
        {
            if (domain.Contains("xn--"))
            {
                domain = new System.Globalization.IdnMapping().GetUnicode(domain);
            }

            return(domain);
        }
Beispiel #3
0
        /// <summary>
        /// Starts DNS transaction processing.
        /// </summary>
        /// <exception cref="InvalidOperationException">Is raised when this method is called in invalid transaction state.</exception>
        public void Start()
        {
            if (this.State != DNS_ClientTransactionState.WaitingForStart)
            {
                throw new InvalidOperationException("DNS_ClientTransaction.Start may be called only in 'WaitingForStart' transaction state.");
            }

            SetState(DNS_ClientTransactionState.Active);

            // Move processing to thread pool.
            ThreadPool.QueueUserWorkItem(delegate(object state){
                try{
                    // Use DNS cache if allowed.
                    if (Dns_Client.UseDnsCache)
                    {
                        DnsServerResponse response = m_pOwner.Cache.GetFromCache(m_QName, (int)m_QType);
                        if (response != null)
                        {
                            m_pResponse = response;

                            SetState(DNS_ClientTransactionState.Completed);
                            Dispose();

                            return;
                        }
                    }

                    byte[] buffer = new byte[1400];
                    int count     = CreateQuery(buffer, m_ID, m_QName, m_QType, 1);

                    // Send parallel query to DNS server(s).
                    foreach (string server in Dns_Client.DnsServers)
                    {
                        if (Net_Utils.IsIPAddress(server))
                        {
                            IPAddress ip = IPAddress.Parse(server);
                            m_pOwner.Send(ip, buffer, count);
                        }
                    }

                    m_pTimeoutTimer.Start();
                }
                catch {
                    // Check if we have bad unicode qname.
                    try{
                        System.Globalization.IdnMapping ldn = new System.Globalization.IdnMapping();
                        ldn.GetAscii(m_QName);
                    }
                    catch {
                        m_pResponse = new DnsServerResponse(true, m_ID, DNS_RCode.NAME_ERROR, new List <DNS_rr>(), new List <DNS_rr>(), new List <DNS_rr>());
                    }

                    SetState(DNS_ClientTransactionState.Completed);
                }
            });
        }
 /// <summary>
 /// Tests whether a given string is a valid target for targeting as a computer. Will first convert from idn name.
 /// </summary>
 public static bool IsValidComputerTarget(string ComputerName)
 {
     try
     {
         System.Globalization.IdnMapping mapping = new System.Globalization.IdnMapping();
         string temp = mapping.GetAscii(ComputerName);
         return(Regex.IsMatch(temp, RegexHelper.ComputerTarget));
     }
     catch { return(false); }
 }
Beispiel #5
0
        internal static bool GetQName(byte[] reply, ref int offset, ref string name)
        {
            bool retVal = GetQNameI(reply, ref offset, ref name);

            // Convert domain name to unicode. For more info see RFC 5890.
            System.Globalization.IdnMapping ldn = new System.Globalization.IdnMapping();
            name = ldn.GetUnicode(name);

            return(retVal);
        }
                // Examines the domain part of the email and normalizes it.
                static string DomainMapper(Match match)
                {
                    // Use IdnMapping class to convert Unicode domain names.
                    var idn = new System.Globalization.IdnMapping();

                    // Pull out and process domain name (throws ArgumentException on invalid)
                    string domainName = idn.GetAscii(match.Groups[2].Value);

                    return(match.Groups[1].Value + domainName);
                }
Beispiel #7
0
 public void TestAsciiNegative()
 {
     foreach (var entry in Factory.GetDataset())
     {
         if (!entry.GetASCIIResult.Success)
         {
             var map = new System.Globalization.IdnMapping();
             Assert.Throws<ArgumentException>(() => map.GetAscii(entry.Source));
         }
     }
 }
Beispiel #8
0
            private static string DomainMapper(Match match)
            {
                string domainName = match.Groups[2].Value;

#if NET46
                // IdnMapping class with default property values.
                var idn = new System.Globalization.IdnMapping();
                domainName = idn.GetAscii(domainName);
#endif
                return(match.Groups[1].Value + domainName);
            }
 public void TestUnicodeNegative()
 {
     foreach (var entry in Factory.GetDataset())
     {
         if (!entry.GetUnicodeResult.Success)
         {
             var map = new System.Globalization.IdnMapping();
             Assert.Throws <ArgumentException>(() => map.GetUnicode(entry.Source));
         }
     }
 }
 public void TestAsciiPositive()
 {
     foreach (var entry in Factory.GetDataset())
     {
         if (entry.GetASCIIResult.Success)
         {
             var map         = new System.Globalization.IdnMapping();
             var asciiResult = map.GetAscii(entry.Source);
             Assert.Equal(entry.GetASCIIResult.Value, asciiResult, StringComparer.OrdinalIgnoreCase);
         }
     }
 }
Beispiel #11
0
        public async Task GetIdnDomain()
        {
            var idn      = new System.Globalization.IdnMapping();
            var hostname = "åbningstider.info";
            var client   = new LookupClient(NameServer.GooglePublicDns);


            var dnsRes = client.Query($"_acme-challenge.{hostname}", QueryType.TXT);
            var res    = dnsRes.Answers.TxtRecords().FirstOrDefault()?.Text.FirstOrDefault();

            Assert.NotEmpty(res);
        }
Beispiel #12
0
        /// <summary>Converts punycode back to unicode.</summary>
        public static string FromPunycode(string host)
        {
            if (host == null)
            {
                // not suitable.
                return(host);
            }

            System.Globalization.IdnMapping mapper = PunyMapper;

            return(mapper.GetUnicode(host));
        }
Beispiel #13
0
        //代理商建站首页
        public ActionResult indexDl()
        {
            string domian = System.Web.HttpContext.Current.Request.Url.Host;

            if (string.IsNullOrEmpty(domian))
            {
                return(View("PageError", new Return_Msg()
                {
                    Msg = "请求异常(域名不合法)!", code = "500"
                }));
            }

            if (domian.Contains(WebSiteConfig.DzWebSiteDomainExt))
            {
                //表示二级域名
                domian = domian.Replace(WebSiteConfig.DzWebSiteDomainExt, "");
            }
            if (domian.Contains("xn--"))//表示中文域名,会进行punycode编码 例如:www.九美.com   System.Web.HttpContext.Current.Request.Url.Host;实际拿到的是 www.xn--sjq221j.com
            {
                System.Globalization.IdnMapping idn = new System.Globalization.IdnMapping();

                domian = idn.GetUnicode(domian);
            }
            AgentWebSiteInfo agentWebSiteInfo = AgentWebSiteInfoBLL.SingleModel.GetModelByDomian(domian);

            if (agentWebSiteInfo == null)
            {
                return(View("PageError", new Return_Msg()
                {
                    Msg = "请求异常(没有数据)!", code = "500"
                }));
            }
            if (agentWebSiteInfo.webState == -1)
            {
                return(View("PageError", new Return_Msg()
                {
                    Msg = "网站已被停用(请联系客户)!", code = "403"
                }));
            }

            if (!string.IsNullOrEmpty(agentWebSiteInfo.seoConfig))
            {
                agentWebSiteInfo.seoConfigModel = JsonConvert.DeserializeObject <SeoConfigModel>(agentWebSiteInfo.seoConfig);
            }
            if (!string.IsNullOrEmpty(agentWebSiteInfo.pageMsgConfig))
            {
                agentWebSiteInfo.pageMsgConfigModel = JsonConvert.DeserializeObject <PageMsgConfigModel>(agentWebSiteInfo.pageMsgConfig);
            }



            return(View(agentWebSiteInfo));
        }
Beispiel #14
0
 public void TestAsciiPositive()
 {
     foreach (var entry in Factory.GetDataset())
     {
         if (entry.GetASCIIResult.Success)
         {
             var map = new System.Globalization.IdnMapping();
             var asciiResult = map.GetAscii(entry.Source);
             Assert.Equal(entry.GetASCIIResult.Value, asciiResult, StringComparer.OrdinalIgnoreCase);
         }
     }
 }
Beispiel #15
0
        /// <summary>
        /// For the given set of options get a new CertRequestConfig to store
        /// </summary>
        /// <returns></returns>
        private ManagedSite GetUpdatedManagedSiteSettings()
        {
            var item = SelectedItem;
            // item.DomainOptions = new ObservableCollection<DomainOption>();
            var config = item.RequestConfig;

            // RefreshDomainOptionSettingsFromUI();
            var primaryDomain = item.DomainOptions.FirstOrDefault(d => d.IsPrimaryDomain == true);

            //if no primary domain need to go back and select one
            if (primaryDomain == null)
            {
                throw new ArgumentException("Primary subject domain must be set.");
            }

            var _idnMapping = new System.Globalization.IdnMapping();

            config.PrimaryDomain = _idnMapping.GetAscii(primaryDomain.Domain); // ACME service requires international domain names in ascii mode

            //apply remaining selected domains as subject alternative names
            config.SubjectAlternativeNames =
                item.DomainOptions.Where(dm => dm.IsSelected == true)
                .Select(i => i.Domain)
                .ToArray();

            //config.PerformChallengeFileCopy = true;
            //config.PerformExtensionlessConfigChecks = !chkSkipConfigCheck.Checked;
            config.PerformAutoConfig = true;

            // config.EnableFailureNotifications = chkEnableNotifications.Checked;

            //determine if this site has an existing entry in Managed Sites, if so use that, otherwise start a new one

            if (SelectedItem.Id == null)
            {
                var siteInfo = SelectedWebSite;
                //if siteInfo null we need to go back and select a site

                item.Id      = Guid.NewGuid().ToString() + ":" + siteInfo.SiteId;
                item.GroupId = siteInfo.SiteId;

                config.WebsiteRootPath = Environment.ExpandEnvironmentVariables(siteInfo.PhysicalPath);
            }

            item.ItemType = ManagedItemType.SSL_LetsEncrypt_LocalIIS;

            //store domain options settings and request config for this site so we can replay for automated renewal

            //managedSite.RequestConfig = config;

            return(item);
        }
Beispiel #16
0
        public void TestAsciiPositive()
        {
            foreach (var entry in Factory.GetDataset())
            {
                if (entry.GetASCIIResult.Success)
                {
                    var map         = new System.Globalization.IdnMapping();
                    var asciiResult = map.GetAscii(entry.Source);

                    CompareResult(entry.GetASCIIResult.Value, asciiResult, StringComparer.OrdinalIgnoreCase, "Error on line number " + entry.LineNumber);
                }
            }
        }
Beispiel #17
0
        internal static Uri EscapeUri(Uri uri)
        {
            if (uri == null)
            {
                throw new ArgumentNullException(nameof(uri));
            }

#if NETSTANDARD1_0
            return(uri);
#else
            var idn = new System.Globalization.IdnMapping();
            return(new Uri(uri.Scheme + "://" + idn.GetAscii(uri.Authority) + uri.PathAndQuery + uri.Fragment));
#endif
        }
        /// <summary>
        /// Remove a override for the given hostname:port.
        /// </summary>
        /// <param name="url"></param>
        public void ClearValidityOverride(Uri url)
        {
            if (url == null)
            {
                throw new ArgumentNullException("url");
            }

            var mapping = new System.Globalization.IdnMapping();

            using (var aHostName = new nsACString(url.Scheme != "all" ? mapping.GetAscii(url.Host) : url.OriginalString))
            {
                Instance.ClearValidityOverride(aHostName, url.Port);
            }
        }
        public bool HasMatchingOverride(Uri url, Certificate cert)
        {
            if (url == null)
            {
                throw new ArgumentNullException("url");
            }

            var mapping = new System.Globalization.IdnMapping();

            using (var aHostName = new nsACString(mapping.GetAscii(url.Host)))
            {
                uint flags  = 0;
                bool isTemp = false;
                return(Instance.HasMatchingOverride(aHostName, url.Port, cert._cert.Instance, ref flags, ref isTemp));
            }
        }
Beispiel #20
0
        public async Task <IActionResult> UploadDomains()
        {
            HashSet <string> domains = null;
            var file = Request.Form.Files[0];

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            using (var ms = new MemoryStream())
            {
                file.CopyTo(ms);
                if (file.FileName.EndsWith(".xlsx"))
                {
                    using (var xlReader = new XLWorkbook(ms, XLEventTracking.Disabled))
                    {
                        var cells = xlReader.Worksheets.First().CellsUsed().Select(x => x.GetString() ?? "")
                                    .Where(x => !string.IsNullOrWhiteSpace(x))
                                    .Where(x => Uri.CheckHostName(x) == UriHostNameType.Dns)
                                    .Select(x => x.Trim());
                        domains = new HashSet <string>(cells);
                    }
                }
                else if (file.FileName.EndsWith(".csv") || file.FileName.EndsWith(".txt"))
                {
                    var lines = Encoding.GetEncoding("windows-1251").GetString(ms.ToArray()).Split(new char[] { '\r', '\n', ';', ',' }, StringSplitOptions.RemoveEmptyEntries);
                    domains = new HashSet <string>(lines.Where(x => !string.IsNullOrWhiteSpace(x) && Uri.CheckHostName(x) == UriHostNameType.Dns).Select(x => x.Trim()));
                }
            }
            var validDomains = new List <string>();
            var mapping      = new System.Globalization.IdnMapping();

            foreach (var domain in domains.Where(x => x.Contains('.')))
            {
                try
                {
                    var entries = await System.Net.Dns.GetHostEntryAsync(mapping.GetAscii(domain));

                    if (entries != null && (!string.IsNullOrWhiteSpace(entries.HostName)))
                    {
                        validDomains.Add(domain);
                    }
                }
                catch { }
            }
            var invalidDomains = domains.Except(validDomains).ToList();
            await Task.FromResult(0);

            return(new JsonResult(new { success = validDomains, error = invalidDomains }));
        }
Beispiel #21
0
        private static string DomainMapper(System.Text.RegularExpressions.Match match)
        {
            // IdnMapping class with default property values.
            System.Globalization.IdnMapping idn = new System.Globalization.IdnMapping();

            string domainName = match.Groups[2].Value;

            try
            {
                domainName = idn.GetAscii(domainName);
            }
            catch (ArgumentException)
            {
                EmailInvalido = true;
            }
            return(match.Groups[1].Value + domainName);
        }
        public static bool IsValidEmail(string email)
        {
            if (string.IsNullOrWhiteSpace(email))
            {
                return(false);
            }

            try
            {
                // Normalize the domain
                email = Regex.Replace(email, @"(@)(.+)$", DomainMapper,
                                      RegexOptions.None, TimeSpan.FromMilliseconds(200));

                // Examines the domain part of the email and normalizes it.
                string DomainMapper(Match match)
                {
                    // Use IdnMapping class to convert Unicode domain names.
                    var idn = new System.Globalization.IdnMapping();

                    // Pull out and process domain name (throws ArgumentException on invalid)
                    var domainName = idn.GetAscii(match.Groups[2].Value);

                    return(match.Groups[1].Value + domainName);
                }
            }
            catch (RegexMatchTimeoutException e)
            {
                return(false);
            }
            catch (ArgumentException e)
            {
                return(false);
            }

            try
            {
                return(Regex.IsMatch(email,
                                     @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
                                     @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-0-9a-z]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
                                     RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250)));
            }
            catch (RegexMatchTimeoutException)
            {
                return(false);
            }
        }
Beispiel #23
0
        public bool IsValidEmail(string email)
        {
            if (string.IsNullOrWhiteSpace(email))
            {
                return(false);
            }

            try
            {
                // Normalize the domain
                email = Regex.Replace(email, @"(@)(.+)$", DomainMapper,
                                      RegexOptions.None, TimeSpan.FromMilliseconds(200));

                // Examines the domain part of the email and normalizes it.
                string DomainMapper(Match match)
                {
                    // Use IdnMapping class to convert Unicode domain names.
                    var idn = new System.Globalization.IdnMapping();

                    // Pull out and process domain name (throws ArgumentException on invalid)
                    string domainName = idn.GetAscii(match.Groups[2].Value);

                    return(match.Groups[1].Value + domainName);
                }
            }
            catch (RegexMatchTimeoutException e)
            {
                return(false);
            }
            catch (ArgumentException e)
            {
                return(false);
            }

            try
            {
                return(Regex.IsMatch(email,
                                     @"^[^@\s]+@[^@\s]+\.[^@\s]+$",
                                     RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250)));
            }
            catch (RegexMatchTimeoutException)
            {
                return(false);
            }
        }
        /// <summary>
        ///  The given cert should always be accepted for the given hostname:port,
        ///  regardless of errors verifying the cert.
        ///  Host:Port is a primary key, only one entry per host:port can exist.
        /// </summary>
        /// <param name="url"></param>
        /// <param name="cert">The cert that should always be accepted</param>
        /// <param name="flags">The errors we want to be overriden.</param>
        public void RememberValidityOverride(Uri url, Certificate cert, CertOverride flags, bool temporary)
        {
            if (url == null)
            {
                throw new ArgumentNullException("url");
            }
            if (cert == null)
            {
                throw new ArgumentNullException("cert");
            }

            var mapping = new System.Globalization.IdnMapping();

            using (var aHostName = new nsACString(mapping.GetAscii(url.Host)))
            {
                Instance.RememberValidityOverride(aHostName, url.Port, cert._cert.Instance, (uint)flags, temporary);
            }
        }
Beispiel #25
0
            private static string DomainMapper(Match match)
            {
                // IdnMapping class with default property values.
                var idn = new System.Globalization.IdnMapping();

                string domainName = match.Groups[2].Value;

                //try
                //{
                domainName = idn.GetAscii(domainName);
                //}
                //catch (ArgumentException)
                //{
                //    invalid = true;
                //}

                return(match.Groups[1].Value + domainName);
            }
Beispiel #26
0
        public void TestUnicodePositive()
        {
            foreach (var entry in Factory.GetDataset())
            {
                if (entry.GetUnicodeResult.Success)
                {
                    try
                    {
                        var map = new System.Globalization.IdnMapping { UseStd3AsciiRules = true, AllowUnassigned = true };
                        var unicodeResult = map.GetUnicode(entry.Source);

                        Assert.Equal(entry.GetUnicodeResult.Value, unicodeResult, StringComparer.OrdinalIgnoreCase);
                    }
                    catch (ArgumentException)
                    {
                        Assert.Equal(entry.GetUnicodeResult.Value, entry.Source, StringComparer.OrdinalIgnoreCase);
                    }
                }
            }
        }
        public void TestUnicodePositive()
        {
            foreach (var entry in Factory.GetDataset())
            {
                if (entry.GetUnicodeResult.Success)
                {
                    try
                    {
                        var map = new System.Globalization.IdnMapping {
                            UseStd3AsciiRules = true, AllowUnassigned = true
                        };
                        var unicodeResult = map.GetUnicode(entry.Source);

                        Assert.Equal(entry.GetUnicodeResult.Value, unicodeResult, StringComparer.OrdinalIgnoreCase);
                    }
                    catch (ArgumentException)
                    {
                        Assert.Equal(entry.GetUnicodeResult.Value, entry.Source, StringComparer.OrdinalIgnoreCase);
                    }
                }
            }
        }
Beispiel #28
0
        /// <summary>
        /// For the given set of options get a new CertRequestConfig to store
        /// </summary>
        /// <returns></returns>
        public void UpdateManagedSiteSettings()
        {
            var item          = SelectedItem;
            var config        = item.RequestConfig;
            var primaryDomain = item.DomainOptions.FirstOrDefault(d => d.IsPrimaryDomain == true);

            //if no primary domain need to go back and select one
            if (primaryDomain == null)
            {
                throw new ArgumentException("Primary subject domain must be set.");
            }

            var _idnMapping = new System.Globalization.IdnMapping();

            config.PrimaryDomain = _idnMapping.GetAscii(primaryDomain.Domain); // ACME service requires international domain names in ascii mode

            //apply remaining selected domains as subject alternative names
            config.SubjectAlternativeNames =
                item.DomainOptions.Where(dm => dm.IsSelected == true)
                .Select(i => i.Domain)
                .ToArray();

            // TODO: config.EnableFailureNotifications = chkEnableNotifications.Checked;

            //determine if this site has an existing entry in Managed Sites, if so use that, otherwise start a new one
            if (SelectedItem.Id == null)
            {
                var siteInfo = SelectedWebSite;
                //if siteInfo null we need to go back and select a site

                item.Id      = Guid.NewGuid().ToString() + ":" + siteInfo.SiteId;
                item.GroupId = siteInfo.SiteId;
            }

            item.ItemType = ManagedItemType.SSL_LetsEncrypt_LocalIIS;
        }
Beispiel #29
0
        /// <summary>
        /// Creates binary query.
        /// </summary>
        /// <param name="buffer">Buffer where to store query.</param>
        /// <param name="ID">Query ID.</param>
        /// <param name="qname">Query text.</param>
        /// <param name="qtype">Query type.</param>
        /// <param name="qclass">Query class.</param>
        /// <returns>Returns number of bytes stored to <b>buffer</b>.</returns>
        private static int CreateQuery(byte[] buffer, int ID, string qname, DnsRecordType qtype, int qclass)
        {
            // DNS协议参考http://www.cnblogs.com/topdog/archive/2011/11/15/2250185.html

            #region DNS协议说明

            /*
             *
             * DNS结构:分为5个部分,分别为Header、Question、Answer、Authority、Additional。
             +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
             |                    Header                     |
             +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
             |                   Question                    |
             +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
             |                    Answer                     |
             +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
             |                   Authority                   |
             +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
             |                   Additional                  |
             +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
             | 其中头部的大小是固定的为12字节。这5个部分不是全部都是必须的,在向服务器发送查询请求的时候,只需要前2个。回复的时候也不一定包含5个(按查询的内容和返回的信息而定)。
             |
             |
             |
             | Header 部分:
             |                            1  1  1  1  1  1
             | 0  1  2  3  4  5  6  7  8  9  0  1  2  3  4  5
             +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
             |                      ID                       |
             +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
             |QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |
             +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
             |                    QDCOUNT                    |
             +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
             |                    ANCOUNT                    |
             +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
             |                    NSCOUNT                    |
             +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
             |                    ARCOUNT                    |
             +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
             |
             | ID:长度为16位,是一个用户发送查询的时候定义的随机数,当服务器返回结果的时候,返回包的ID与用户发送的一致。
             |
             | QR:长度1位,值0是请求,1是应答。
             |
             | Opcode:长度4位,值0是标准查询,1是反向查询,2死服务器状态查询。
             |
             | AA:长度1位,授权应答(Authoritative Answer) - 这个比特位在应答的时候才有意义,指出给出应答的服务器是查询域名的授权解析服务器。
             |
             | TC:长度1位,截断(TrunCation) - 用来指出报文比允许的长度还要长,导致被截断。
             |
             | RD:长度1位,期望递归(Recursion Desired) - 这个比特位被请求设置,应答的时候使用的相同的值返回。如果设置了RD,就建议域名服务器进行递归解析,递归查询的支持是可选的。
             |
             | RA:长度1位,支持递归(Recursion Available) - 这个比特位在应答中设置或取消,用来代表服务器是否支持递归查询。
             |
             | Z:长度3位,保留值,值为0.
             |
             | RCode:长度4位,应答码,类似http的stateCode一样,值0没有错误、1格式错误、2服务器错误、3名字错误、4服务器不支持、5拒绝。
             |
             | QDCount:长度16位,报文请求段中的问题记录数。
             |
             | ANCount:长度16位,报文回答段中的回答记录数。
             |
             | NSCOUNT :长度16位,报文授权段中的授权记录数。
             |
             | ARCOUNT :长度16位,报文附加段中的附加记录数。
             |
             |
             | Question 部分:这部分的内容是你要查询的内容。
             |
             |                               1  1  1  1  1  1
             | 0  1  2  3  4  5  6  7  8  9  0  1  2  3  4  5
             +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
             |                                               |
             | /                     QNAME                     /
             | /                                               /
             +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
             |                     QTYPE                     |
             +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
             |                     QCLASS                    |
             +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
             |
             | QName:是你要查询的域名,属于不定长字段。他的格式是“长度(1字节)+N字节内容
             | (N由前面的长度定义)+~~~+长度0。以一个长度单位N为开始,然后连续的N字节为
             | 其内容,然后又是一个N2长度的一字节,然后后面又是N2个字节内容,直到遇到长度
             | 为0的长度标记。记录类型:
             |
             | A=0x01, //指定计算机 IP 地址。
             | NS=0x02, //指定用于命名区域的 DNS 名称服务器。
             | MD=0x03, //指定邮件接收站(此类型已经过时了,使用MX代替)
             | MF=0x04, //指定邮件中转站(此类型已经过时了,使用MX代替)
             | CNAME=0x05, //指定用于别名的规范名称。
             | SOA=0x06, //指定用于 DNS 区域的“起始授权机构”。
             | MB=0x07, //指定邮箱域名。
             | MG=0x08, //指定邮件组成员。
             | MR=0x09, //指定邮件重命名域名。
             | NULL=0x0A, //指定空的资源记录
             | WKS=0x0B, //描述已知服务。
             | PTR=0x0C, //如果查询是 IP 地址,则指定计算机名;否则指定指向其它信息的指针。
             | HINFO=0x0D, //指定计算机 CPU 以及操作系统类型。
             | MINFO=0x0E, //指定邮箱或邮件列表信息。
             | MX=0x0F, //指定邮件交换器。
             | TXT=0x10, //指定文本信息。
             | UINFO=0x64, //指定用户信息。
             | UID=0x65, //指定用户标识符。
             | GID=0x66, //指定组名的组标识符。
             | ANY=0xFF //指定所有数据类型。
             |
             */
            #endregion



            //--------- Header 部分 -----------------------------------//
            buffer[0]  = (byte)(ID >> 8);
            buffer[1]  = (byte)(ID & 0xFF);
            buffer[2]  = (byte)1;
            buffer[3]  = (byte)0;
            buffer[4]  = (byte)0;
            buffer[5]  = (byte)1;
            buffer[6]  = (byte)0;
            buffer[7]  = (byte)0;
            buffer[8]  = (byte)0;
            buffer[9]  = (byte)0;
            buffer[10] = (byte)0;
            buffer[11] = (byte)0;
            //---------------------------------------------------------//


            //----Create query ------------------------------------//

            // Convert unicode domain name. For more info see RFC 5890.
            System.Globalization.IdnMapping ldn = new System.Globalization.IdnMapping();
            qname = ldn.GetAscii(qname);

            string[] labels   = qname.Split(new char[] { '.' });
            int      position = 12;

            // Copy all domain parts(labels) to query
            // eg. lumisoft.ee = 2 labels, lumisoft and ee.
            // format = label.length + label(bytes)
            foreach (string label in labels)
            {
                // convert label string to byte array
                byte[] b = Encoding.ASCII.GetBytes(label);

                // add label lenght to query
                buffer[position++] = (byte)(b.Length);
                b.CopyTo(buffer, position);

                // Move position by label length
                position += b.Length;
            }

            // Terminate domain (see note above)
            buffer[position++] = (byte)0;

            // Set QTYPE
            buffer[position++] = (byte)0;
            buffer[position++] = (byte)qtype;

            // Set QCLASS
            buffer[position++] = (byte)0;
            buffer[position++] = (byte)qclass;
            //-------------------------------------------------------//

            return(position);
        }
Beispiel #30
0
		/// <summary>
		/// Creates binary query.
		/// </summary>
        /// <param name="buffer">Buffer where to store query.</param>
		/// <param name="ID">Query ID.</param>
		/// <param name="qname">Query text.</param>
		/// <param name="qtype">Query type.</param>
		/// <param name="qclass">Query class.</param>
		/// <returns>Returns number of bytes stored to <b>buffer</b>.</returns>
		private int CreateQuery(byte[] buffer,int ID,string qname,DNS_QType qtype,int qclass)
		{
			//---- Create header --------------------------------------------//
			// Header is first 12 bytes of query

			/* 4.1.1. Header section format
										  1  1  1  1  1  1
			0  1  2  3  4  5  6  7  8  9  0  1  2  3  4  5
			+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
			|                      ID                       |
			+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
			|QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |
			+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
			|                    QDCOUNT                    |
			+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
			|                    ANCOUNT                    |
			+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
			|                    NSCOUNT                    |
			+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
			|                    ARCOUNT                    |
			+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
			
			QR  A one bit field that specifies whether this message is a
                query (0), or a response (1).
				
			OPCODE          A four bit field that specifies kind of query in this
                message.  This value is set by the originator of a query
                and copied into the response.  The values are:

                0               a standard query (QUERY)

                1               an inverse query (IQUERY)

                2               a server status request (STATUS)
				
			*/

			//--------- Header part -----------------------------------//
			buffer[0]  = (byte) (ID >> 8); buffer[1]  = (byte) (ID & 0xFF);
			buffer[2]  = (byte) 1;         buffer[3]  = (byte) 0;
			buffer[4]  = (byte) 0;         buffer[5]  = (byte) 1;
			buffer[6]  = (byte) 0;         buffer[7]  = (byte) 0;
			buffer[8]  = (byte) 0;         buffer[9]  = (byte) 0;
			buffer[10] = (byte) 0;         buffer[11] = (byte) 0;
			//---------------------------------------------------------//

			//---- End of header --------------------------------------------//


			//----Create query ------------------------------------//

			/* 	Rfc 1035 4.1.2. Question section format
											  1  1  1  1  1  1
			0  1  2  3  4  5  6  7  8  9  0  1  2  3  4  5
			+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
			|                                               |
			/                     QNAME                     /
			/                                               /
			+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
			|                     QTYPE                     |
			+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
			|                     QCLASS                    |
			+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
			
			QNAME
				a domain name represented as a sequence of labels, where
				each label consists of a length octet followed by that
				number of octets.  The domain name terminates with the
				zero length octet for the null label of the root.  Note
				that this field may be an odd number of octets; no
				padding is used.
			*/

            // Convert unicode domain name. For more info see RFC 5890.
            System.Globalization.IdnMapping ldn = new System.Globalization.IdnMapping();
            qname = ldn.GetAscii(qname);

			string[] labels = qname.Split(new char[] {'.'});
			int position = 12;
					
			// Copy all domain parts(labels) to query
			// eg. lumisoft.ee = 2 labels, lumisoft and ee.
			// format = label.length + label(bytes)
			foreach(string label in labels){
                // convert label string to byte array
                byte[] b = Encoding.ASCII.GetBytes(label);

				// add label lenght to query
				buffer[position++] = (byte)(b.Length);
                b.CopyTo(buffer,position);

				// Move position by label length
				position += b.Length;
			}

			// Terminate domain (see note above)
			buffer[position++] = (byte) 0; 
			
			// Set QTYPE 
			buffer[position++] = (byte) 0;
			buffer[position++] = (byte)qtype;
				
			// Set QCLASS
			buffer[position++] = (byte) 0;
			buffer[position++] = (byte)qclass;
			//-------------------------------------------------------//
			
			return position;
		}
Beispiel #31
0
        /// <summary>
        /// Creates binary query.
        /// </summary>
        /// <param name="buffer">Buffer where to store query.</param>
        /// <param name="ID">Query ID.</param>
        /// <param name="qname">Query text.</param>
        /// <param name="qtype">Query type.</param>
        /// <param name="qclass">Query class.</param>
        /// <returns>Returns number of bytes stored to <b>buffer</b>.</returns>
        private int CreateQuery(byte[] buffer, int ID, string qname, DNS_QType qtype, int qclass)
        {
            //---- Create header --------------------------------------------//
            // Header is first 12 bytes of query

            /* 4.1.1. Header section format
             *                                                                    1  1  1  1  1  1
             *          0  1  2  3  4  5  6  7  8  9  0  1  2  3  4  5
             +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
             |                      ID                       |
             +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
             |QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |
             +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
             |                    QDCOUNT                    |
             +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
             |                    ANCOUNT                    |
             +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
             |                    NSCOUNT                    |
             +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
             |                    ARCOUNT                    |
             +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
             |
             |          QR  A one bit field that specifies whether this message is a
             |  query (0), or a response (1).
             |
             |          OPCODE          A four bit field that specifies kind of query in this
             |  message.  This value is set by the originator of a query
             |  and copied into the response.  The values are:
             |
             |  0               a standard query (QUERY)
             |
             |  1               an inverse query (IQUERY)
             |
             |  2               a server status request (STATUS)
             |
             */

            //--------- Header part -----------------------------------//
            buffer[0]  = (byte)(ID >> 8); buffer[1] = (byte)(ID & 0xFF);
            buffer[2]  = (byte)1; buffer[3] = (byte)0;
            buffer[4]  = (byte)0; buffer[5] = (byte)1;
            buffer[6]  = (byte)0; buffer[7] = (byte)0;
            buffer[8]  = (byte)0; buffer[9] = (byte)0;
            buffer[10] = (byte)0; buffer[11] = (byte)0;
            //---------------------------------------------------------//

            //---- End of header --------------------------------------------//


            //----Create query ------------------------------------//

            /*  Rfc 1035 4.1.2. Question section format
             *                                                                            1  1  1  1  1  1
             *          0  1  2  3  4  5  6  7  8  9  0  1  2  3  4  5
             +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
             |                                               |
             |          /                     QNAME                     /
             |          /                                               /
             +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
             |                     QTYPE                     |
             +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
             |                     QCLASS                    |
             +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
             |
             |          QNAME
             |                  a domain name represented as a sequence of labels, where
             |                  each label consists of a length octet followed by that
             |                  number of octets.  The domain name terminates with the
             |                  zero length octet for the null label of the root.  Note
             |                  that this field may be an odd number of octets; no
             |                  padding is used.
             */

            // Convert unicode domain name. For more info see RFC 5890.
            System.Globalization.IdnMapping ldn = new System.Globalization.IdnMapping();
            qname = ldn.GetAscii(qname);

            string[] labels   = qname.Split(new char[] { '.' });
            int      position = 12;

            // Copy all domain parts(labels) to query
            // eg. lumisoft.ee = 2 labels, lumisoft and ee.
            // format = label.length + label(bytes)
            foreach (string label in labels)
            {
                // convert label string to byte array
                byte[] b = Encoding.ASCII.GetBytes(label);

                // add label lenght to query
                buffer[position++] = (byte)(b.Length);
                b.CopyTo(buffer, position);

                // Move position by label length
                position += b.Length;
            }

            // Terminate domain (see note above)
            buffer[position++] = (byte)0;

            // Set QTYPE
            buffer[position++] = (byte)0;
            buffer[position++] = (byte)qtype;

            // Set QCLASS
            buffer[position++] = (byte)0;
            buffer[position++] = (byte)qclass;
            //-------------------------------------------------------//

            return(position);
        }
Beispiel #32
0
            private static string DomainMapper(Match match)
            {
                // IdnMapping class with default property values.
                var idn = new System.Globalization.IdnMapping();

                string domainName = match.Groups[2].Value;
                //try
                //{
                    domainName = idn.GetAscii(domainName);
                //}
                //catch (ArgumentException)
                //{
                //    invalid = true;
                //}

                return match.Groups[1].Value + domainName;
            }
        /// <summary>
        /// Starts DNS transaction processing.
        /// </summary>
        /// <exception cref="InvalidOperationException">Is raised when this method is called in invalid transaction state.</exception>
        public void Start()
        {   
            if(this.State != DNS_ClientTransactionState.WaitingForStart){
                throw new InvalidOperationException("DNS_ClientTransaction.Start may be called only in 'WaitingForStart' transaction state.");
            }

            SetState(DNS_ClientTransactionState.Active);

            // Move processing to thread pool.
            ThreadPool.QueueUserWorkItem(delegate(object state){
                try{
                    // Use DNS cache if allowed.
			        if(Dns_Client.UseDnsCache){ 
	                    DnsServerResponse response = m_pOwner.Cache.GetFromCache(m_QName,(int)m_QType);
				        if(response != null){
					        m_pResponse = response;

                            SetState(DNS_ClientTransactionState.Completed);
                            Dispose();

                            return;
				        }
			        }   

                    byte[] buffer = new byte[1400];
                    int count = CreateQuery(buffer,m_ID,m_QName,m_QType,1);
  
                    // Send parallel query to DNS server(s).
                    foreach(string server in Dns_Client.DnsServers){
                        if(Net_Utils.IsIPAddress(server)){
                            IPAddress ip = IPAddress.Parse(server);
                            m_pOwner.Send(ip,buffer,count);
                        }
                    }

                    m_pTimeoutTimer.Start();
                }
                catch{
                    // Check if we have bad unicode qname.
                    try{
                        System.Globalization.IdnMapping ldn = new System.Globalization.IdnMapping();
                        ldn.GetAscii(m_QName);
                    }
                    catch{
                        m_pResponse = new DnsServerResponse(true,m_ID,DNS_RCode.NAME_ERROR,new List<DNS_rr>(),new List<DNS_rr>(),new List<DNS_rr>());
                    }

                    SetState(DNS_ClientTransactionState.Completed);
                }
            });
        }
Beispiel #34
0
        public override RouteData GetRouteData(HttpContextBase httpContext)
        {
            domainRegex = CreateRegex(Domain);
            pathRegex = CreateRegex(Url);
            string requestDomain = httpContext.Request.Headers["host"];//中国域名会编码,使用IdnMapping解码
            if (!string.IsNullOrEmpty(requestDomain))
            {
                if (requestDomain.IndexOf(":") > 0)
                {
                    requestDomain = requestDomain.Substring(0, requestDomain.IndexOf(":"));
                }
            }
            else
            {
                requestDomain = httpContext.Request.Url.Host;
            }
            string requestPath = httpContext.Request.AppRelativeCurrentExecutionFilePath.Substring(2) + httpContext.Request.PathInfo;

            requestDomain = new System.Globalization.IdnMapping().GetUnicode(requestDomain);//中文域名解码

            Match domainMatch = domainRegex.Match(requestDomain);
            Match pathMatch = pathRegex.Match(requestPath);

            RouteData data = null;
            if (domainMatch.Success && pathMatch.Success)
            {
                data = new RouteData(this, RouteHandler);
                if (Defaults != null)
                {
                    foreach (KeyValuePair<string, object> item in Defaults)
                    {
                        data.Values[item.Key] = item.Value;
                    }
                }
                for (int i = 1; i < domainMatch.Groups.Count; i++)
                {
                    Group group = domainMatch.Groups[i];
                    if (group.Success)
                    {
                        string key = domainRegex.GroupNameFromNumber(i);

                        if (!string.IsNullOrEmpty(key) && !char.IsNumber(key, 0))
                        {
                            if (!string.IsNullOrEmpty(group.Value))
                            {
                                data.Values[key] = group.Value;
                            }
                        }
                    }
                }

                for (int i = 1; i < pathMatch.Groups.Count; i++)
                {
                    Group group = pathMatch.Groups[i];
                    if (group.Success)
                    {
                        string key = pathRegex.GroupNameFromNumber(i);

                        if (!string.IsNullOrEmpty(key) && !char.IsNumber(key, 0))
                        {
                            if (!string.IsNullOrEmpty(group.Value))
                            {
                                data.Values[key] = group.Value;
                            }
                        }
                    }
                }

                foreach (var item in this.DataTokens)
                {
                    data.DataTokens.Add(item.Key, item.Value);
                }
            }

            return data;
        }
Beispiel #35
0
        public override RouteData GetRouteData(HttpContextBase httpContext)
        {
            domainRegex = CreateRegex(Domain);
            pathRegex   = CreateRegex(Url);
            string requestDomain = httpContext.Request.Headers["host"];//中国域名会编码,使用IdnMapping解码

            if (!string.IsNullOrEmpty(requestDomain))
            {
                if (requestDomain.IndexOf(":") > 0)
                {
                    requestDomain = requestDomain.Substring(0, requestDomain.IndexOf(":"));
                }
            }
            else
            {
                requestDomain = httpContext.Request.Url.Host;
            }
            string requestPath = httpContext.Request.AppRelativeCurrentExecutionFilePath.Substring(2) + httpContext.Request.PathInfo;

            requestDomain = new System.Globalization.IdnMapping().GetUnicode(requestDomain);//中文域名解码

            Match domainMatch = domainRegex.Match(requestDomain);
            Match pathMatch   = pathRegex.Match(requestPath);

            RouteData data = null;

            if (domainMatch.Success && pathMatch.Success)
            {
                data = new RouteData(this, RouteHandler);
                if (Defaults != null)
                {
                    foreach (KeyValuePair <string, object> item in Defaults)
                    {
                        data.Values[item.Key] = item.Value;
                    }
                }
                for (int i = 1; i < domainMatch.Groups.Count; i++)
                {
                    Group group = domainMatch.Groups[i];
                    if (group.Success)
                    {
                        string key = domainRegex.GroupNameFromNumber(i);


                        if (!string.IsNullOrEmpty(key) && !char.IsNumber(key, 0))
                        {
                            if (!string.IsNullOrEmpty(group.Value))
                            {
                                data.Values[key] = group.Value;
                            }
                        }
                    }
                }


                for (int i = 1; i < pathMatch.Groups.Count; i++)
                {
                    Group group = pathMatch.Groups[i];
                    if (group.Success)
                    {
                        string key = pathRegex.GroupNameFromNumber(i);


                        if (!string.IsNullOrEmpty(key) && !char.IsNumber(key, 0))
                        {
                            if (!string.IsNullOrEmpty(group.Value))
                            {
                                data.Values[key] = group.Value;
                            }
                        }
                    }
                }

                foreach (var item in this.DataTokens)
                {
                    data.DataTokens.Add(item.Key, item.Value);
                }
            }


            return(data);
        }
Beispiel #36
0
        internal static bool GetQName(byte[] reply,ref int offset,ref string name)
		{
            bool retVal = GetQNameI(reply,ref offset,ref name);

            // Convert domain name to unicode. For more info see RFC 5890.
            System.Globalization.IdnMapping ldn = new System.Globalization.IdnMapping();
            name = ldn.GetUnicode(name);

            return retVal;
        }