1 // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT.
3 // Copyright 2016 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
9 // Package idna implements IDNA2008 using the compatibility processing
10 // defined by UTS (Unicode Technical Standard) #46, which defines a standard to
11 // deal with the transition from IDNA2003.
13 // IDNA2008 (Internationalized Domain Names for Applications), is defined in RFC
14 // 5890, RFC 5891, RFC 5892, RFC 5893 and RFC 5894.
15 // UTS #46 is defined in https://www.unicode.org/reports/tr46.
16 // See https://unicode.org/cldr/utility/idna.jsp for a visualization of the
17 // differences between these two standards.
18 package idna // import "golang.org/x/net/idna"
25 "golang.org/x/text/secure/bidirule"
26 "golang.org/x/text/unicode/bidi"
27 "golang.org/x/text/unicode/norm"
30 // NOTE: Unlike common practice in Go APIs, the functions will return a
31 // sanitized domain name in case of errors. Browsers sometimes use a partially
32 // evaluated string as lookup.
33 // TODO: the current error handling is, in my opinion, the least opinionated.
34 // Other strategies are also viable, though:
35 // Option 1) Return an empty string in case of error, but allow the user to
36 // specify explicitly which errors to ignore.
37 // Option 2) Return the partially evaluated string if it is itself a valid
38 // string, otherwise return the empty string in case of error.
39 // Option 3) Option 1 and 2.
40 // Option 4) Always return an empty string for now and implement Option 1 as
41 // needed, and document that the return string may not be empty in case of
42 // error in the future.
43 // I think Option 1 is best, but it is quite opinionated.
45 // ToASCII is a wrapper for Punycode.ToASCII.
46 func ToASCII(s string) (string, error) {
47 return Punycode.process(s, true)
50 // ToUnicode is a wrapper for Punycode.ToUnicode.
51 func ToUnicode(s string) (string, error) {
52 return Punycode.process(s, false)
55 // An Option configures a Profile at creation time.
56 type Option func(*options)
58 // Transitional sets a Profile to use the Transitional mapping as defined in UTS
59 // #46. This will cause, for example, "ß" to be mapped to "ss". Using the
60 // transitional mapping provides a compromise between IDNA2003 and IDNA2008
61 // compatibility. It is used by most browsers when resolving domain names. This
62 // option is only meaningful if combined with MapForLookup.
63 func Transitional(transitional bool) Option {
64 return func(o *options) { o.transitional = true }
67 // VerifyDNSLength sets whether a Profile should fail if any of the IDN parts
68 // are longer than allowed by the RFC.
69 func VerifyDNSLength(verify bool) Option {
70 return func(o *options) { o.verifyDNSLength = verify }
73 // RemoveLeadingDots removes leading label separators. Leading runes that map to
74 // dots, such as U+3002 IDEOGRAPHIC FULL STOP, are removed as well.
76 // This is the behavior suggested by the UTS #46 and is adopted by some
78 func RemoveLeadingDots(remove bool) Option {
79 return func(o *options) { o.removeLeadingDots = remove }
82 // ValidateLabels sets whether to check the mandatory label validation criteria
83 // as defined in Section 5.4 of RFC 5891. This includes testing for correct use
84 // of hyphens ('-'), normalization, validity of runes, and the context rules.
85 func ValidateLabels(enable bool) Option {
86 return func(o *options) {
87 // Don't override existing mappings, but set one that at least checks
88 // normalization if it is not set.
89 if o.mapping == nil && enable {
93 o.validateLabels = enable
94 o.fromPuny = validateFromPunycode
98 // StrictDomainName limits the set of permissible ASCII characters to those
99 // allowed in domain names as defined in RFC 1034 (A-Z, a-z, 0-9 and the
100 // hyphen). This is set by default for MapForLookup and ValidateForRegistration.
102 // This option is useful, for instance, for browsers that allow characters
103 // outside this range, for example a '_' (U+005F LOW LINE). See
104 // http://www.rfc-editor.org/std/std3.txt for more details This option
105 // corresponds to the UseSTD3ASCIIRules option in UTS #46.
106 func StrictDomainName(use bool) Option {
107 return func(o *options) {
110 o.fromPuny = validateFromPunycode
114 // NOTE: the following options pull in tables. The tables should not be linked
115 // in as long as the options are not used.
117 // BidiRule enables the Bidi rule as defined in RFC 5893. Any application
118 // that relies on proper validation of labels should include this rule.
119 func BidiRule() Option {
120 return func(o *options) { o.bidirule = bidirule.ValidString }
123 // ValidateForRegistration sets validation options to verify that a given IDN is
124 // properly formatted for registration as defined by Section 4 of RFC 5891.
125 func ValidateForRegistration() Option {
126 return func(o *options) {
127 o.mapping = validateRegistration
128 StrictDomainName(true)(o)
129 ValidateLabels(true)(o)
130 VerifyDNSLength(true)(o)
135 // MapForLookup sets validation and mapping options such that a given IDN is
136 // transformed for domain name lookup according to the requirements set out in
137 // Section 5 of RFC 5891. The mappings follow the recommendations of RFC 5894,
138 // RFC 5895 and UTS 46. It does not add the Bidi Rule. Use the BidiRule option
139 // to add this check.
141 // The mappings include normalization and mapping case, width and other
142 // compatibility mappings.
143 func MapForLookup() Option {
144 return func(o *options) {
145 o.mapping = validateAndMap
146 StrictDomainName(true)(o)
147 ValidateLabels(true)(o)
151 type options struct {
156 removeLeadingDots bool
160 // fromPuny calls validation rules when converting A-labels to U-labels.
161 fromPuny func(p *Profile, s string) error
163 // mapping implements a validation and mapping step as defined in RFC 5895
164 // or UTS 46, tailored to, for example, domain registration or lookup.
165 mapping func(p *Profile, s string) (mapped string, isBidi bool, err error)
167 // bidirule, if specified, checks whether s conforms to the Bidi Rule
168 // defined in RFC 5893.
169 bidirule func(s string) bool
172 // A Profile defines the configuration of an IDNA mapper.
173 type Profile struct {
177 func apply(o *options, opts []Option) {
178 for _, f := range opts {
183 // New creates a new Profile.
185 // With no options, the returned Profile is the most permissive and equals the
186 // Punycode Profile. Options can be passed to further restrict the Profile. The
187 // MapForLookup and ValidateForRegistration options set a collection of options,
188 // for lookup and registration purposes respectively, which can be tailored by
189 // adding more fine-grained options, where later options override earlier
191 func New(o ...Option) *Profile {
197 // ToASCII converts a domain or domain label to its ASCII form. For example,
198 // ToASCII("bücher.example.com") is "xn--bcher-kva.example.com", and
199 // ToASCII("golang") is "golang". If an error is encountered it will return
200 // an error and a (partially) processed result.
201 func (p *Profile) ToASCII(s string) (string, error) {
202 return p.process(s, true)
205 // ToUnicode converts a domain or domain label to its Unicode form. For example,
206 // ToUnicode("xn--bcher-kva.example.com") is "bücher.example.com", and
207 // ToUnicode("golang") is "golang". If an error is encountered it will return
208 // an error and a (partially) processed result.
209 func (p *Profile) ToUnicode(s string) (string, error) {
211 pp.transitional = false
212 return pp.process(s, false)
215 // String reports a string with a description of the profile for debugging
216 // purposes. The string format may change with different versions.
217 func (p *Profile) String() string {
222 s = "NonTransitional"
227 if p.validateLabels {
228 s += ":ValidateLabels"
230 if p.verifyDNSLength {
231 s += ":VerifyDNSLength"
237 // Punycode is a Profile that does raw punycode processing with a minimum
239 Punycode *Profile = punycode
241 // Lookup is the recommended profile for looking up domain names, according
242 // to Section 5 of RFC 5891. The exact configuration of this profile may
244 Lookup *Profile = lookup
246 // Display is the recommended profile for displaying domain names.
247 // The configuration of this profile may change over time.
248 Display *Profile = display
250 // Registration is the recommended profile for checking whether a given
251 // IDN is valid for registration, according to Section 4 of RFC 5891.
252 Registration *Profile = registration
254 punycode = &Profile{}
255 lookup = &Profile{options{
258 validateLabels: true,
260 fromPuny: validateFromPunycode,
261 mapping: validateAndMap,
262 bidirule: bidirule.ValidString,
264 display = &Profile{options{
266 validateLabels: true,
268 fromPuny: validateFromPunycode,
269 mapping: validateAndMap,
270 bidirule: bidirule.ValidString,
272 registration = &Profile{options{
274 validateLabels: true,
275 verifyDNSLength: true,
277 fromPuny: validateFromPunycode,
278 mapping: validateRegistration,
279 bidirule: bidirule.ValidString,
283 // Register: recommended for approving domain names: don't do any mappings
284 // but rather reject on invalid input. Bundle or block deviation characters.
287 type labelError struct{ label, code_ string }
289 func (e labelError) code() string { return e.code_ }
290 func (e labelError) Error() string {
291 return fmt.Sprintf("idna: invalid label %q", e.label)
296 func (e runeError) code() string { return "P1" }
297 func (e runeError) Error() string {
298 return fmt.Sprintf("idna: disallowed rune %U", e)
301 // process implements the algorithm described in section 4 of UTS #46,
302 // see https://www.unicode.org/reports/tr46.
303 func (p *Profile) process(s string, toASCII bool) (string, error) {
306 if p.mapping != nil {
307 s, isBidi, err = p.mapping(p, s)
309 // Remove leading empty labels.
310 if p.removeLeadingDots {
311 for ; len(s) > 0 && s[0] == '.'; s = s[1:] {
314 // TODO: allow for a quick check of the tables data.
315 // It seems like we should only create this error on ToASCII, but the
316 // UTS 46 conformance tests suggests we should always check this.
317 if err == nil && p.verifyDNSLength && s == "" {
318 err = &labelError{s, "A4"}
320 labels := labelIter{orig: s}
321 for ; !labels.done(); labels.next() {
322 label := labels.label()
324 // Empty labels are not okay. The label iterator skips the last
325 // label if it is empty.
326 if err == nil && p.verifyDNSLength {
327 err = &labelError{s, "A4"}
331 if strings.HasPrefix(label, acePrefix) {
332 u, err2 := decode(label[len(acePrefix):])
337 // Spec says keep the old label.
340 isBidi = isBidi || bidirule.DirectionString(u) != bidi.LeftToRight
342 if err == nil && p.validateLabels {
343 err = p.fromPuny(p, u)
346 // This should be called on NonTransitional, according to the
347 // spec, but that currently does not have any effect. Use the
348 // original profile to preserve options.
349 err = p.validateLabel(u)
351 } else if err == nil {
352 err = p.validateLabel(label)
355 if isBidi && p.bidirule != nil && err == nil {
356 for labels.reset(); !labels.done(); labels.next() {
357 if !p.bidirule(labels.label()) {
358 err = &labelError{s, "B"}
364 for labels.reset(); !labels.done(); labels.next() {
365 label := labels.label()
367 a, err2 := encode(acePrefix, label)
375 if p.verifyDNSLength && err == nil && (n == 0 || n > 63) {
376 err = &labelError{label, "A4"}
381 if toASCII && p.verifyDNSLength && err == nil {
382 // Compute the length of the domain name minus the root label and its dot.
384 if n > 0 && s[n-1] == '.' {
387 if len(s) < 1 || n > 253 {
388 err = &labelError{s, "A4"}
394 func normalize(p *Profile, s string) (mapped string, isBidi bool, err error) {
395 // TODO: consider first doing a quick check to see if any of these checks
396 // need to be done. This will make it slower in the general case, but
397 // faster in the common case.
398 mapped = norm.NFC.String(s)
399 isBidi = bidirule.DirectionString(mapped) == bidi.RightToLeft
400 return mapped, isBidi, nil
403 func validateRegistration(p *Profile, s string) (idem string, bidi bool, err error) {
404 // TODO: filter need for normalization in loop below.
405 if !norm.NFC.IsNormalString(s) {
406 return s, false, &labelError{s, "V1"}
408 for i := 0; i < len(s); {
409 v, sz := trie.lookupString(s[i:])
411 return s, bidi, runeError(utf8.RuneError)
413 bidi = bidi || info(v).isBidi(s[i:])
414 // Copy bytes not copied so far.
415 switch p.simplify(info(v).category()) {
416 // TODO: handle the NV8 defined in the Unicode idna data set to allow
417 // for strict conformance to IDNA2008.
418 case valid, deviation:
419 case disallowed, mapped, unknown, ignored:
420 r, _ := utf8.DecodeRuneInString(s[i:])
421 return s, bidi, runeError(r)
428 func (c info) isBidi(s string) bool {
430 return c&attributesMask == rtl
432 // TODO: also store bidi info for mapped data. This is possible, but a bit
433 // cumbersome and not for the common case.
434 p, _ := bidi.LookupString(s)
436 case bidi.R, bidi.AL, bidi.AN:
442 func validateAndMap(p *Profile, s string) (vm string, bidi bool, err error) {
447 // combinedInfoBits contains the or-ed bits of all runes. We use this
448 // to derive the mayNeedNorm bit later. This may trigger normalization
449 // overeagerly, but it will not do so in the common case. The end result
450 // is another 10% saving on BenchmarkProfile for the common case.
451 var combinedInfoBits info
452 for i := 0; i < len(s); {
453 v, sz := trie.lookupString(s[i:])
455 b = append(b, s[k:i]...)
456 b = append(b, "\ufffd"...)
459 err = runeError(utf8.RuneError)
463 combinedInfoBits |= info(v)
464 bidi = bidi || info(v).isBidi(s[i:])
467 // Copy bytes not copied so far.
468 switch p.simplify(info(v).category()) {
473 r, _ := utf8.DecodeRuneInString(s[start:])
477 case mapped, deviation:
478 b = append(b, s[k:start]...)
479 b = info(v).appendMapping(b, s[start:i])
481 b = append(b, s[k:start]...)
484 b = append(b, s[k:start]...)
485 b = append(b, "\ufffd"...)
490 // No changes so far.
491 if combinedInfoBits&mayNeedNorm != 0 {
492 s = norm.NFC.String(s)
495 b = append(b, s[k:]...)
496 if norm.NFC.QuickSpan(b) != len(b) {
497 b = norm.NFC.Bytes(b)
499 // TODO: the punycode converters require strings as input.
505 // A labelIter allows iterating over domain name labels.
506 type labelIter struct {
514 func (l *labelIter) reset() {
520 func (l *labelIter) done() bool {
521 return l.curStart >= len(l.orig)
524 func (l *labelIter) result() string {
526 return strings.Join(l.slice, ".")
531 func (l *labelIter) label() string {
535 p := strings.IndexByte(l.orig[l.curStart:], '.')
536 l.curEnd = l.curStart + p
538 l.curEnd = len(l.orig)
540 return l.orig[l.curStart:l.curEnd]
543 // next sets the value to the next label. It skips the last label if it is empty.
544 func (l *labelIter) next() {
547 if l.i >= len(l.slice) || l.i == len(l.slice)-1 && l.slice[l.i] == "" {
548 l.curStart = len(l.orig)
551 l.curStart = l.curEnd + 1
552 if l.curStart == len(l.orig)-1 && l.orig[l.curStart] == '.' {
553 l.curStart = len(l.orig)
558 func (l *labelIter) set(s string) {
560 l.slice = strings.Split(l.orig, ".")
565 // acePrefix is the ASCII Compatible Encoding prefix.
566 const acePrefix = "xn--"
568 func (p *Profile) simplify(cat category) category {
570 case disallowedSTD3Mapped:
576 case disallowedSTD3Valid:
586 case validNV8, validXV8:
587 // TODO: handle V2008
593 func validateFromPunycode(p *Profile, s string) error {
594 if !norm.NFC.IsNormalString(s) {
595 return &labelError{s, "V1"}
597 // TODO: detect whether string may have to be normalized in the following
599 for i := 0; i < len(s); {
600 v, sz := trie.lookupString(s[i:])
602 return runeError(utf8.RuneError)
604 if c := p.simplify(info(v).category()); c != valid && c != deviation {
605 return &labelError{s, "V6"}
620 stateStart joinState = iota
628 var joinStates = [][numJoinTypes]joinState{
630 joiningL: stateBefore,
631 joiningD: stateBefore,
634 joinVirama: stateVirama,
637 joiningL: stateBefore,
638 joiningD: stateBefore,
641 joiningL: stateBefore,
642 joiningD: stateBefore,
643 joiningT: stateBefore,
644 joinZWNJ: stateAfter,
646 joinVirama: stateBeforeVirama,
649 joiningL: stateBefore,
650 joiningD: stateBefore,
651 joiningT: stateBefore,
655 joiningD: stateBefore,
656 joiningT: stateAfter,
657 joiningR: stateStart,
660 joinVirama: stateAfter, // no-op as we can't accept joiners here
670 joinVirama: stateFAIL,
674 // validateLabel validates the criteria from Section 4.1. Item 1, 4, and 6 are
675 // already implicitly satisfied by the overall implementation.
676 func (p *Profile) validateLabel(s string) (err error) {
678 if p.verifyDNSLength {
679 return &labelError{s, "A4"}
683 if !p.validateLabels {
686 trie := p.trie // p.validateLabels is only set if trie is set.
687 if len(s) > 4 && s[2] == '-' && s[3] == '-' {
688 return &labelError{s, "V2"}
690 if s[0] == '-' || s[len(s)-1] == '-' {
691 return &labelError{s, "V3"}
693 // TODO: merge the use of this in the trie.
694 v, sz := trie.lookupString(s)
697 return &labelError{s, "V5"}
699 // Quickly return in the absence of zero-width (non) joiners.
700 if strings.Index(s, zwj) == -1 && strings.Index(s, zwnj) == -1 {
706 if s[i:i+sz] == zwj {
708 } else if s[i:i+sz] == zwnj {
711 st = joinStates[st][jt]
712 if x.isViramaModifier() {
713 st = joinStates[st][joinVirama]
715 if i += sz; i == len(s) {
718 v, sz = trie.lookupString(s[i:])
721 if st == stateFAIL || st == stateAfter {
722 return &labelError{s, "C"}
727 func ascii(s string) bool {
728 for i := 0; i < len(s); i++ {
729 if s[i] >= utf8.RuneSelf {