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.
7 // Package idna implements IDNA2008 using the compatibility processing
8 // defined by UTS (Unicode Technical Standard) #46, which defines a standard to
9 // deal with the transition from IDNA2003.
11 // IDNA2008 (Internationalized Domain Names for Applications), is defined in RFC
12 // 5890, RFC 5891, RFC 5892, RFC 5893 and RFC 5894.
13 // UTS #46 is defined in http://www.unicode.org/reports/tr46.
14 // See http://unicode.org/cldr/utility/idna.jsp for a visualization of the
15 // differences between these two standards.
16 package idna // import "golang.org/x/net/idna"
23 "golang.org/x/text/secure/bidirule"
24 "golang.org/x/text/unicode/norm"
27 // NOTE: Unlike common practice in Go APIs, the functions will return a
28 // sanitized domain name in case of errors. Browsers sometimes use a partially
29 // evaluated string as lookup.
30 // TODO: the current error handling is, in my opinion, the least opinionated.
31 // Other strategies are also viable, though:
32 // Option 1) Return an empty string in case of error, but allow the user to
33 // specify explicitly which errors to ignore.
34 // Option 2) Return the partially evaluated string if it is itself a valid
35 // string, otherwise return the empty string in case of error.
36 // Option 3) Option 1 and 2.
37 // Option 4) Always return an empty string for now and implement Option 1 as
38 // needed, and document that the return string may not be empty in case of
39 // error in the future.
40 // I think Option 1 is best, but it is quite opinionated.
42 // ToASCII is a wrapper for Punycode.ToASCII.
43 func ToASCII(s string) (string, error) {
44 return Punycode.process(s, true)
47 // ToUnicode is a wrapper for Punycode.ToUnicode.
48 func ToUnicode(s string) (string, error) {
49 return Punycode.process(s, false)
52 // An Option configures a Profile at creation time.
53 type Option func(*options)
55 // Transitional sets a Profile to use the Transitional mapping as defined in UTS
56 // #46. This will cause, for example, "ß" to be mapped to "ss". Using the
57 // transitional mapping provides a compromise between IDNA2003 and IDNA2008
58 // compatibility. It is used by most browsers when resolving domain names. This
59 // option is only meaningful if combined with MapForLookup.
60 func Transitional(transitional bool) Option {
61 return func(o *options) { o.transitional = true }
64 // VerifyDNSLength sets whether a Profile should fail if any of the IDN parts
65 // are longer than allowed by the RFC.
66 func VerifyDNSLength(verify bool) Option {
67 return func(o *options) { o.verifyDNSLength = verify }
70 // RemoveLeadingDots removes leading label separators. Leading runes that map to
71 // dots, such as U+3002, are removed as well.
73 // This is the behavior suggested by the UTS #46 and is adopted by some
75 func RemoveLeadingDots(remove bool) Option {
76 return func(o *options) { o.removeLeadingDots = remove }
79 // ValidateLabels sets whether to check the mandatory label validation criteria
80 // as defined in Section 5.4 of RFC 5891. This includes testing for correct use
81 // of hyphens ('-'), normalization, validity of runes, and the context rules.
82 func ValidateLabels(enable bool) Option {
83 return func(o *options) {
84 // Don't override existing mappings, but set one that at least checks
85 // normalization if it is not set.
86 if o.mapping == nil && enable {
90 o.validateLabels = enable
91 o.fromPuny = validateFromPunycode
95 // StrictDomainName limits the set of permissable ASCII characters to those
96 // allowed in domain names as defined in RFC 1034 (A-Z, a-z, 0-9 and the
97 // hyphen). This is set by default for MapForLookup and ValidateForRegistration.
99 // This option is useful, for instance, for browsers that allow characters
100 // outside this range, for example a '_' (U+005F LOW LINE). See
101 // http://www.rfc-editor.org/std/std3.txt for more details This option
102 // corresponds to the UseSTD3ASCIIRules option in UTS #46.
103 func StrictDomainName(use bool) Option {
104 return func(o *options) {
107 o.fromPuny = validateFromPunycode
111 // NOTE: the following options pull in tables. The tables should not be linked
112 // in as long as the options are not used.
114 // BidiRule enables the Bidi rule as defined in RFC 5893. Any application
115 // that relies on proper validation of labels should include this rule.
116 func BidiRule() Option {
117 return func(o *options) { o.bidirule = bidirule.ValidString }
120 // ValidateForRegistration sets validation options to verify that a given IDN is
121 // properly formatted for registration as defined by Section 4 of RFC 5891.
122 func ValidateForRegistration() Option {
123 return func(o *options) {
124 o.mapping = validateRegistration
125 StrictDomainName(true)(o)
126 ValidateLabels(true)(o)
127 VerifyDNSLength(true)(o)
132 // MapForLookup sets validation and mapping options such that a given IDN is
133 // transformed for domain name lookup according to the requirements set out in
134 // Section 5 of RFC 5891. The mappings follow the recommendations of RFC 5894,
135 // RFC 5895 and UTS 46. It does not add the Bidi Rule. Use the BidiRule option
136 // to add this check.
138 // The mappings include normalization and mapping case, width and other
139 // compatibility mappings.
140 func MapForLookup() Option {
141 return func(o *options) {
142 o.mapping = validateAndMap
143 StrictDomainName(true)(o)
144 ValidateLabels(true)(o)
145 RemoveLeadingDots(true)(o)
149 type options struct {
154 removeLeadingDots bool
158 // fromPuny calls validation rules when converting A-labels to U-labels.
159 fromPuny func(p *Profile, s string) error
161 // mapping implements a validation and mapping step as defined in RFC 5895
162 // or UTS 46, tailored to, for example, domain registration or lookup.
163 mapping func(p *Profile, s string) (string, error)
165 // bidirule, if specified, checks whether s conforms to the Bidi Rule
166 // defined in RFC 5893.
167 bidirule func(s string) bool
170 // A Profile defines the configuration of a IDNA mapper.
171 type Profile struct {
175 func apply(o *options, opts []Option) {
176 for _, f := range opts {
181 // New creates a new Profile.
183 // With no options, the returned Profile is the most permissive and equals the
184 // Punycode Profile. Options can be passed to further restrict the Profile. The
185 // MapForLookup and ValidateForRegistration options set a collection of options,
186 // for lookup and registration purposes respectively, which can be tailored by
187 // adding more fine-grained options, where later options override earlier
189 func New(o ...Option) *Profile {
195 // ToASCII converts a domain or domain label to its ASCII form. For example,
196 // ToASCII("bücher.example.com") is "xn--bcher-kva.example.com", and
197 // ToASCII("golang") is "golang". If an error is encountered it will return
198 // an error and a (partially) processed result.
199 func (p *Profile) ToASCII(s string) (string, error) {
200 return p.process(s, true)
203 // ToUnicode converts a domain or domain label to its Unicode form. For example,
204 // ToUnicode("xn--bcher-kva.example.com") is "bücher.example.com", and
205 // ToUnicode("golang") is "golang". If an error is encountered it will return
206 // an error and a (partially) processed result.
207 func (p *Profile) ToUnicode(s string) (string, error) {
209 pp.transitional = false
210 return pp.process(s, false)
213 // String reports a string with a description of the profile for debugging
214 // purposes. The string format may change with different versions.
215 func (p *Profile) String() string {
220 s = "NonTransitional"
225 if p.validateLabels {
226 s += ":ValidateLabels"
228 if p.verifyDNSLength {
229 s += ":VerifyDNSLength"
235 // Punycode is a Profile that does raw punycode processing with a minimum
237 Punycode *Profile = punycode
239 // Lookup is the recommended profile for looking up domain names, according
240 // to Section 5 of RFC 5891. The exact configuration of this profile may
242 Lookup *Profile = lookup
244 // Display is the recommended profile for displaying domain names.
245 // The configuration of this profile may change over time.
246 Display *Profile = display
248 // Registration is the recommended profile for checking whether a given
249 // IDN is valid for registration, according to Section 4 of RFC 5891.
250 Registration *Profile = registration
252 punycode = &Profile{}
253 lookup = &Profile{options{
256 validateLabels: true,
257 removeLeadingDots: true,
259 fromPuny: validateFromPunycode,
260 mapping: validateAndMap,
261 bidirule: bidirule.ValidString,
263 display = &Profile{options{
265 validateLabels: true,
266 removeLeadingDots: 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 http://www.unicode.org/reports/tr46.
303 func (p *Profile) process(s string, toASCII bool) (string, error) {
305 if p.mapping != nil {
306 s, err = p.mapping(p, s)
308 // Remove leading empty labels.
309 if p.removeLeadingDots {
310 for ; len(s) > 0 && s[0] == '.'; s = s[1:] {
313 // It seems like we should only create this error on ToASCII, but the
314 // UTS 46 conformance tests suggests we should always check this.
315 if err == nil && p.verifyDNSLength && s == "" {
316 err = &labelError{s, "A4"}
318 labels := labelIter{orig: s}
319 for ; !labels.done(); labels.next() {
320 label := labels.label()
322 // Empty labels are not okay. The label iterator skips the last
323 // label if it is empty.
324 if err == nil && p.verifyDNSLength {
325 err = &labelError{s, "A4"}
329 if strings.HasPrefix(label, acePrefix) {
330 u, err2 := decode(label[len(acePrefix):])
335 // Spec says keep the old label.
339 if err == nil && p.validateLabels {
340 err = p.fromPuny(p, u)
343 // This should be called on NonTransitional, according to the
344 // spec, but that currently does not have any effect. Use the
345 // original profile to preserve options.
346 err = p.validateLabel(u)
348 } else if err == nil {
349 err = p.validateLabel(label)
353 for labels.reset(); !labels.done(); labels.next() {
354 label := labels.label()
356 a, err2 := encode(acePrefix, label)
364 if p.verifyDNSLength && err == nil && (n == 0 || n > 63) {
365 err = &labelError{label, "A4"}
370 if toASCII && p.verifyDNSLength && err == nil {
371 // Compute the length of the domain name minus the root label and its dot.
373 if n > 0 && s[n-1] == '.' {
376 if len(s) < 1 || n > 253 {
377 err = &labelError{s, "A4"}
383 func normalize(p *Profile, s string) (string, error) {
384 return norm.NFC.String(s), nil
387 func validateRegistration(p *Profile, s string) (string, error) {
388 if !norm.NFC.IsNormalString(s) {
389 return s, &labelError{s, "V1"}
391 for i := 0; i < len(s); {
392 v, sz := trie.lookupString(s[i:])
393 // Copy bytes not copied so far.
394 switch p.simplify(info(v).category()) {
395 // TODO: handle the NV8 defined in the Unicode idna data set to allow
396 // for strict conformance to IDNA2008.
397 case valid, deviation:
398 case disallowed, mapped, unknown, ignored:
399 r, _ := utf8.DecodeRuneInString(s[i:])
400 return s, runeError(r)
407 func validateAndMap(p *Profile, s string) (string, error) {
413 for i := 0; i < len(s); {
414 v, sz := trie.lookupString(s[i:])
417 // Copy bytes not copied so far.
418 switch p.simplify(info(v).category()) {
423 r, _ := utf8.DecodeRuneInString(s[start:])
427 case mapped, deviation:
428 b = append(b, s[k:start]...)
429 b = info(v).appendMapping(b, s[start:i])
431 b = append(b, s[k:start]...)
434 b = append(b, s[k:start]...)
435 b = append(b, "\ufffd"...)
440 // No changes so far.
441 s = norm.NFC.String(s)
443 b = append(b, s[k:]...)
444 if norm.NFC.QuickSpan(b) != len(b) {
445 b = norm.NFC.Bytes(b)
447 // TODO: the punycode converters require strings as input.
453 // A labelIter allows iterating over domain name labels.
454 type labelIter struct {
462 func (l *labelIter) reset() {
468 func (l *labelIter) done() bool {
469 return l.curStart >= len(l.orig)
472 func (l *labelIter) result() string {
474 return strings.Join(l.slice, ".")
479 func (l *labelIter) label() string {
483 p := strings.IndexByte(l.orig[l.curStart:], '.')
484 l.curEnd = l.curStart + p
486 l.curEnd = len(l.orig)
488 return l.orig[l.curStart:l.curEnd]
491 // next sets the value to the next label. It skips the last label if it is empty.
492 func (l *labelIter) next() {
495 if l.i >= len(l.slice) || l.i == len(l.slice)-1 && l.slice[l.i] == "" {
496 l.curStart = len(l.orig)
499 l.curStart = l.curEnd + 1
500 if l.curStart == len(l.orig)-1 && l.orig[l.curStart] == '.' {
501 l.curStart = len(l.orig)
506 func (l *labelIter) set(s string) {
508 l.slice = strings.Split(l.orig, ".")
513 // acePrefix is the ASCII Compatible Encoding prefix.
514 const acePrefix = "xn--"
516 func (p *Profile) simplify(cat category) category {
518 case disallowedSTD3Mapped:
524 case disallowedSTD3Valid:
534 case validNV8, validXV8:
535 // TODO: handle V2008
541 func validateFromPunycode(p *Profile, s string) error {
542 if !norm.NFC.IsNormalString(s) {
543 return &labelError{s, "V1"}
545 for i := 0; i < len(s); {
546 v, sz := trie.lookupString(s[i:])
547 if c := p.simplify(info(v).category()); c != valid && c != deviation {
548 return &labelError{s, "V6"}
563 stateStart joinState = iota
571 var joinStates = [][numJoinTypes]joinState{
573 joiningL: stateBefore,
574 joiningD: stateBefore,
577 joinVirama: stateVirama,
580 joiningL: stateBefore,
581 joiningD: stateBefore,
584 joiningL: stateBefore,
585 joiningD: stateBefore,
586 joiningT: stateBefore,
587 joinZWNJ: stateAfter,
589 joinVirama: stateBeforeVirama,
592 joiningL: stateBefore,
593 joiningD: stateBefore,
594 joiningT: stateBefore,
598 joiningD: stateBefore,
599 joiningT: stateAfter,
600 joiningR: stateStart,
603 joinVirama: stateAfter, // no-op as we can't accept joiners here
613 joinVirama: stateFAIL,
617 // validateLabel validates the criteria from Section 4.1. Item 1, 4, and 6 are
618 // already implicitly satisfied by the overall implementation.
619 func (p *Profile) validateLabel(s string) error {
621 if p.verifyDNSLength {
622 return &labelError{s, "A4"}
626 if p.bidirule != nil && !p.bidirule(s) {
627 return &labelError{s, "B"}
629 if !p.validateLabels {
632 trie := p.trie // p.validateLabels is only set if trie is set.
633 if len(s) > 4 && s[2] == '-' && s[3] == '-' {
634 return &labelError{s, "V2"}
636 if s[0] == '-' || s[len(s)-1] == '-' {
637 return &labelError{s, "V3"}
639 // TODO: merge the use of this in the trie.
640 v, sz := trie.lookupString(s)
643 return &labelError{s, "V5"}
645 // Quickly return in the absence of zero-width (non) joiners.
646 if strings.Index(s, zwj) == -1 && strings.Index(s, zwnj) == -1 {
652 if s[i:i+sz] == zwj {
654 } else if s[i:i+sz] == zwnj {
657 st = joinStates[st][jt]
658 if x.isViramaModifier() {
659 st = joinStates[st][joinVirama]
661 if i += sz; i == len(s) {
664 v, sz = trie.lookupString(s[i:])
667 if st == stateFAIL || st == stateAfter {
668 return &labelError{s, "C"}
673 func ascii(s string) bool {
674 for i := 0; i < len(s); i++ {
675 if s[i] >= utf8.RuneSelf {