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/norm"
29 // NOTE: Unlike common practice in Go APIs, the functions will return a
30 // sanitized domain name in case of errors. Browsers sometimes use a partially
31 // evaluated string as lookup.
32 // TODO: the current error handling is, in my opinion, the least opinionated.
33 // Other strategies are also viable, though:
34 // Option 1) Return an empty string in case of error, but allow the user to
35 // specify explicitly which errors to ignore.
36 // Option 2) Return the partially evaluated string if it is itself a valid
37 // string, otherwise return the empty string in case of error.
38 // Option 3) Option 1 and 2.
39 // Option 4) Always return an empty string for now and implement Option 1 as
40 // needed, and document that the return string may not be empty in case of
41 // error in the future.
42 // I think Option 1 is best, but it is quite opinionated.
44 // ToASCII is a wrapper for Punycode.ToASCII.
45 func ToASCII(s string) (string, error) {
46 return Punycode.process(s, true)
49 // ToUnicode is a wrapper for Punycode.ToUnicode.
50 func ToUnicode(s string) (string, error) {
51 return Punycode.process(s, false)
54 // An Option configures a Profile at creation time.
55 type Option func(*options)
57 // Transitional sets a Profile to use the Transitional mapping as defined in UTS
58 // #46. This will cause, for example, "ß" to be mapped to "ss". Using the
59 // transitional mapping provides a compromise between IDNA2003 and IDNA2008
60 // compatibility. It is used by most browsers when resolving domain names. This
61 // option is only meaningful if combined with MapForLookup.
62 func Transitional(transitional bool) Option {
63 return func(o *options) { o.transitional = true }
66 // VerifyDNSLength sets whether a Profile should fail if any of the IDN parts
67 // are longer than allowed by the RFC.
68 func VerifyDNSLength(verify bool) Option {
69 return func(o *options) { o.verifyDNSLength = verify }
72 // RemoveLeadingDots removes leading label separators. Leading runes that map to
73 // dots, such as U+3002 IDEOGRAPHIC FULL STOP, are removed as well.
75 // This is the behavior suggested by the UTS #46 and is adopted by some
77 func RemoveLeadingDots(remove bool) Option {
78 return func(o *options) { o.removeLeadingDots = remove }
81 // ValidateLabels sets whether to check the mandatory label validation criteria
82 // as defined in Section 5.4 of RFC 5891. This includes testing for correct use
83 // of hyphens ('-'), normalization, validity of runes, and the context rules.
84 func ValidateLabels(enable bool) Option {
85 return func(o *options) {
86 // Don't override existing mappings, but set one that at least checks
87 // normalization if it is not set.
88 if o.mapping == nil && enable {
92 o.validateLabels = enable
93 o.fromPuny = validateFromPunycode
97 // StrictDomainName limits the set of permissable ASCII characters to those
98 // allowed in domain names as defined in RFC 1034 (A-Z, a-z, 0-9 and the
99 // hyphen). This is set by default for MapForLookup and ValidateForRegistration.
101 // This option is useful, for instance, for browsers that allow characters
102 // outside this range, for example a '_' (U+005F LOW LINE). See
103 // http://www.rfc-editor.org/std/std3.txt for more details This option
104 // corresponds to the UseSTD3ASCIIRules option in UTS #46.
105 func StrictDomainName(use bool) Option {
106 return func(o *options) {
109 o.fromPuny = validateFromPunycode
113 // NOTE: the following options pull in tables. The tables should not be linked
114 // in as long as the options are not used.
116 // BidiRule enables the Bidi rule as defined in RFC 5893. Any application
117 // that relies on proper validation of labels should include this rule.
118 func BidiRule() Option {
119 return func(o *options) { o.bidirule = bidirule.ValidString }
122 // ValidateForRegistration sets validation options to verify that a given IDN is
123 // properly formatted for registration as defined by Section 4 of RFC 5891.
124 func ValidateForRegistration() Option {
125 return func(o *options) {
126 o.mapping = validateRegistration
127 StrictDomainName(true)(o)
128 ValidateLabels(true)(o)
129 VerifyDNSLength(true)(o)
134 // MapForLookup sets validation and mapping options such that a given IDN is
135 // transformed for domain name lookup according to the requirements set out in
136 // Section 5 of RFC 5891. The mappings follow the recommendations of RFC 5894,
137 // RFC 5895 and UTS 46. It does not add the Bidi Rule. Use the BidiRule option
138 // to add this check.
140 // The mappings include normalization and mapping case, width and other
141 // compatibility mappings.
142 func MapForLookup() Option {
143 return func(o *options) {
144 o.mapping = validateAndMap
145 StrictDomainName(true)(o)
146 ValidateLabels(true)(o)
147 RemoveLeadingDots(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) (string, 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 a 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,
259 removeLeadingDots: true,
261 fromPuny: validateFromPunycode,
262 mapping: validateAndMap,
263 bidirule: bidirule.ValidString,
265 display = &Profile{options{
267 validateLabels: true,
268 removeLeadingDots: true,
270 fromPuny: validateFromPunycode,
271 mapping: validateAndMap,
272 bidirule: bidirule.ValidString,
274 registration = &Profile{options{
276 validateLabels: true,
277 verifyDNSLength: true,
279 fromPuny: validateFromPunycode,
280 mapping: validateRegistration,
281 bidirule: bidirule.ValidString,
285 // Register: recommended for approving domain names: don't do any mappings
286 // but rather reject on invalid input. Bundle or block deviation characters.
289 type labelError struct{ label, code_ string }
291 func (e labelError) code() string { return e.code_ }
292 func (e labelError) Error() string {
293 return fmt.Sprintf("idna: invalid label %q", e.label)
298 func (e runeError) code() string { return "P1" }
299 func (e runeError) Error() string {
300 return fmt.Sprintf("idna: disallowed rune %U", e)
303 // process implements the algorithm described in section 4 of UTS #46,
304 // see https://www.unicode.org/reports/tr46.
305 func (p *Profile) process(s string, toASCII bool) (string, error) {
307 if p.mapping != nil {
308 s, err = p.mapping(p, s)
310 // Remove leading empty labels.
311 if p.removeLeadingDots {
312 for ; len(s) > 0 && s[0] == '.'; s = s[1:] {
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.
341 if err == nil && p.validateLabels {
342 err = p.fromPuny(p, u)
345 // This should be called on NonTransitional, according to the
346 // spec, but that currently does not have any effect. Use the
347 // original profile to preserve options.
348 err = p.validateLabel(u)
350 } else if err == nil {
351 err = p.validateLabel(label)
355 for labels.reset(); !labels.done(); labels.next() {
356 label := labels.label()
358 a, err2 := encode(acePrefix, label)
366 if p.verifyDNSLength && err == nil && (n == 0 || n > 63) {
367 err = &labelError{label, "A4"}
372 if toASCII && p.verifyDNSLength && err == nil {
373 // Compute the length of the domain name minus the root label and its dot.
375 if n > 0 && s[n-1] == '.' {
378 if len(s) < 1 || n > 253 {
379 err = &labelError{s, "A4"}
385 func normalize(p *Profile, s string) (string, error) {
386 return norm.NFC.String(s), nil
389 func validateRegistration(p *Profile, s string) (string, error) {
390 if !norm.NFC.IsNormalString(s) {
391 return s, &labelError{s, "V1"}
393 for i := 0; i < len(s); {
394 v, sz := trie.lookupString(s[i:])
395 // Copy bytes not copied so far.
396 switch p.simplify(info(v).category()) {
397 // TODO: handle the NV8 defined in the Unicode idna data set to allow
398 // for strict conformance to IDNA2008.
399 case valid, deviation:
400 case disallowed, mapped, unknown, ignored:
401 r, _ := utf8.DecodeRuneInString(s[i:])
402 return s, runeError(r)
409 func validateAndMap(p *Profile, s string) (string, error) {
415 for i := 0; i < len(s); {
416 v, sz := trie.lookupString(s[i:])
419 // Copy bytes not copied so far.
420 switch p.simplify(info(v).category()) {
425 r, _ := utf8.DecodeRuneInString(s[start:])
429 case mapped, deviation:
430 b = append(b, s[k:start]...)
431 b = info(v).appendMapping(b, s[start:i])
433 b = append(b, s[k:start]...)
436 b = append(b, s[k:start]...)
437 b = append(b, "\ufffd"...)
442 // No changes so far.
443 s = norm.NFC.String(s)
445 b = append(b, s[k:]...)
446 if norm.NFC.QuickSpan(b) != len(b) {
447 b = norm.NFC.Bytes(b)
449 // TODO: the punycode converters require strings as input.
455 // A labelIter allows iterating over domain name labels.
456 type labelIter struct {
464 func (l *labelIter) reset() {
470 func (l *labelIter) done() bool {
471 return l.curStart >= len(l.orig)
474 func (l *labelIter) result() string {
476 return strings.Join(l.slice, ".")
481 func (l *labelIter) label() string {
485 p := strings.IndexByte(l.orig[l.curStart:], '.')
486 l.curEnd = l.curStart + p
488 l.curEnd = len(l.orig)
490 return l.orig[l.curStart:l.curEnd]
493 // next sets the value to the next label. It skips the last label if it is empty.
494 func (l *labelIter) next() {
497 if l.i >= len(l.slice) || l.i == len(l.slice)-1 && l.slice[l.i] == "" {
498 l.curStart = len(l.orig)
501 l.curStart = l.curEnd + 1
502 if l.curStart == len(l.orig)-1 && l.orig[l.curStart] == '.' {
503 l.curStart = len(l.orig)
508 func (l *labelIter) set(s string) {
510 l.slice = strings.Split(l.orig, ".")
515 // acePrefix is the ASCII Compatible Encoding prefix.
516 const acePrefix = "xn--"
518 func (p *Profile) simplify(cat category) category {
520 case disallowedSTD3Mapped:
526 case disallowedSTD3Valid:
536 case validNV8, validXV8:
537 // TODO: handle V2008
543 func validateFromPunycode(p *Profile, s string) error {
544 if !norm.NFC.IsNormalString(s) {
545 return &labelError{s, "V1"}
547 for i := 0; i < len(s); {
548 v, sz := trie.lookupString(s[i:])
549 if c := p.simplify(info(v).category()); c != valid && c != deviation {
550 return &labelError{s, "V6"}
565 stateStart joinState = iota
573 var joinStates = [][numJoinTypes]joinState{
575 joiningL: stateBefore,
576 joiningD: stateBefore,
579 joinVirama: stateVirama,
582 joiningL: stateBefore,
583 joiningD: stateBefore,
586 joiningL: stateBefore,
587 joiningD: stateBefore,
588 joiningT: stateBefore,
589 joinZWNJ: stateAfter,
591 joinVirama: stateBeforeVirama,
594 joiningL: stateBefore,
595 joiningD: stateBefore,
596 joiningT: stateBefore,
600 joiningD: stateBefore,
601 joiningT: stateAfter,
602 joiningR: stateStart,
605 joinVirama: stateAfter, // no-op as we can't accept joiners here
615 joinVirama: stateFAIL,
619 // validateLabel validates the criteria from Section 4.1. Item 1, 4, and 6 are
620 // already implicitly satisfied by the overall implementation.
621 func (p *Profile) validateLabel(s string) error {
623 if p.verifyDNSLength {
624 return &labelError{s, "A4"}
628 if p.bidirule != nil && !p.bidirule(s) {
629 return &labelError{s, "B"}
631 if !p.validateLabels {
634 trie := p.trie // p.validateLabels is only set if trie is set.
635 if len(s) > 4 && s[2] == '-' && s[3] == '-' {
636 return &labelError{s, "V2"}
638 if s[0] == '-' || s[len(s)-1] == '-' {
639 return &labelError{s, "V3"}
641 // TODO: merge the use of this in the trie.
642 v, sz := trie.lookupString(s)
645 return &labelError{s, "V5"}
647 // Quickly return in the absence of zero-width (non) joiners.
648 if strings.Index(s, zwj) == -1 && strings.Index(s, zwnj) == -1 {
654 if s[i:i+sz] == zwj {
656 } else if s[i:i+sz] == zwnj {
659 st = joinStates[st][jt]
660 if x.isViramaModifier() {
661 st = joinStates[st][joinVirama]
663 if i += sz; i == len(s) {
666 v, sz = trie.lookupString(s[i:])
669 if st == stateFAIL || st == stateAfter {
670 return &labelError{s, "C"}
675 func ascii(s string) bool {
676 for i := 0; i < len(s); i++ {
677 if s[i] >= utf8.RuneSelf {