OSDN Git Service

new repo
[bytom/vapor.git] / vendor / golang.org / x / net / idna / idna.go
1 // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT.
2
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.
6
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.
10 //
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"
17
18 import (
19         "fmt"
20         "strings"
21         "unicode/utf8"
22
23         "golang.org/x/text/secure/bidirule"
24         "golang.org/x/text/unicode/norm"
25 )
26
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.
41
42 // ToASCII is a wrapper for Punycode.ToASCII.
43 func ToASCII(s string) (string, error) {
44         return Punycode.process(s, true)
45 }
46
47 // ToUnicode is a wrapper for Punycode.ToUnicode.
48 func ToUnicode(s string) (string, error) {
49         return Punycode.process(s, false)
50 }
51
52 // An Option configures a Profile at creation time.
53 type Option func(*options)
54
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 }
62 }
63
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 }
68 }
69
70 // RemoveLeadingDots removes leading label separators. Leading runes that map to
71 // dots, such as U+3002, are removed as well.
72 //
73 // This is the behavior suggested by the UTS #46 and is adopted by some
74 // browsers.
75 func RemoveLeadingDots(remove bool) Option {
76         return func(o *options) { o.removeLeadingDots = remove }
77 }
78
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 {
87                         o.mapping = normalize
88                 }
89                 o.trie = trie
90                 o.validateLabels = enable
91                 o.fromPuny = validateFromPunycode
92         }
93 }
94
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.
98 //
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) {
105                 o.trie = trie
106                 o.useSTD3Rules = use
107                 o.fromPuny = validateFromPunycode
108         }
109 }
110
111 // NOTE: the following options pull in tables. The tables should not be linked
112 // in as long as the options are not used.
113
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 }
118 }
119
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)
128                 BidiRule()(o)
129         }
130 }
131
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.
137 //
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)
146         }
147 }
148
149 type options struct {
150         transitional      bool
151         useSTD3Rules      bool
152         validateLabels    bool
153         verifyDNSLength   bool
154         removeLeadingDots bool
155
156         trie *idnaTrie
157
158         // fromPuny calls validation rules when converting A-labels to U-labels.
159         fromPuny func(p *Profile, s string) error
160
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)
164
165         // bidirule, if specified, checks whether s conforms to the Bidi Rule
166         // defined in RFC 5893.
167         bidirule func(s string) bool
168 }
169
170 // A Profile defines the configuration of a IDNA mapper.
171 type Profile struct {
172         options
173 }
174
175 func apply(o *options, opts []Option) {
176         for _, f := range opts {
177                 f(o)
178         }
179 }
180
181 // New creates a new Profile.
182 //
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
188 // options.
189 func New(o ...Option) *Profile {
190         p := &Profile{}
191         apply(&p.options, o)
192         return p
193 }
194
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)
201 }
202
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) {
208         pp := *p
209         pp.transitional = false
210         return pp.process(s, false)
211 }
212
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 {
216         s := ""
217         if p.transitional {
218                 s = "Transitional"
219         } else {
220                 s = "NonTransitional"
221         }
222         if p.useSTD3Rules {
223                 s += ":UseSTD3Rules"
224         }
225         if p.validateLabels {
226                 s += ":ValidateLabels"
227         }
228         if p.verifyDNSLength {
229                 s += ":VerifyDNSLength"
230         }
231         return s
232 }
233
234 var (
235         // Punycode is a Profile that does raw punycode processing with a minimum
236         // of validation.
237         Punycode *Profile = punycode
238
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
241         // change over time.
242         Lookup *Profile = lookup
243
244         // Display is the recommended profile for displaying domain names.
245         // The configuration of this profile may change over time.
246         Display *Profile = display
247
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
251
252         punycode = &Profile{}
253         lookup   = &Profile{options{
254                 transitional:      true,
255                 useSTD3Rules:      true,
256                 validateLabels:    true,
257                 removeLeadingDots: true,
258                 trie:              trie,
259                 fromPuny:          validateFromPunycode,
260                 mapping:           validateAndMap,
261                 bidirule:          bidirule.ValidString,
262         }}
263         display = &Profile{options{
264                 useSTD3Rules:      true,
265                 validateLabels:    true,
266                 removeLeadingDots: true,
267                 trie:              trie,
268                 fromPuny:          validateFromPunycode,
269                 mapping:           validateAndMap,
270                 bidirule:          bidirule.ValidString,
271         }}
272         registration = &Profile{options{
273                 useSTD3Rules:    true,
274                 validateLabels:  true,
275                 verifyDNSLength: true,
276                 trie:            trie,
277                 fromPuny:        validateFromPunycode,
278                 mapping:         validateRegistration,
279                 bidirule:        bidirule.ValidString,
280         }}
281
282         // TODO: profiles
283         // Register: recommended for approving domain names: don't do any mappings
284         // but rather reject on invalid input. Bundle or block deviation characters.
285 )
286
287 type labelError struct{ label, code_ string }
288
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)
292 }
293
294 type runeError rune
295
296 func (e runeError) code() string { return "P1" }
297 func (e runeError) Error() string {
298         return fmt.Sprintf("idna: disallowed rune %U", e)
299 }
300
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) {
304         var err error
305         if p.mapping != nil {
306                 s, err = p.mapping(p, s)
307         }
308         // Remove leading empty labels.
309         if p.removeLeadingDots {
310                 for ; len(s) > 0 && s[0] == '.'; s = s[1:] {
311                 }
312         }
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"}
317         }
318         labels := labelIter{orig: s}
319         for ; !labels.done(); labels.next() {
320                 label := labels.label()
321                 if 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"}
326                         }
327                         continue
328                 }
329                 if strings.HasPrefix(label, acePrefix) {
330                         u, err2 := decode(label[len(acePrefix):])
331                         if err2 != nil {
332                                 if err == nil {
333                                         err = err2
334                                 }
335                                 // Spec says keep the old label.
336                                 continue
337                         }
338                         labels.set(u)
339                         if err == nil && p.validateLabels {
340                                 err = p.fromPuny(p, u)
341                         }
342                         if err == nil {
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)
347                         }
348                 } else if err == nil {
349                         err = p.validateLabel(label)
350                 }
351         }
352         if toASCII {
353                 for labels.reset(); !labels.done(); labels.next() {
354                         label := labels.label()
355                         if !ascii(label) {
356                                 a, err2 := encode(acePrefix, label)
357                                 if err == nil {
358                                         err = err2
359                                 }
360                                 label = a
361                                 labels.set(a)
362                         }
363                         n := len(label)
364                         if p.verifyDNSLength && err == nil && (n == 0 || n > 63) {
365                                 err = &labelError{label, "A4"}
366                         }
367                 }
368         }
369         s = labels.result()
370         if toASCII && p.verifyDNSLength && err == nil {
371                 // Compute the length of the domain name minus the root label and its dot.
372                 n := len(s)
373                 if n > 0 && s[n-1] == '.' {
374                         n--
375                 }
376                 if len(s) < 1 || n > 253 {
377                         err = &labelError{s, "A4"}
378                 }
379         }
380         return s, err
381 }
382
383 func normalize(p *Profile, s string) (string, error) {
384         return norm.NFC.String(s), nil
385 }
386
387 func validateRegistration(p *Profile, s string) (string, error) {
388         if !norm.NFC.IsNormalString(s) {
389                 return s, &labelError{s, "V1"}
390         }
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)
401                 }
402                 i += sz
403         }
404         return s, nil
405 }
406
407 func validateAndMap(p *Profile, s string) (string, error) {
408         var (
409                 err error
410                 b   []byte
411                 k   int
412         )
413         for i := 0; i < len(s); {
414                 v, sz := trie.lookupString(s[i:])
415                 start := i
416                 i += sz
417                 // Copy bytes not copied so far.
418                 switch p.simplify(info(v).category()) {
419                 case valid:
420                         continue
421                 case disallowed:
422                         if err == nil {
423                                 r, _ := utf8.DecodeRuneInString(s[start:])
424                                 err = runeError(r)
425                         }
426                         continue
427                 case mapped, deviation:
428                         b = append(b, s[k:start]...)
429                         b = info(v).appendMapping(b, s[start:i])
430                 case ignored:
431                         b = append(b, s[k:start]...)
432                         // drop the rune
433                 case unknown:
434                         b = append(b, s[k:start]...)
435                         b = append(b, "\ufffd"...)
436                 }
437                 k = i
438         }
439         if k == 0 {
440                 // No changes so far.
441                 s = norm.NFC.String(s)
442         } else {
443                 b = append(b, s[k:]...)
444                 if norm.NFC.QuickSpan(b) != len(b) {
445                         b = norm.NFC.Bytes(b)
446                 }
447                 // TODO: the punycode converters require strings as input.
448                 s = string(b)
449         }
450         return s, err
451 }
452
453 // A labelIter allows iterating over domain name labels.
454 type labelIter struct {
455         orig     string
456         slice    []string
457         curStart int
458         curEnd   int
459         i        int
460 }
461
462 func (l *labelIter) reset() {
463         l.curStart = 0
464         l.curEnd = 0
465         l.i = 0
466 }
467
468 func (l *labelIter) done() bool {
469         return l.curStart >= len(l.orig)
470 }
471
472 func (l *labelIter) result() string {
473         if l.slice != nil {
474                 return strings.Join(l.slice, ".")
475         }
476         return l.orig
477 }
478
479 func (l *labelIter) label() string {
480         if l.slice != nil {
481                 return l.slice[l.i]
482         }
483         p := strings.IndexByte(l.orig[l.curStart:], '.')
484         l.curEnd = l.curStart + p
485         if p == -1 {
486                 l.curEnd = len(l.orig)
487         }
488         return l.orig[l.curStart:l.curEnd]
489 }
490
491 // next sets the value to the next label. It skips the last label if it is empty.
492 func (l *labelIter) next() {
493         l.i++
494         if l.slice != nil {
495                 if l.i >= len(l.slice) || l.i == len(l.slice)-1 && l.slice[l.i] == "" {
496                         l.curStart = len(l.orig)
497                 }
498         } else {
499                 l.curStart = l.curEnd + 1
500                 if l.curStart == len(l.orig)-1 && l.orig[l.curStart] == '.' {
501                         l.curStart = len(l.orig)
502                 }
503         }
504 }
505
506 func (l *labelIter) set(s string) {
507         if l.slice == nil {
508                 l.slice = strings.Split(l.orig, ".")
509         }
510         l.slice[l.i] = s
511 }
512
513 // acePrefix is the ASCII Compatible Encoding prefix.
514 const acePrefix = "xn--"
515
516 func (p *Profile) simplify(cat category) category {
517         switch cat {
518         case disallowedSTD3Mapped:
519                 if p.useSTD3Rules {
520                         cat = disallowed
521                 } else {
522                         cat = mapped
523                 }
524         case disallowedSTD3Valid:
525                 if p.useSTD3Rules {
526                         cat = disallowed
527                 } else {
528                         cat = valid
529                 }
530         case deviation:
531                 if !p.transitional {
532                         cat = valid
533                 }
534         case validNV8, validXV8:
535                 // TODO: handle V2008
536                 cat = valid
537         }
538         return cat
539 }
540
541 func validateFromPunycode(p *Profile, s string) error {
542         if !norm.NFC.IsNormalString(s) {
543                 return &labelError{s, "V1"}
544         }
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"}
549                 }
550                 i += sz
551         }
552         return nil
553 }
554
555 const (
556         zwnj = "\u200c"
557         zwj  = "\u200d"
558 )
559
560 type joinState int8
561
562 const (
563         stateStart joinState = iota
564         stateVirama
565         stateBefore
566         stateBeforeVirama
567         stateAfter
568         stateFAIL
569 )
570
571 var joinStates = [][numJoinTypes]joinState{
572         stateStart: {
573                 joiningL:   stateBefore,
574                 joiningD:   stateBefore,
575                 joinZWNJ:   stateFAIL,
576                 joinZWJ:    stateFAIL,
577                 joinVirama: stateVirama,
578         },
579         stateVirama: {
580                 joiningL: stateBefore,
581                 joiningD: stateBefore,
582         },
583         stateBefore: {
584                 joiningL:   stateBefore,
585                 joiningD:   stateBefore,
586                 joiningT:   stateBefore,
587                 joinZWNJ:   stateAfter,
588                 joinZWJ:    stateFAIL,
589                 joinVirama: stateBeforeVirama,
590         },
591         stateBeforeVirama: {
592                 joiningL: stateBefore,
593                 joiningD: stateBefore,
594                 joiningT: stateBefore,
595         },
596         stateAfter: {
597                 joiningL:   stateFAIL,
598                 joiningD:   stateBefore,
599                 joiningT:   stateAfter,
600                 joiningR:   stateStart,
601                 joinZWNJ:   stateFAIL,
602                 joinZWJ:    stateFAIL,
603                 joinVirama: stateAfter, // no-op as we can't accept joiners here
604         },
605         stateFAIL: {
606                 0:          stateFAIL,
607                 joiningL:   stateFAIL,
608                 joiningD:   stateFAIL,
609                 joiningT:   stateFAIL,
610                 joiningR:   stateFAIL,
611                 joinZWNJ:   stateFAIL,
612                 joinZWJ:    stateFAIL,
613                 joinVirama: stateFAIL,
614         },
615 }
616
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 {
620         if s == "" {
621                 if p.verifyDNSLength {
622                         return &labelError{s, "A4"}
623                 }
624                 return nil
625         }
626         if p.bidirule != nil && !p.bidirule(s) {
627                 return &labelError{s, "B"}
628         }
629         if !p.validateLabels {
630                 return nil
631         }
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"}
635         }
636         if s[0] == '-' || s[len(s)-1] == '-' {
637                 return &labelError{s, "V3"}
638         }
639         // TODO: merge the use of this in the trie.
640         v, sz := trie.lookupString(s)
641         x := info(v)
642         if x.isModifier() {
643                 return &labelError{s, "V5"}
644         }
645         // Quickly return in the absence of zero-width (non) joiners.
646         if strings.Index(s, zwj) == -1 && strings.Index(s, zwnj) == -1 {
647                 return nil
648         }
649         st := stateStart
650         for i := 0; ; {
651                 jt := x.joinType()
652                 if s[i:i+sz] == zwj {
653                         jt = joinZWJ
654                 } else if s[i:i+sz] == zwnj {
655                         jt = joinZWNJ
656                 }
657                 st = joinStates[st][jt]
658                 if x.isViramaModifier() {
659                         st = joinStates[st][joinVirama]
660                 }
661                 if i += sz; i == len(s) {
662                         break
663                 }
664                 v, sz = trie.lookupString(s[i:])
665                 x = info(v)
666         }
667         if st == stateFAIL || st == stateAfter {
668                 return &labelError{s, "C"}
669         }
670         return nil
671 }
672
673 func ascii(s string) bool {
674         for i := 0; i < len(s); i++ {
675                 if s[i] >= utf8.RuneSelf {
676                         return false
677                 }
678         }
679         return true
680 }