Ejemplo n.º 1
0
        public void FullyQualifiedDomainNameVsIndividualLabels()
        {
            var idn = new IdnMapping();

            // ASCII only code points
            Assert.Equal("\u0061\u0062\u0063", idn.GetAscii("\u0061\u0062\u0063"));
            // non-ASCII only code points
            Assert.Equal("xn--d9juau41awczczp", idn.GetAscii("\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067"));
            // ASCII and non-ASCII code points
            Assert.Equal("xn--de-jg4avhby1noc0d", idn.GetAscii("\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0"));
            // Fully Qualified Domain Name
            Assert.Equal("abc.xn--d9juau41awczczp.xn--de-jg4avhby1noc0d", idn.GetAscii("\u0061\u0062\u0063.\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067.\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0"));
        }
        public void UseStd3AsciiRules_NonLDH_ASCII_Codepoint()
        {
            var idnStd3False = new IdnMapping { UseStd3AsciiRules = false };
            string unicode = "\u0030\u002D\u0045\u007A";

            Assert.Equal(unicode, idnStd3False.GetAscii(unicode), ignoreCase: true);
        }
        [InlineData("\u002D\u0062\u002D", true)] // Leading and trailing hyphen minus
        public void UseStd3AsciiRules_ChangesGetAsciiBehavior(string unicode, bool containsInvalidHyphen)
        {
            var idnStd3False = new IdnMapping { UseStd3AsciiRules = false };
            var idnStd3True = new IdnMapping { UseStd3AsciiRules = true };

            if (containsInvalidHyphen && !s_isWindows)
            {
                // ICU always fails on leading/trailing hyphens regardless of the Std3 rules option.
                Assert.Throws<ArgumentException>("unicode", () => idnStd3False.GetAscii(unicode));
            }
            else
            {
                Assert.Equal(unicode, idnStd3False.GetAscii(unicode));
            }

            Assert.Throws<ArgumentException>("unicode", () => idnStd3True.GetAscii(unicode));
        }
        [InlineData("\u002D\u0062\u002D", true)] // Leading and trailing hyphen minus
        public void UseStd3AsciiRules_ChangesGetAsciiBehavior(string unicode, bool containsInvalidHyphen)
        {
            var idnStd3False = new IdnMapping { UseStd3AsciiRules = false };
            var idnStd3True = new IdnMapping { UseStd3AsciiRules = true };

            if (containsInvalidHyphen && !s_isWindows)
            {
                // ICU always fails on leading/trailing hyphens regardless of the Std3 rules option.
                Assert.Throws<ArgumentException>("unicode", () => idnStd3False.GetAscii(unicode));
            }
            else
            {
                Assert.Equal(unicode, idnStd3False.GetAscii(unicode));
            }

            ArgumentException ae = Assert.Throws<ArgumentException>(() => idnStd3True.GetAscii(unicode));
            // sometimes the desktop returns "Unicode" instead of "unicode" for the parameter name.
            Assert.Equal("unicode", ae.ParamName, ignoreCase: true);
        }
Ejemplo n.º 5
0
        public void EmbeddedNulls()
        {
            var idn = new IdnMapping();

            Assert.Throws<ArgumentException>(() => idn.GetAscii("\u0101\u0000"));
            Assert.Throws<ArgumentException>(() => idn.GetAscii("\u0101\u0000", 0));
            Assert.Throws<ArgumentException>(() => idn.GetAscii("\u0101\u0000", 0, 2));
            Assert.Throws<ArgumentException>(() => idn.GetAscii("\u0101\u0000\u0101"));
            Assert.Throws<ArgumentException>(() => idn.GetAscii("\u0101\u0000\u0101", 0));
            Assert.Throws<ArgumentException>(() => idn.GetAscii("\u0101\u0000\u0101", 0, 3));
            Assert.Throws<ArgumentException>(() => idn.GetAscii("\u0101\u0000\u0101\u0000"));
            Assert.Throws<ArgumentException>(() => idn.GetAscii("\u0101\u0000\u0101\u0000", 0));
            Assert.Throws<ArgumentException>(() => idn.GetAscii("\u0101\u0000\u0101\u0000", 0, 4));
            Assert.Throws<ArgumentException>(() => idn.GetUnicode("abc\u0000", 0, 4));
            Assert.Throws<ArgumentException>(() => idn.GetUnicode("ab\u0000c", 0, 4));
        }
 public void GetAscii_Invalid()
 {
     foreach (var entry in Factory.GetDataset())
     {
         if (!entry.GetASCIIResult.Success)
         {
             var map = new IdnMapping();
             Assert.Throws<ArgumentException>(() => map.GetAscii(entry.Source));
         }
     }
 }
Ejemplo n.º 7
0
 public static void GetUnicode_Invalid(IdnMapping idnMapping, string ascii, int index, int count, Type exceptionType)
 {
     if (ascii == null || index + count == ascii.Length)
     {
         if (ascii == null || index == 0)
         {
             Assert.Throws(exceptionType, () => idnMapping.GetUnicode(ascii));
         }
         Assert.Throws(exceptionType, () => idnMapping.GetUnicode(ascii, index));
     }
     Assert.Throws(exceptionType, () => idnMapping.GetAscii(ascii, index, count));
 }
 public void GetAscii_Success()
 {
     foreach (var entry in Factory.GetDataset())
     {
         if (entry.GetASCIIResult.Success)
         {
             var map = new IdnMapping();
             var asciiResult = map.GetAscii(entry.Source);
             Assert.Equal(entry.GetASCIIResult.Value, asciiResult, StringComparer.OrdinalIgnoreCase);
         }
     }
 }
Ejemplo n.º 9
0
        public static void GetAsciiThrows()
        {
            IdnMapping idnMapping = new IdnMapping();

            Assert.Throws<ArgumentNullException>("unicode", () => idnMapping.GetAscii(null, -5));
            Assert.Throws<ArgumentNullException>("unicode", () => idnMapping.GetAscii(null, -5, -10));
            Assert.Throws<ArgumentOutOfRangeException>("index", () => idnMapping.GetAscii("abc", -5, -10));
            Assert.Throws<ArgumentOutOfRangeException>("count", () => idnMapping.GetAscii("abc", 10, -10));
            Assert.Throws<ArgumentOutOfRangeException>("byteIndex", () => idnMapping.GetAscii("abc", 4, 99));
            Assert.Throws<ArgumentOutOfRangeException>("unicode", () => idnMapping.GetAscii("abc", 2, 2));
            Assert.Throws<ArgumentException>("unicode", () => idnMapping.GetAscii("abc", 3, 0));
        }
Ejemplo n.º 10
0
    private string DomainMapper(Match match)
    {
        // IdnMapping class with default property values.
        IdnMapping idn = new IdnMapping();

        string domainName = match.Groups[2].Value;
        try
        {
            domainName = idn.GetAscii(domainName);
        }
        catch (ArgumentException)
        {
            invalid = true;
        }
        return match.Groups[1].Value + domainName;
    }
Ejemplo n.º 11
0
        /// <summary>
        /// Creates a valid ASCII domain name out of a Unicode one.
        /// </summary>
        /// <param name="match">Used by the Regex class.</param>
        /// <returns>A valid domain, if one can be generated.</returns>
        private string DomainMapper(Match match)
        {
            // IdnMapping class with default property values.
            IdnMapping idn = new IdnMapping();

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

            try
            {
                domainName = idn.GetAscii(domainName);
            }
            catch (ArgumentException)
            {
                IsEmailValid = true;    // This causes ValidateEmail to fail.
            }
            return(match.Groups[1].Value + domainName);
        }
        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 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);
            }
        }
        /// <summary>
        ///     Needed to support chinese character support
        /// </summary>
        /// <param name="match"></param>
        /// <returns></returns>
        private static string DomainMapper(Match match)
        {
            // IdnMapping class with default property values.
            var idn = new IdnMapping();

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

            try
            {
                domainName = idn.GetAscii(domainName);
            }
            catch (ArgumentException)
            {
                _invalid = true;
            }
            return(match.Groups[1].Value + domainName);
        }
Ejemplo n.º 14
0
        public static ValidationResponse Email(string email)
        {
            if (string.IsNullOrWhiteSpace(email))
            {
                return(ValidationResponse.Empty);
            }

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

                string DomainMapper(Match match)
                {
                    var idn        = new IdnMapping();
                    var domainName = idn.GetAscii(match.Groups[2].Value);

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

            try
            {
                var regex = @"^(?("")("".+?(?<!\\)""@)|(([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]))$";

                if (Regex.IsMatch(email, regex, RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250)))
                {
                    return(ValidationResponse.Valid);
                }
                else
                {
                    return(ValidationResponse.Invalid);
                }
            }
            catch (RegexMatchTimeoutException)
            {
                return(ValidationResponse.Invalid);
            }
        }
Ejemplo n.º 15
0
        public void SimpleValidationTests()
        {
            var idn = new IdnMapping();

            Assert.Equal("xn--yda", idn.GetAscii("\u0101"));
            Assert.Equal("xn--yda", idn.GetAscii("\u0101", 0));
            Assert.Equal("xn--yda", idn.GetAscii("\u0101", 0, 1));

            Assert.Equal("xn--aa-cla", idn.GetAscii("\u0101\u0061\u0041"));
            Assert.Equal("xn--ab-dla", idn.GetAscii("\u0061\u0101\u0062"));
            Assert.Equal("xn--ab-ela", idn.GetAscii("\u0061\u0062\u0101"));
        }
Ejemplo n.º 16
0
        public void SimpleValidationTests()
        {
            var idn = new IdnMapping();

            Assert.Equal("xn--yda", idn.GetAscii("\u0101"));
            Assert.Equal("xn--yda", idn.GetAscii("\u0101", 0));
            Assert.Equal("xn--yda", idn.GetAscii("\u0101", 0, 1));

            Assert.Equal("xn--aa-cla", idn.GetAscii("\u0101\u0061\u0041"));
            Assert.Equal("xn--ab-dla", idn.GetAscii("\u0061\u0101\u0062"));
            Assert.Equal("xn--ab-ela", idn.GetAscii("\u0061\u0062\u0101"));
        }
Ejemplo n.º 17
0
        internal List <IISBindingOption> GetBindings()
        {
            if (_iisClient.Version.Major == 0)
            {
                _log.Warning("IIS not found. Skipping scan.");
                return(new List <IISBindingOption>());
            }

            // Get all bindings matched together with their respective sites
            _log.Debug("Scanning IIS site bindings for hosts");
            var siteBindings = _iisClient.WebSites.
                               SelectMany(site => site.Bindings, (site, binding) => new { site, binding }).
                               Where(sb => !string.IsNullOrWhiteSpace(sb.binding.Host)).
                               ToList();

            // Option: hide http bindings when there are already https equivalents
            var https = siteBindings.Where(sb =>
                                           sb.binding.Protocol == "https" ||
                                           sb.site.Bindings.Any(other =>
                                                                other.Protocol == "https" &&
                                                                string.Equals(sb.binding.Host, other.Host, StringComparison.InvariantCultureIgnoreCase))).ToList();

            var targets = siteBindings.
                          Select(sb => new
            {
                host = sb.binding.Host.ToLower(),
                sb.site,
                sb.binding,
                https = https.Contains(sb)
            }).
                          Select(sbi => new IISBindingOption
            {
                SiteId       = sbi.site.Id,
                HostUnicode  = sbi.host,
                HostPunycode = _idnMapping.GetAscii(sbi.host),
                Port         = sbi.binding.Port,
                Protocol     = sbi.binding.Protocol,
                Https        = sbi.https
            }).
                          DistinctBy(t => t.HostUnicode + t.SiteId).
                          OrderBy(t => t.HostUnicode).
                          ToList();

            return(targets);
        }
Ejemplo n.º 18
0
        public Boolean ValidarEmail(string email)
        {
            if (string.IsNullOrWhiteSpace(email))
            {
                return(false);
            }

            try
            {
                // normaliza el dominio
                email = Regex.Replace(email, @"(@)(.+)$", DomainMapper, RegexOptions.None, TimeSpan.FromMilliseconds(200));

                // Examina el dominio y lo normaliza
                string DomainMapper(Match match)
                {
                    // Utilice la clase IdnMapping para convertir nombres de dominio Unicode
                    var idn = new IdnMapping();

                    // Extrae y procesa el nombre del dominio
                    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);
            }
        }
Ejemplo n.º 19
0
    public static void Main()
    {
/*
 * Define a domain name consisting of the labels: GREEK SMALL LETTER
 * PI (U+03C0); IDEOGRAPHIC FULL STOP (U+3002); GREEK SMALL LETTER
 * THETA (U+03B8); FULLWIDTH FULL STOP (U+FF0E); and "com".
 */
        string name = "\u03C0\u3002\u03B8\uFF0Ecom";
        string international;
        string nonInternational;

        string msg1 = "the original non-internationalized \ndomain name:";
        string msg2 = "Allow unassigned characters?:     {0}";
        string msg3 = "Use non-internationalized rules?: {0}";
        string msg4 = "Convert the non-internationalized domain name to international format...";
        string msg5 = "Display the encoded domain name:\n\"{0}\"";
        string msg6 = "the encoded domain name:";
        string msg7 = "Convert the internationalized domain name to non-international format...";
        string msg8 = "the reconstituted non-internationalized \ndomain name:";
        string msg9 = "Visually compare the code points of the reconstituted string to the " +
                      "original.\n" +
                      "Note that the reconstituted string contains standard label " +
                      "separators (U+002e).";

// ----------------------------------------------------------------------------
        CodePoints(name, msg1);
// ----------------------------------------------------------------------------

        IdnMapping idn = new IdnMapping();

        Console.WriteLine(msg2, idn.AllowUnassigned);
        Console.WriteLine(msg3, idn.UseStd3AsciiRules);
        Console.WriteLine();
// ----------------------------------------------------------------------------
        Console.WriteLine(msg4);
        international = idn.GetAscii(name, 0, name.Length);
        Console.WriteLine(msg5, international);
        Console.WriteLine();
        CodePoints(international, msg6);
// ----------------------------------------------------------------------------
        Console.WriteLine(msg7);
        nonInternational = idn.GetUnicode(international, 0, international.Length);
        CodePoints(nonInternational, msg8);
        Console.WriteLine(msg9);
    }
Ejemplo n.º 20
0
        public static bool IsValidEmail(string email)
        {
            if (string.IsNullOrWhiteSpace(email))
            {
                return(false);
            }

            try
            {
                // Normalizar el dominio
                email = Regex.Replace(email, @"(@)(.+)$", DomainMapper,
                                      RegexOptions.None, TimeSpan.FromMilliseconds(200));

                // Examina la parte del dominio del correo electrónico y la normaliza.
                string DomainMapper(Match match)
                {
                    // Utilice la clase IdnMapping para convertir nombres de dominio Unicode.
                    var idn = new IdnMapping();

                    // Extraiga y procese el nombre de dominio (arroja ArgumentException en inválido)
                    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);
            }
        }
Ejemplo n.º 21
0
        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 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)
            {
                return(false);
            }
            catch (ArgumentException)
            {
                return(false);
            }

            try
            {
                return(Regex.IsMatch(email,
                                     @"^[^@\s]+@[^@\s]+\.[^@\s]+$",
                                     RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250)));
            }
            catch (RegexMatchTimeoutException)
            {
                return(false);
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Проверка корректности электронной почты.
        /// </summary>
        /// <param name="email">Электронаня почта.</param>
        /// <returns>Если электронная почта введена корректно - true, в противном случае вернёт false.</returns>
        public static bool IsValidEmail(string email)
        {
            if (string.IsNullOrWhiteSpace(email))
            {
                return(false);
            }

            try
            {
                // Нормализация домена.
                email = Regex.Replace(email, @"(@)(.+)$", DomainMapper,
                                      RegexOptions.None, TimeSpan.FromMilliseconds(200));

                // Изучает домен электронной почты и нормализует её.
                string DomainMapper(Match match)
                {
                    var idn = new IdnMapping();

                    // Вытащить и обработать доменное имя (создает недопустимое ArgumentException)
                    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);
            }
        }
Ejemplo n.º 23
0
        public bool IsValidEmail(string input)
        {
            if (input.IsNullOrEmptyOrWhiteSpace())
            {
                return(false);
            }

            _isValid = true;

            string replaced;

            try
            {
                replaced = _emailPrimaryRegex.Replace(input, DomainMapper);
            } catch (RegexMatchTimeoutException)
            {
                return(false);
            }

            if (!_isValid)
            {
                return(false);
            }

            try
            {
                return(_emailSecondaryRegex.IsMatch(replaced));
            } catch (RegexMatchTimeoutException)
            {
                return(false);
            }

            string DomainMapper(Match match)
            {
                var domainName = match.Groups[2].Value;

                try {
                    domainName = _idn.GetAscii(domainName);
                }
                catch (ArgumentException) {
                    _isValid = false;
                }
                return(match.Groups[1].Value + domainName);
            }
        }
Ejemplo n.º 24
0
        private string DomainMapper(Match match)
        {
            // IDNMAPPING CLASS WITH DEFAULT PROPERTY VALUES

            IdnMapping idn = new IdnMapping();

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

            try
            {
                domainName = idn.GetAscii(domainName);
            }
            catch (ArgumentException)
            {
                inValid = true;
            }
            return(match.Groups[1].Value + domainName);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Generates a URL with optional scheme, host and path. Example: "http://thiel.com/chauncey_simonis"
        /// </summary>
        /// <param name="host">Optional host name to use. Example: "example.com"</param>
        /// <param name="path">Optional path to use: Example: "/clotilde.swift".</param>
        /// <param name="scheme">Optional scheme. Example: "https". Default is "http".</param>
        /// <returns>A URL with optional scheme, host and path</returns>
        /// <remarks>The implementation does not check if any of the values make sense, e.g. if the given scheme
        /// even exists.</remarks>
        /// <exception cref="ArgumentOutOfRangeException">If scheme or host is an empty string.</exception>
        public static string Url(string host = null, string path = null, string scheme = "http")
        {
            var idn = new IdnMapping();

            host = host ?? idn.GetAscii(DomainName());
            var percentEncodedUserName = Uri.EscapeDataString(UserName());

            path = path ?? $"/{percentEncodedUserName}";
            if (string.IsNullOrWhiteSpace(scheme))
            {
                throw new ArgumentOutOfRangeException(nameof(scheme), "Must not be empty string or white spaces only.");
            }
            if (string.IsNullOrWhiteSpace(host))
            {
                throw new ArgumentOutOfRangeException(nameof(host), "Must not be empty string or white spaces only.");
            }
            return($"{scheme}://{host}{path}");
        }
 public void GetAscii_Success()
 {
     Assert.All(Factory.GetDataset().Where(e => e.ASCIIResult.Success), entry =>
     {
         try
         {
             var map         = new IdnMapping();
             var asciiResult = map.GetAscii(entry.Source);
             Assert.Equal(entry.ASCIIResult.Value, asciiResult, StringComparer.OrdinalIgnoreCase);
         }
         catch (ArgumentException)
         {
             string actualCodePoints   = GetCodePoints(entry.Source);
             string expectedCodePoints = GetCodePoints(entry.ASCIIResult.Value);
             throw new Exception($"Expected IdnMapping.GetAscii(\"{actualCodePoints}\" to return \"{expectedCodePoints}\".");
         }
     });
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="match"></param>
        /// <returns></returns>
        private string DomainMapper(Match match)
        {
            // IdnMapping class with default property values.
            IdnMapping idn = new IdnMapping();

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

            try
            {
                domainName = idn.GetAscii(domainName);
            }
            catch (Exception e)
            {
                LogUtil.Log(e.Message + Environment.NewLine + e.StackTrace);
                throw e;
            }
            return(match.Groups[1].Value + domainName);
        }
Ejemplo n.º 28
0
        private void ButtonGo_Click(object sender, EventArgs e)
        {
            // This code section extracts the protocol, host section and extension of the string that is
            // entered in the address control
            // A more sophisticated verification is recommended to make this adapt for all possible erroneous input
            Regex  r     = new Regex(@"(?<proto>\w+)://(?<host>[\w.]+)/*(?<ext>\S*)", RegexOptions.Compiled);
            string proto = r.Match(this.textBoxAddress.Text).Result("${proto}");
            string host  = r.Match(this.textBoxAddress.Text).Result("${host}");
            string ext   = r.Match(this.textBoxAddress.Text).Result("${ext}");

            // Convert the entered IDN host name to Punycode
            IdnMapping mapping = new IdnMapping();
            string     puny    = mapping.GetAscii(host);

            // Assemble the URL and navigate to the specified site
            this.textBoxPunycode.Text = proto + "://" + puny + "/" + ext;
            this.webBrowser1.Navigate(this.textBoxPunycode.Text);
        }
Ejemplo n.º 29
0
        private string DomainMapper(System.Text.RegularExpressions.Match match)
        {
            logger.Log(LogLevel.Debug, "Trace:: RegexUtilities.DomainMapper(match: " + match + ")");
            // IdnMapping class with default property values.
            var idn = new IdnMapping();

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

            try
            {
                domainName = idn.GetAscii(domainName);
            }
            catch (ArgumentException)
            {
                invalid = true;
            }
            return(match.Groups[1].Value + domainName);
        }
Ejemplo n.º 30
0
        string DomainMapper(Match match)
        {
            bool invalid = false;
            // IdnMapping class with default property values.
            IdnMapping idn = new IdnMapping();

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

            try
            {
                domainName = idn.GetAscii(domainName);
            }
            catch (ArgumentException)
            {
                invalid = true;
            }
            return(match.Groups[1].Value + domainName);
        }
Ejemplo n.º 31
0
        private string DomainMapper(Match match) // Resolves unicode domain names when sending an email
        {
            // IdnMapping class with default property values.
            IdnMapping idn = new IdnMapping();

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

            try
            {
                domainName = idn.GetAscii(domainName);
            }
            catch (ArgumentException ae)
            {
                // The email is invalid so throw exception // WHY?
                throw ae;
            }
            return(match.Groups[1].Value + domainName);
        }
Ejemplo n.º 32
0
        public PendingAuthorization BeginRegistrationAndValidation(CertRequestConfig requestConfig, string identifierAlias, string challengeType = "http-01", string domain = null)
        {
            //if no alternative domain specified, use the primary domains as the subject
            if (domain == null)
            {
                domain = requestConfig.PrimaryDomain;
            }

            // if (GetIdentifier(identifierAlias) == null)

            //if an identifier exists for the same dns in vault, remove it to avoid confusion
            this.DeleteIdentifierByDNS(domain);

            // ACME service requires international domain names in ascii mode, regiser the new
            // identifier with Lets Encrypt
            var authState = ACMESharpUtils.NewIdentifier(identifierAlias, idnMapping.GetAscii(domain));

            var identifier = this.GetIdentifier(identifierAlias, reloadVaultConfig: true);

            //FIXME: when validating subsequent SAN names in parallel request mode, the identifier is null?
            if (identifier != null && identifier.Authorization != null && identifier.Authorization.IsPending())
            {
                ACMESharpUtils.CompleteChallenge(identifier.Alias, challengeType, Handler: "manual", Regenerate: true, Repeat: true);

                //get challenge info
                ReloadVaultConfig();
                identifier = GetIdentifier(identifierAlias);
                var challengeInfo = identifier.Challenges.FirstOrDefault(c => c.Value.Type == challengeType).Value;

                //identifier challenege specification is now ready for use to prepare and answer for LetsEncrypt to check
                return(new PendingAuthorization()
                {
                    Challenge = GetAuthorizeChallengeItemFromAuthChallenge(challengeInfo), Identifier = GetDomainIdentifierItemFromIdentifierInfo(identifier), TempFilePath = "", ExtensionlessConfigCheckedOK = false
                });
            }
            else
            {
                //identifier is null or already valid (previously authorized)
                return(new PendingAuthorization()
                {
                    Challenge = null, Identifier = GetDomainIdentifierItemFromIdentifierInfo(identifier), TempFilePath = "", ExtensionlessConfigCheckedOK = false
                });
            }
        }
Ejemplo n.º 33
0
        private bool IsValidEmail()
        {
            var email = Value;

            if (string.IsNullOrWhiteSpace(email))
            {
                return(false);
            }

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

                string DomainMapper(Match match)
                {
                    var idn = new IdnMapping();

                    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);
            }
        }
Ejemplo n.º 34
0
        /*
         * public static bool VerifyRegNr(string regNr)
         * {
         *  regNr = System.Text.RegularExpressions.Regex.Match
         * }*/
        public static bool VerifyEmail(string email)
        {
            if (string.IsNullOrWhiteSpace(email))
            {
                return(false);
            }

            try
            {
                // Normaliserr domänen
                email = System.Text.RegularExpressions.Regex.Replace(email, @"(@)(.+)$", DomainMapper,
                                                                     RegexOptions.None, TimeSpan.FromMilliseconds(200));

                // Undersöker domändelen av e-postmeddelandet och normaliserar det
                string DomainMapper(Match match)
                {
                    // Använd IdnMapping-klassen för att konvertera Unicode-domännamn.
                    var idn = new IdnMapping();

                    // Dra ut och bearbeta domännamn(kastar ArgumentException på ogiltigt)
                    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(System.Text.RegularExpressions.Regex.IsMatch(email,
                                                                    @"^[^@\s]+@[^@\s]+\.[^@\s]+$",
                                                                    RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250)));
            }
            catch (RegexMatchTimeoutException)
            {
                return(false);
            }
        }
Ejemplo n.º 35
0
        /// <summary>
        /// Assists in domain mapping.
        /// </summary>
        /// <param name="match">
        /// The match.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        private string DomainMapper(Match match)
        {
            // IdnMapping class with default property values.
            var idn = new IdnMapping();

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

            try
            {
                domainName = idn.GetAscii(domainName);
            }
            catch (ArgumentException)
            {
                MultiLogHelper.Debug <EmailValidationHelper>("Invalid email address");
                this.invalid = true;
            }

            return(match.Groups[1].Value + domainName);
        }
Ejemplo n.º 36
0
        public static bool IsIPv4AddressOrFQDN(this string value, string propertyName, out string address, bool allowEmptyString = false, bool throwExceptionOnMiss = false)
        {
            if (!String.IsNullOrEmpty(value))
            {
                IPAddress ip;
                if (NetworkAddressTest.IsIPv4Address(value, out ip))
                {
                    address = ip.ToString();
                    return(true);
                }
                else if (NetworkAddressTest.IsFqdn(value))
                {
                    IdnMapping idn = new IdnMapping();
                    address = idn.GetAscii(value.Trim());
                    return(true);
                }
                else
                {
                    address = null;
                    throw new FormatException($"{propertyName} must be a valid IPv4 or FQDN, {value} was provided.");
                }
            }
            else
            {
                address = null;

                if (allowEmptyString)
                {
                    return(true);
                }
                else
                {
                    if (throwExceptionOnMiss)
                    {
                        throw new ArgumentNullException($"The value for {propertyName} was null or empty and not a valid FQDN or IPv4 address.");
                    }
                    else
                    {
                        return(false);
                    }
                }
            }
        }
        //  Inspired by: http://stackoverflow.com/questions/3275242/how-do-you-remove-invalid-characters-when-creating-a-friendly-url-ie-how-do-you
        public static string Slugify(string text)
        {
            IdnMapping idnMapping = new IdnMapping();

            text = idnMapping.GetAscii(text);

            text = RemoveAccent(text).ToLower();

            //  Remove all invalid characters.
            text = Regex.Replace(text, @"[^a-z0-9\s-]", "");

            //  Convert multiple spaces into one space
            text = Regex.Replace(text, @"\s+", " ").Trim();

            //  Replace spaces by underscores.
            text = Regex.Replace(text, @"\s", "_");

            return(text);
        }
Ejemplo n.º 38
0
 [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))] // https://github.com/dotnet/runtime/issues/22409
 public void GetAscii_Invalid()
 {
     Assert.All(Factory.GetDataset().Where(entry => !entry.ASCIIResult.Success), entry =>
     {
         try
         {
             var map = new IdnMapping()
             {
                 UseStd3AsciiRules = true
             };
             AssertExtensions.Throws <ArgumentException>("unicode", () => map.GetAscii(entry.Source));
         }
         catch (ThrowsException)
         {
             string codePoints = GetCodePoints(entry.Source);
             throw new Exception($"Expected IdnMapping.GetAscii(\"{codePoints}\") to throw an ArgumentException. Line Number: {entry.LineNumber}");
         }
     });
 }
Ejemplo n.º 39
0
        private string GetHost(bool allowUnicode)
        {
            string domain = host;

            // Downgrade Unicode domain names
            if (!allowUnicode && !MimeBasePart.IsAscii(domain, true))
            {
                IdnMapping mapping = new IdnMapping();
                try
                {
                    domain = mapping.GetAscii(domain);
                }
                catch (ArgumentException argEx)
                {
                    throw new SmtpException(SR.GetString(SR.SmtpInvalidHostName, Address), argEx);
                }
            }
            return(domain);
        }
Ejemplo n.º 40
0
            public string DomainMapper(Match match)
            {
                // IdnMapping class with default property values.
                IdnMapping idn = new IdnMapping();

                string domainName;

                try
                {
                    domainName = match.Groups[2].Value;
                    domainName = idn.GetAscii(domainName);
                    return(match.Groups[1].Value + domainName);
                }
                catch
                {
                    isValid = false;
                    return(null);
                }
            }
Ejemplo n.º 41
0
        protected AbstractDnsRecord(string name, DnsRecordType type,
                                    long timeToLive, DnsRecordClass dnsClass = DnsRecordClass.IN)
        {
            if (TimeToLive < 0)
            {
                throw new ArgumentException($"timeToLive: {timeToLive} (expected: >= 0)");
            }

            TimeToLive = timeToLive;

            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentNullException(nameof(name));
            }

            Name     = AppendTrailingDot(idn.GetAscii(name));
            Type     = type ?? throw new ArgumentNullException(nameof(type));
            DnsClass = dnsClass;
        }
Ejemplo n.º 42
0
        public void IllegalChars(bool useStd3AsciiRules)
        {
            var idn = new IdnMapping();
            idn.UseStd3AsciiRules = useStd3AsciiRules;
            string testString;

            for (int i = 0; i <= 0x1F; i++)
            {
                testString = "abc" + new string((char)i, 1) + "def";
                Assert.Throws<ArgumentException>(() => idn.GetAscii(testString));
                Assert.Throws<ArgumentException>(() => idn.GetUnicode(testString));
            }

            testString = "abc" + new string((char)0x7F, 1) + "def";
            Assert.Throws<ArgumentException>(() => idn.GetAscii(testString));
            Assert.Throws<ArgumentException>(() => idn.GetUnicode(testString));
        }
Ejemplo n.º 43
0
        public void SurrogatePairsSeparatedByAsciiAndNonAscii()
        {
            var idn = new IdnMapping();

            Assert.Equal("xn--a-nha4529qfag", idn.GetAscii("\uD800\uDF00\u0101\uD800\uDF01\u0061\uD800\uDF02"));
        }
Ejemplo n.º 44
0
        public void SurrogatePairsSeparatedByNonAscii()
        {
            var idn = new IdnMapping();

            Assert.Equal("xn--yda263v6b6kfag", idn.GetAscii("\uD800\uDF00\u0101\uD800\uDF01\u305D\uD800\uDF02"));
        }
Ejemplo n.º 45
0
        public void SurrogatePairsSeparatedByAscii()
        {
            var idn = new IdnMapping();

            Assert.Equal("xn--ab-ic6nfag", idn.GetAscii("\uD800\uDF00\u0061\uD800\uDF01\u0042\uD800\uDF02"));
        }
Ejemplo n.º 46
0
        public void SurrogatePairsConsecutive()
        {
            var idn = new IdnMapping();

            Assert.Equal("xn--097ccd", idn.GetAscii("\uD800\uDF00\uD800\uDF01\uD800\uDF02"));
        }
Ejemplo n.º 47
0
        public void EmbeddedDomainNameConversion()
        {
            var idn = new IdnMapping();

            Assert.Equal("abc.xn--d9juau41awczczp.xn--de-jg4avhby1noc0d", idn.GetAscii("\u0061\u0062\u0063.\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067.\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0", 0));
            Assert.Equal("abc.xn--d9juau41awczczp", idn.GetAscii("\u0061\u0062\u0063.\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067.\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0", 0, 11));
            Assert.Equal("abc.xn--d9juau41awczczp.", idn.GetAscii("\u0061\u0062\u0063.\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067.\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0", 0, 12));
            Assert.Equal("abc.xn--d9juau41awczczp.xn--de-jg4avhby1noc0d", idn.GetAscii("\u0061\u0062\u0063.\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067.\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0", 0, 21));
            Assert.Throws<ArgumentException>(() => idn.GetAscii("\u0061\u0062\u0063.\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067.\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0", 3));
            Assert.Throws<ArgumentException>(() => idn.GetAscii("\u0061\u0062\u0063.\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067.\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0", 3, 8));
            Assert.Throws<ArgumentException>(() => idn.GetAscii("\u0061\u0062\u0063.\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067.\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0", 3, 9));
            Assert.Equal("xn--d9juau41awczczp.xn--de-jg4avhby1noc0d", idn.GetAscii("\u0061\u0062\u0063.\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067.\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0", 4));
            Assert.Equal("xn--d9juau41awczczp", idn.GetAscii("\u0061\u0062\u0063.\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067.\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0", 4, 7));
            Assert.Equal("xn--d9juau41awczczp.", idn.GetAscii("\u0061\u0062\u0063.\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067.\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0", 4, 8));
            Assert.Equal("xn--d9juau41awczczp.xn--de-jg4avhby1noc0d", idn.GetAscii("\u0061\u0062\u0063.\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067.\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0", 4, 17));
            Assert.Throws<ArgumentException>(() => idn.GetAscii("\u0061\u0062\u0063.\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067.\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0", 11));
            Assert.Throws<ArgumentException>(() => idn.GetAscii("\u0061\u0062\u0063.\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067.\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0", 11, 10));
            Assert.Equal("xn--de-jg4avhby1noc0d", idn.GetAscii("\u0061\u0062\u0063.\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067.\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0", 12));
            Assert.Equal("xn--de-jg4avhby1noc0d", idn.GetAscii("\u0061\u0062\u0063.\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067.\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0", 12, 9));
        }
Ejemplo n.º 48
0
 public static void GetAscii_Invalid(IdnMapping idnMapping, string unicode, int index, int count, Type exceptionType)
 {
     if (unicode == null || index + count == unicode.Length)
     {
         if (unicode == null || index == 0)
         {
             Assert.Throws(exceptionType, () => idnMapping.GetAscii(unicode));
         }
         Assert.Throws(exceptionType, () => idnMapping.GetAscii(unicode, index));
     }
     Assert.Throws(exceptionType, () => idnMapping.GetAscii(unicode, index, count));
 }