public HostName(string host, bool idn = true) { if (host == null) { throw new ArgumentNullException(); } try { host = host.ToLower(); if (host.StartsWith("xn--") || host.Contains(".xn--")) { Unicode = IdnMapping.GetUnicode(host); Ascii = IdnMapping.GetAscii(Unicode); } else { Ascii = IdnMapping.GetAscii(host); Unicode = IdnMapping.GetUnicode(Ascii); } Idn = idn && Ascii != Unicode; } catch (Exception e) { throw new FormatException(String.Format("Invalid host '{0}'", host), e); } }
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.GetUnicode(ascii, index, count)); }
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 List <string> GetImportableItems(int packageId, int itemTypeId, Type itemType, ResourceGroupInfo group) { List <string> items = new List <string>(); // get service id int serviceId = PackageController.GetPackageServiceId(packageId, group.GroupName); if (serviceId == 0) { return(items); } // Mail provider DNSServer dns = new DNSServer(); ServiceProviderProxy.Init(dns, serviceId); // IDN: The list of importable names is populated with unicode names, to make it easier for the user var idn = new IdnMapping(); if (itemType == typeof(DnsZone)) { items.AddRange(dns.GetZones().Select(z => Encoding.UTF8.GetByteCount(z) == z.Length ? // IsASCII idn.GetUnicode(z) : z)); } return(items); }
private bool IsValidSiteUrl(string url) { var absUrl = "http://" + url; if (!Uri.IsWellFormedUriString(absUrl, UriKind.Absolute)) { return(false); } try { var uri = new Uri(absUrl); // this is necessary when the link is ascii-formatted because uri.Authority will be unicode formatted var idnMapping = new IdnMapping(); var uniUrl = idnMapping.GetUnicode(url); if (uri.Authority != url) { return(false); } } catch { // Do not log this, we only have to decide whether the URL is valid or not. return(false); } return(true); }
/// <summary> /// Creates a new HostString from the given URI component. /// Any punycode will be converted to Unicode. /// </summary> /// <param name="uriComponent"></param> /// <returns></returns> public static HostString FromUriComponent(string uriComponent) { if (!string.IsNullOrEmpty(uriComponent)) { int index; if (uriComponent.IndexOf('[') >= 0) { // IPv6 in brackets [::1], maybe with port } else if ((index = uriComponent.IndexOf(':')) >= 0 && index < uriComponent.Length - 1 && uriComponent.IndexOf(':', index + 1) >= 0) { // IPv6 without brackets ::1 is the only type of host with 2 or more colons } else if (uriComponent.IndexOf("xn--", StringComparison.Ordinal) >= 0) { // Contains punycode if (index >= 0) { // Has a port string port = uriComponent.Substring(index); var mapping = new IdnMapping(); uriComponent = mapping.GetUnicode(uriComponent, 0, index) + port; } else { var mapping = new IdnMapping(); uriComponent = mapping.GetUnicode(uriComponent); } } } return(new HostString(uriComponent)); }
public static (Dictionary <string, string> headers, string response, int status) SendResponse(HttpListenerRequest request) { int status; string response = "<head><link rel=\"icon\" href=\"data:;base64,iVBORw0KGgo=\"></head><body>Loading..</body>"; Dictionary <string, string> headers = new Dictionary <string, string>(); IdnMapping idn = new IdnMapping(); if (domains.Contains(request.UserHostName)) { string real_domain = idn.GetUnicode(request.UserHostName); string return_url = redirect_table[real_domain]; status = 307; response = ""; headers.Add("Location", return_url); Debug.WriteLine("Target: " + real_domain); } else { status = 400; response = "<body>shortcut query failed.</body>"; } return(headers, response, status); }
public static void Main() { string email = "johann_doe@bücher.com [email protected] иван@мойдомен.рф"; IdnMapping idn = new IdnMapping(); int start = 0, end = 0; while (end >= 0) { start = email.IndexOf("@", end); end = email.IndexOf(" ", start); string domain = String.Empty; try { string punyCode = String.Empty; if (start >= 0 && end >= 0) { domain = email.Substring(start + 1, end - start - 1); punyCode = idn.GetAscii(email, start + 1, end - start - 1); } else { domain = email.Substring(start + 1); punyCode = idn.GetAscii(email, start + 1); } string name2 = idn.GetUnicode(punyCode); Console.WriteLine("{0} --> {1} --> {2}", domain, punyCode, name2); } catch (ArgumentException) { Console.WriteLine("{0} is not a valid domain name.", domain); } Console.WriteLine(); } }
public static void Main() { string[] names = { "johann_doe@bücher.com", "vi@мойдомен.рф", "ia@παράδειγμα.δοκιμή", "webmaster@mycharity\u3002org", "admin@prose\u0000ware.com", "*****@*****.**", "*****@*****.**", "me@my_company.com" }; IdnMapping idn = new IdnMapping(); foreach (var thisName in names) { string name = thisName; try { int position = name.LastIndexOf("@"); if (position >= 0) { name = name.Substring(position + 1); } string punyCode = idn.GetAscii(name); string name2 = idn.GetUnicode(punyCode); Console.WriteLine("{0} --> {1} --> {2}", name, punyCode, name2); Console.WriteLine("Original: {0}", ShowCodePoints(name)); Console.WriteLine("Restored: {0}", ShowCodePoints(name2)); } catch (ArgumentException) { Console.WriteLine("{0} is not a valid domain name.", name); } Console.WriteLine(); } }
public String Decode(String url) { var u = new Uri(url); var idn = new IdnMapping(); var hostName = idn.GetUnicode(u.Host); return(url.Replace(u.Host, hostName)); }
public static string IdnDecode(string ascii) { try { return(idn.GetUnicode(ascii)); } catch { return(ascii); } }
void GetUnicodeInvalid(IdnMapping m, string s, object label) { try { m.GetUnicode(s); Assert.Fail(label != null ? label.ToString() + ":" + s : s); } catch (ArgumentException) { } }
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)); }
// // Will convert a host name into its unicode equivalent expanding any existing idn names present // internal static unsafe string?UnicodeEquivalent(string idnHost, char *hostname, int start, int end) { // Test common scenario first for perf // try to get unicode equivalent try { return(s_idnMapping.GetUnicode(idnHost)); } catch (ArgumentException) { } // Here because something threw in GetUnicode above // Need to now check individual labels of they had an ace label that was not valid Idn name // or if there is a label with invalid Idn char. bool dummy = true; return(UnicodeEquivalent(hostname, start, end, ref dummy, ref dummy)); }
public Site GetSiteByDomain(string domain) { domain = _idnMapping.GetUnicode(domain); using (var iisManager = new ServerManager()) { var sites = GetSites(iisManager, false).ToList(); foreach (var s in sites) { foreach (var b in s.Bindings) { if (b.Host.Equals(domain, StringComparison.InvariantCultureIgnoreCase)) { return(s); } } } } return(null); }
public static string ExplainHostName(this string hostName) { var unicodeHostname = IDN_MAPPING.GetUnicode(hostName); if (!hostName.Equals(unicodeHostname, StringComparison.OrdinalIgnoreCase)) { return($"{unicodeHostname} ({hostName})"); } return(unicodeHostname); }
public void GetUnicode_Invalid() { foreach (IConformanceIdnaTest entry in Factory.GetDataset()) { if (!entry.UnicodeResult.Success) { var map = new IdnMapping(); Assert.Throws <ArgumentException>(() => map.GetUnicode(entry.Source)); } } }
// Token: 0x06002165 RID: 8549 RVA: 0x00079E7C File Offset: 0x0007807C private static string DecodeIdnDomain(SmtpAddress smtpAddress) { string domain = smtpAddress.Domain; if (!string.IsNullOrEmpty(domain)) { IdnMapping idnMapping = new IdnMapping(); string unicode = idnMapping.GetUnicode(domain); return(smtpAddress.Local + "@" + unicode); } return(smtpAddress.ToString()); }
public DomainName Get(string domain) { if (string.IsNullOrEmpty(domain)) { return(null); } IdnMapping mapping = new IdnMapping(); var parts = domain .ToLowerInvariant().Split('.') .Select(x => x.StartsWith("xn--")?mapping.GetUnicode(x).Trim():x.Trim()) //punycode .Reverse().ToList(); if (parts.Count == 0 || parts.Any(x => x.Equals(""))) { return(null); } var structure = this._domainDataStructure; foreach (var part in parts) { if (structure.Nested.ContainsKey(part)) { structure = structure.Nested[part]; continue; } else if (structure.Nested.ContainsKey("*")) { structure = structure.Nested["*"]; continue; } else { break; } } if (structure.TldRule == null) { return(null); } //Domain is TLD if (parts.Count == structure.TldRule.LabelCount) { return(null); } var domainName = new DomainName(domain, structure.TldRule); return(domainName); }
public string PunycodeToUnicode(string domain) { try { var mapping = new IdnMapping(); return(mapping.GetUnicode(domain)); } catch (ArgumentException e) { throw new InvalidPunycodeDomainException(e.Message); } }
public static void GetUnicodeThrows() { IdnMapping idnMapping = new IdnMapping(); Assert.Throws <ArgumentNullException>("ascii", () => idnMapping.GetUnicode(null, -5)); Assert.Throws <ArgumentNullException>("ascii", () => idnMapping.GetUnicode(null, -5, -10)); Assert.Throws <ArgumentOutOfRangeException>("index", () => idnMapping.GetUnicode("abc", -5, -10)); Assert.Throws <ArgumentOutOfRangeException>("count", () => idnMapping.GetUnicode("abc", 10, -10)); Assert.Throws <ArgumentOutOfRangeException>("byteIndex", () => idnMapping.GetUnicode("abc", 4, 99)); Assert.Throws <ArgumentOutOfRangeException>("ascii", () => idnMapping.GetUnicode("abc", 2, 2)); Assert.Throws <ArgumentException>("ascii", () => idnMapping.GetUnicode("abc", 3, 0)); }
public static void GetUnicodeThrows() { IdnMapping idnMapping = new IdnMapping(); Assert.Throws<ArgumentNullException>("ascii", () => idnMapping.GetUnicode(null, -5)); Assert.Throws<ArgumentNullException>("ascii", () => idnMapping.GetUnicode(null, -5, -10)); Assert.Throws<ArgumentOutOfRangeException>("index", () => idnMapping.GetUnicode("abc", -5, -10)); Assert.Throws<ArgumentOutOfRangeException>("count", () => idnMapping.GetUnicode("abc", 10, -10)); Assert.Throws<ArgumentOutOfRangeException>("byteIndex", () => idnMapping.GetUnicode("abc", 4, 99)); Assert.Throws<ArgumentOutOfRangeException>("ascii", () => idnMapping.GetUnicode("abc", 2, 2)); Assert.Throws<ArgumentException>("ascii", () => idnMapping.GetUnicode("abc", 3, 0)); }
private string ToUnicodeString(string input) { if (string.IsNullOrEmpty(input)) { return(input); } //if string already has (non-ascii range) unicode characters return original if (input.Any(c => c > 255)) { return(input); } return(_idnMapping.GetUnicode(input)); }
internal static unsafe string UnicodeEquivalent(string idnHost, char *hostname, int start, int end) { IdnMapping mapping = new IdnMapping(); try { return(mapping.GetUnicode(idnHost)); } catch (ArgumentException) { } bool allAscii = true; return(UnicodeEquivalent(hostname, start, end, ref allAscii, ref allAscii)); }
/// <summary> /// Transforms names with the <see cref="ACEPrefix"/> to the unicode variant and adds a trailing '.' at the end if not present. /// The original value will be kept in this instance in case it is needed. /// </summary> /// <remarks> /// The method does not parse the domain name unless it contains a <see cref="ACEPrefix"/>. /// </remarks> /// <param name="query">The value to check.</param> /// <returns>The <see cref="DnsString"/> representation.</returns> public static DnsString FromResponseQueryString(string query) { if (query.Length == 0 || query[query.Length - 1] != Dot) { query += DotStr; } if (query.Contains(ACEPrefix)) { var unicode = IDN.GetUnicode(query); return(new DnsString(unicode, query)); } return(new DnsString(query, query)); }
private async Task <Site> GetIISSiteByDomain(string domain) { if (string.IsNullOrEmpty(domain)) { return(null); } domain = _idnMapping.GetUnicode(domain); using (var iisManager = await GetDefaultServerManager()) { var sites = GetSites(iisManager, false).ToList(); foreach (var s in sites) { foreach (var b in s.Bindings) { if (b.Host.Equals(domain, StringComparison.InvariantCultureIgnoreCase)) { return(s); } } } } return(null); }
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 static string GetUnicode(string name) { if (!string.IsNullOrWhiteSpace(name) && name.Contains(idnHostNamePrefix)) { try { name = idnMapping.GetUnicode(name); } catch (ArgumentException) { // In the case of invalid punycode we will use the original name. } } return(name); }
/// <summary>Transforms names with the <see cref="ACEPrefix"/> to the unicode variant and adds a trailing '.' at the end if not present. The original value will be kept in this instance in case it is needed.</summary> /// <remarks>/// The method does not parse the domain name unless it contains a <see cref="ACEPrefix"/>./// </remarks> /// <param name="query">The value to check.</param> /// <returns>The <see cref="DnsString"/> representation.</returns> public IDnsString FromResponseQueryString(string query) { if (query.Length == 0 || query[query.Length - 1] != Dot) { query += DotStr; } if (query.Contains(ACEPrefix)) { IdnMapping idnMapping = new IdnMapping(); string unicode = idnMapping.GetUnicode(query); return(new DnsString(unicode, query)); } return(new DnsString(query, query)); }
public void GetUnicode_Invalid() { Assert.All(Factory.GetDataset().Where(entry => !entry.UnicodeResult.Success), entry => { try { var map = new IdnMapping(); AssertExtensions.Throws <ArgumentException>("ascii", () => map.GetUnicode(entry.Source)); } catch (ThrowsException) { string codePoints = GetCodePoints(entry.Source); throw new Exception($"Expected IdnMapping.GetUnicode(\"{codePoints}\") to throw an ArgumentException."); } }); }
/// <summary> /// Transforms names with the <see cref="ACEPrefix"/> to the Unicode variant and adds a trailing '.' at the end if not present. /// The original value will be kept in this instance in case it is needed. /// </summary> /// <remarks> /// The method does not parse the domain name unless it contains a <see cref="ACEPrefix"/>. /// </remarks> /// <param name="query">The value to check.</param> /// <returns>The <see cref="DnsString"/> representation.</returns> public static DnsString FromResponseQueryString(string query) { var data = query; if (query.Length == 0 || query[query.Length - 1] != Dot) { data += DotStr; } if (data.Contains(ACEPrefix)) { var unicode = IDN.GetUnicode(data); return(new DnsString(query, unicode)); } return(new DnsString(query, data)); }
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)."; // ---------------------------------------------------------------------------- Console.Clear(); 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); }
public void GetUnicode_Succes() { foreach (var entry in Factory.GetDataset()) { if (entry.GetUnicodeResult.Success) { try { var map = new 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 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)); }
public void GetUnicode_Invalid() { foreach (var entry in Factory.GetDataset()) { if (!entry.GetUnicodeResult.Success) { var map = new IdnMapping(); Assert.Throws<ArgumentException>(() => map.GetUnicode(entry.Source)); } } }