encode function should return nil when an invalid character is detected and

ToPunycode function should return an empty string when there's an invalid
domain name
This commit is contained in:
Rafael Dantas Justo 2015-07-16 13:02:51 -03:00
parent aab9736a4e
commit 0ec31bb825
2 changed files with 12 additions and 6 deletions

View File

@ -27,8 +27,8 @@ const (
) )
// ToPunycode converts unicode domain names to DNS-appropriate punycode names. // ToPunycode converts unicode domain names to DNS-appropriate punycode names.
// This function would return incorrect result for strings for non-canonical // This function would return an empty string result for domain names with
// unicode strings. // invalid unicode strings. This function expects domain names in lowercase.
func ToPunycode(s string) string { func ToPunycode(s string) string {
tokens := dns.SplitDomainName(s) tokens := dns.SplitDomainName(s)
switch { switch {
@ -41,7 +41,11 @@ func ToPunycode(s string) string {
} }
for i := range tokens { for i := range tokens {
tokens[i] = string(encode([]byte(tokens[i]))) t := encode([]byte(tokens[i]))
if t == nil {
return ""
}
tokens[i] = string(t)
} }
return strings.Join(tokens, ".") return strings.Join(tokens, ".")
} }
@ -139,14 +143,16 @@ func tfunc(k, bias rune) rune {
return k - bias return k - bias
} }
// encode transforms Unicode input bytes (that represent DNS label) into punycode bytestream // encode transforms Unicode input bytes (that represent DNS label) into
// punycode bytestream. This function would return nil if there's an invalid
// character in the label
func encode(input []byte) []byte { func encode(input []byte) []byte {
n, bias := _N, _BIAS n, bias := _N, _BIAS
b := bytes.Runes(input) b := bytes.Runes(input)
for i := range b { for i := range b {
if !isValidRune(b[i]) { if !isValidRune(b[i]) {
return input return nil
} }
b[i] = preprune(b[i]) b[i] = preprune(b[i])

View File

@ -108,7 +108,7 @@ var invalidUnicodes = []string{
func TestInvalidUnicodes(t *testing.T) { func TestInvalidUnicodes(t *testing.T) {
for _, d := range invalidUnicodes { for _, d := range invalidUnicodes {
s := ToPunycode(d) s := ToPunycode(d)
if s != d { if s != "" {
t.Errorf("Changed invalid name %s to %#v", d, s) t.Errorf("Changed invalid name %s to %#v", d, s)
} }
} }