Source file src/vendor/golang.org/x/net/idna/idna10.0.0.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  //go:build go1.10
     8  
     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.
    12  //
    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"
    19  
    20  import (
    21  	"fmt"
    22  	"strings"
    23  	"unicode/utf8"
    24  
    25  	"golang.org/x/text/secure/bidirule"
    26  	"golang.org/x/text/unicode/bidi"
    27  	"golang.org/x/text/unicode/norm"
    28  )
    29  
    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.
    44  
    45  // ToASCII is a wrapper for Punycode.ToASCII.
    46  func ToASCII(s string) (string, error) {
    47  	return Punycode.process(s, true)
    48  }
    49  
    50  // ToUnicode is a wrapper for Punycode.ToUnicode.
    51  func ToUnicode(s string) (string, error) {
    52  	return Punycode.process(s, false)
    53  }
    54  
    55  // An Option configures a Profile at creation time.
    56  type Option func(*options)
    57  
    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 some 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 = transitional }
    65  }
    66  
    67  // VerifyDNSLength sets whether a Profile should fail if any of the IDN parts
    68  // are longer than allowed by the RFC.
    69  //
    70  // This option corresponds to the VerifyDnsLength flag in UTS #46.
    71  func VerifyDNSLength(verify bool) Option {
    72  	return func(o *options) { o.verifyDNSLength = verify }
    73  }
    74  
    75  // RemoveLeadingDots removes leading label separators. Leading runes that map to
    76  // dots, such as U+3002 IDEOGRAPHIC FULL STOP, are removed as well.
    77  func RemoveLeadingDots(remove bool) Option {
    78  	return func(o *options) { o.removeLeadingDots = remove }
    79  }
    80  
    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  // In particular, ValidateLabels also sets the CheckHyphens and CheckJoiners flags
    85  // in UTS #46.
    86  func ValidateLabels(enable bool) Option {
    87  	return func(o *options) {
    88  		// Don't override existing mappings, but set one that at least checks
    89  		// normalization if it is not set.
    90  		if o.mapping == nil && enable {
    91  			o.mapping = normalize
    92  		}
    93  		o.trie = trie
    94  		o.checkJoiners = enable
    95  		o.checkHyphens = enable
    96  		if enable {
    97  			o.fromPuny = validateFromPunycode
    98  		} else {
    99  			o.fromPuny = nil
   100  		}
   101  	}
   102  }
   103  
   104  // CheckHyphens sets whether to check for correct use of hyphens ('-') in
   105  // labels. Most web browsers do not have this option set, since labels such as
   106  // "r3---sn-apo3qvuoxuxbt-j5pe" are in common use.
   107  //
   108  // This option corresponds to the CheckHyphens flag in UTS #46.
   109  func CheckHyphens(enable bool) Option {
   110  	return func(o *options) { o.checkHyphens = enable }
   111  }
   112  
   113  // CheckJoiners sets whether to check the ContextJ rules as defined in Appendix
   114  // A of RFC 5892, concerning the use of joiner runes.
   115  //
   116  // This option corresponds to the CheckJoiners flag in UTS #46.
   117  func CheckJoiners(enable bool) Option {
   118  	return func(o *options) {
   119  		o.trie = trie
   120  		o.checkJoiners = enable
   121  	}
   122  }
   123  
   124  // StrictDomainName limits the set of permissible ASCII characters to those
   125  // allowed in domain names as defined in RFC 1034 (A-Z, a-z, 0-9 and the
   126  // hyphen). This is set by default for MapForLookup and ValidateForRegistration,
   127  // but is only useful if ValidateLabels is set.
   128  //
   129  // This option is useful, for instance, for browsers that allow characters
   130  // outside this range, for example a '_' (U+005F LOW LINE). See
   131  // http://www.rfc-editor.org/std/std3.txt for more details.
   132  //
   133  // This option corresponds to the UseSTD3ASCIIRules flag in UTS #46.
   134  func StrictDomainName(use bool) Option {
   135  	return func(o *options) { o.useSTD3Rules = use }
   136  }
   137  
   138  // NOTE: the following options pull in tables. The tables should not be linked
   139  // in as long as the options are not used.
   140  
   141  // BidiRule enables the Bidi rule as defined in RFC 5893. Any application
   142  // that relies on proper validation of labels should include this rule.
   143  //
   144  // This option corresponds to the CheckBidi flag in UTS #46.
   145  func BidiRule() Option {
   146  	return func(o *options) { o.bidirule = bidirule.ValidString }
   147  }
   148  
   149  // ValidateForRegistration sets validation options to verify that a given IDN is
   150  // properly formatted for registration as defined by Section 4 of RFC 5891.
   151  func ValidateForRegistration() Option {
   152  	return func(o *options) {
   153  		o.mapping = validateRegistration
   154  		StrictDomainName(true)(o)
   155  		ValidateLabels(true)(o)
   156  		VerifyDNSLength(true)(o)
   157  		BidiRule()(o)
   158  	}
   159  }
   160  
   161  // MapForLookup sets validation and mapping options such that a given IDN is
   162  // transformed for domain name lookup according to the requirements set out in
   163  // Section 5 of RFC 5891. The mappings follow the recommendations of RFC 5894,
   164  // RFC 5895 and UTS 46. It does not add the Bidi Rule. Use the BidiRule option
   165  // to add this check.
   166  //
   167  // The mappings include normalization and mapping case, width and other
   168  // compatibility mappings.
   169  func MapForLookup() Option {
   170  	return func(o *options) {
   171  		o.mapping = validateAndMap
   172  		StrictDomainName(true)(o)
   173  		ValidateLabels(true)(o)
   174  	}
   175  }
   176  
   177  type options struct {
   178  	transitional      bool
   179  	useSTD3Rules      bool
   180  	checkHyphens      bool
   181  	checkJoiners      bool
   182  	verifyDNSLength   bool
   183  	removeLeadingDots bool
   184  
   185  	trie *idnaTrie
   186  
   187  	// fromPuny calls validation rules when converting A-labels to U-labels.
   188  	fromPuny func(p *Profile, s string) error
   189  
   190  	// mapping implements a validation and mapping step as defined in RFC 5895
   191  	// or UTS 46, tailored to, for example, domain registration or lookup.
   192  	mapping func(p *Profile, s string) (mapped string, isBidi bool, err error)
   193  
   194  	// bidirule, if specified, checks whether s conforms to the Bidi Rule
   195  	// defined in RFC 5893.
   196  	bidirule func(s string) bool
   197  }
   198  
   199  // A Profile defines the configuration of an IDNA mapper.
   200  type Profile struct {
   201  	options
   202  }
   203  
   204  func apply(o *options, opts []Option) {
   205  	for _, f := range opts {
   206  		f(o)
   207  	}
   208  }
   209  
   210  // New creates a new Profile.
   211  //
   212  // With no options, the returned Profile is the most permissive and equals the
   213  // Punycode Profile. Options can be passed to further restrict the Profile. The
   214  // MapForLookup and ValidateForRegistration options set a collection of options,
   215  // for lookup and registration purposes respectively, which can be tailored by
   216  // adding more fine-grained options, where later options override earlier
   217  // options.
   218  func New(o ...Option) *Profile {
   219  	p := &Profile{}
   220  	apply(&p.options, o)
   221  	return p
   222  }
   223  
   224  // ToASCII converts a domain or domain label to its ASCII form. For example,
   225  // ToASCII("bücher.example.com") is "xn--bcher-kva.example.com", and
   226  // ToASCII("golang") is "golang". If an error is encountered it will return
   227  // an error and a (partially) processed result.
   228  func (p *Profile) ToASCII(s string) (string, error) {
   229  	return p.process(s, true)
   230  }
   231  
   232  // ToUnicode converts a domain or domain label to its Unicode form. For example,
   233  // ToUnicode("xn--bcher-kva.example.com") is "bücher.example.com", and
   234  // ToUnicode("golang") is "golang". If an error is encountered it will return
   235  // an error and a (partially) processed result.
   236  func (p *Profile) ToUnicode(s string) (string, error) {
   237  	pp := *p
   238  	pp.transitional = false
   239  	return pp.process(s, false)
   240  }
   241  
   242  // String reports a string with a description of the profile for debugging
   243  // purposes. The string format may change with different versions.
   244  func (p *Profile) String() string {
   245  	s := ""
   246  	if p.transitional {
   247  		s = "Transitional"
   248  	} else {
   249  		s = "NonTransitional"
   250  	}
   251  	if p.useSTD3Rules {
   252  		s += ":UseSTD3Rules"
   253  	}
   254  	if p.checkHyphens {
   255  		s += ":CheckHyphens"
   256  	}
   257  	if p.checkJoiners {
   258  		s += ":CheckJoiners"
   259  	}
   260  	if p.verifyDNSLength {
   261  		s += ":VerifyDNSLength"
   262  	}
   263  	return s
   264  }
   265  
   266  var (
   267  	// Punycode is a Profile that does raw punycode processing with a minimum
   268  	// of validation.
   269  	Punycode *Profile = punycode
   270  
   271  	// Lookup is the recommended profile for looking up domain names, according
   272  	// to Section 5 of RFC 5891. The exact configuration of this profile may
   273  	// change over time.
   274  	Lookup *Profile = lookup
   275  
   276  	// Display is the recommended profile for displaying domain names.
   277  	// The configuration of this profile may change over time.
   278  	Display *Profile = display
   279  
   280  	// Registration is the recommended profile for checking whether a given
   281  	// IDN is valid for registration, according to Section 4 of RFC 5891.
   282  	Registration *Profile = registration
   283  
   284  	punycode = &Profile{}
   285  	lookup   = &Profile{options{
   286  		transitional: transitionalLookup,
   287  		useSTD3Rules: true,
   288  		checkHyphens: true,
   289  		checkJoiners: true,
   290  		trie:         trie,
   291  		fromPuny:     validateFromPunycode,
   292  		mapping:      validateAndMap,
   293  		bidirule:     bidirule.ValidString,
   294  	}}
   295  	display = &Profile{options{
   296  		useSTD3Rules: true,
   297  		checkHyphens: true,
   298  		checkJoiners: true,
   299  		trie:         trie,
   300  		fromPuny:     validateFromPunycode,
   301  		mapping:      validateAndMap,
   302  		bidirule:     bidirule.ValidString,
   303  	}}
   304  	registration = &Profile{options{
   305  		useSTD3Rules:    true,
   306  		verifyDNSLength: true,
   307  		checkHyphens:    true,
   308  		checkJoiners:    true,
   309  		trie:            trie,
   310  		fromPuny:        validateFromPunycode,
   311  		mapping:         validateRegistration,
   312  		bidirule:        bidirule.ValidString,
   313  	}}
   314  
   315  	// TODO: profiles
   316  	// Register: recommended for approving domain names: don't do any mappings
   317  	// but rather reject on invalid input. Bundle or block deviation characters.
   318  )
   319  
   320  type labelError struct{ label, code_ string }
   321  
   322  func (e labelError) code() string { return e.code_ }
   323  func (e labelError) Error() string {
   324  	return fmt.Sprintf("idna: invalid label %q", e.label)
   325  }
   326  
   327  type runeError rune
   328  
   329  func (e runeError) code() string { return "P1" }
   330  func (e runeError) Error() string {
   331  	return fmt.Sprintf("idna: disallowed rune %U", e)
   332  }
   333  
   334  // process implements the algorithm described in section 4 of UTS #46,
   335  // see https://www.unicode.org/reports/tr46.
   336  func (p *Profile) process(s string, toASCII bool) (string, error) {
   337  	var err error
   338  	var isBidi bool
   339  	if p.mapping != nil {
   340  		s, isBidi, err = p.mapping(p, s)
   341  	}
   342  	// Remove leading empty labels.
   343  	if p.removeLeadingDots {
   344  		for ; len(s) > 0 && s[0] == '.'; s = s[1:] {
   345  		}
   346  	}
   347  	// TODO: allow for a quick check of the tables data.
   348  	// It seems like we should only create this error on ToASCII, but the
   349  	// UTS 46 conformance tests suggests we should always check this.
   350  	if err == nil && p.verifyDNSLength && s == "" {
   351  		err = &labelError{s, "A4"}
   352  	}
   353  	labels := labelIter{orig: s}
   354  	for ; !labels.done(); labels.next() {
   355  		label := labels.label()
   356  		if label == "" {
   357  			// Empty labels are not okay. The label iterator skips the last
   358  			// label if it is empty.
   359  			if err == nil && p.verifyDNSLength {
   360  				err = &labelError{s, "A4"}
   361  			}
   362  			continue
   363  		}
   364  		if strings.HasPrefix(label, acePrefix) {
   365  			enc := label[len(acePrefix):]
   366  			u, err2 := decode(enc)
   367  			if err2 != nil {
   368  				if err == nil {
   369  					err = err2
   370  				}
   371  				// Spec says keep the old label.
   372  				continue
   373  			}
   374  			if err == nil && len(u) > 0 && isASCII(u) {
   375  				err = punyError(enc)
   376  			}
   377  			isBidi = isBidi || bidirule.DirectionString(u) != bidi.LeftToRight
   378  			labels.set(u)
   379  			if err == nil && p.fromPuny != nil {
   380  				err = p.fromPuny(p, u)
   381  			}
   382  			if err == nil {
   383  				// This should be called on NonTransitional, according to the
   384  				// spec, but that currently does not have any effect. Use the
   385  				// original profile to preserve options.
   386  				err = p.validateLabel(u)
   387  			}
   388  		} else if err == nil {
   389  			err = p.validateLabel(label)
   390  		}
   391  	}
   392  	if isBidi && p.bidirule != nil && err == nil {
   393  		for labels.reset(); !labels.done(); labels.next() {
   394  			if !p.bidirule(labels.label()) {
   395  				err = &labelError{s, "B"}
   396  				break
   397  			}
   398  		}
   399  	}
   400  	if toASCII {
   401  		for labels.reset(); !labels.done(); labels.next() {
   402  			label := labels.label()
   403  			if !ascii(label) {
   404  				a, err2 := encode(acePrefix, label)
   405  				if err == nil {
   406  					err = err2
   407  				}
   408  				label = a
   409  				labels.set(a)
   410  			}
   411  			n := len(label)
   412  			if p.verifyDNSLength && err == nil && (n == 0 || n > 63) {
   413  				err = &labelError{label, "A4"}
   414  			}
   415  		}
   416  	}
   417  	s = labels.result()
   418  	if toASCII && p.verifyDNSLength && err == nil {
   419  		// Compute the length of the domain name minus the root label and its dot.
   420  		n := len(s)
   421  		if n > 0 && s[n-1] == '.' {
   422  			n--
   423  		}
   424  		if len(s) < 1 || n > 253 {
   425  			err = &labelError{s, "A4"}
   426  		}
   427  	}
   428  	return s, err
   429  }
   430  
   431  func isASCII(s string) bool {
   432  	for _, c := range []byte(s) {
   433  		if c >= 0x80 {
   434  			return false
   435  		}
   436  	}
   437  	return true
   438  }
   439  
   440  func normalize(p *Profile, s string) (mapped string, isBidi bool, err error) {
   441  	// TODO: consider first doing a quick check to see if any of these checks
   442  	// need to be done. This will make it slower in the general case, but
   443  	// faster in the common case.
   444  	mapped = norm.NFC.String(s)
   445  	isBidi = bidirule.DirectionString(mapped) == bidi.RightToLeft
   446  	return mapped, isBidi, nil
   447  }
   448  
   449  func validateRegistration(p *Profile, s string) (idem string, bidi bool, err error) {
   450  	// TODO: filter need for normalization in loop below.
   451  	if !norm.NFC.IsNormalString(s) {
   452  		return s, false, &labelError{s, "V1"}
   453  	}
   454  	for i := 0; i < len(s); {
   455  		v, sz := trie.lookupString(s[i:])
   456  		if sz == 0 {
   457  			return s, bidi, runeError(utf8.RuneError)
   458  		}
   459  		bidi = bidi || info(v).isBidi(s[i:])
   460  		// Copy bytes not copied so far.
   461  		switch p.simplify(info(v).category()) {
   462  		// TODO: handle the NV8 defined in the Unicode idna data set to allow
   463  		// for strict conformance to IDNA2008.
   464  		case valid, deviation:
   465  		case disallowed, mapped, unknown, ignored:
   466  			r, _ := utf8.DecodeRuneInString(s[i:])
   467  			return s, bidi, runeError(r)
   468  		}
   469  		i += sz
   470  	}
   471  	return s, bidi, nil
   472  }
   473  
   474  func (c info) isBidi(s string) bool {
   475  	if !c.isMapped() {
   476  		return c&attributesMask == rtl
   477  	}
   478  	// TODO: also store bidi info for mapped data. This is possible, but a bit
   479  	// cumbersome and not for the common case.
   480  	p, _ := bidi.LookupString(s)
   481  	switch p.Class() {
   482  	case bidi.R, bidi.AL, bidi.AN:
   483  		return true
   484  	}
   485  	return false
   486  }
   487  
   488  func validateAndMap(p *Profile, s string) (vm string, bidi bool, err error) {
   489  	var (
   490  		b []byte
   491  		k int
   492  	)
   493  	// combinedInfoBits contains the or-ed bits of all runes. We use this
   494  	// to derive the mayNeedNorm bit later. This may trigger normalization
   495  	// overeagerly, but it will not do so in the common case. The end result
   496  	// is another 10% saving on BenchmarkProfile for the common case.
   497  	var combinedInfoBits info
   498  	for i := 0; i < len(s); {
   499  		v, sz := trie.lookupString(s[i:])
   500  		if sz == 0 {
   501  			b = append(b, s[k:i]...)
   502  			b = append(b, "\ufffd"...)
   503  			k = len(s)
   504  			if err == nil {
   505  				err = runeError(utf8.RuneError)
   506  			}
   507  			break
   508  		}
   509  		combinedInfoBits |= info(v)
   510  		bidi = bidi || info(v).isBidi(s[i:])
   511  		start := i
   512  		i += sz
   513  		// Copy bytes not copied so far.
   514  		switch p.simplify(info(v).category()) {
   515  		case valid:
   516  			continue
   517  		case disallowed:
   518  			if err == nil {
   519  				r, _ := utf8.DecodeRuneInString(s[start:])
   520  				err = runeError(r)
   521  			}
   522  			continue
   523  		case mapped, deviation:
   524  			b = append(b, s[k:start]...)
   525  			b = info(v).appendMapping(b, s[start:i])
   526  		case ignored:
   527  			b = append(b, s[k:start]...)
   528  			// drop the rune
   529  		case unknown:
   530  			b = append(b, s[k:start]...)
   531  			b = append(b, "\ufffd"...)
   532  		}
   533  		k = i
   534  	}
   535  	if k == 0 {
   536  		// No changes so far.
   537  		if combinedInfoBits&mayNeedNorm != 0 {
   538  			s = norm.NFC.String(s)
   539  		}
   540  	} else {
   541  		b = append(b, s[k:]...)
   542  		if norm.NFC.QuickSpan(b) != len(b) {
   543  			b = norm.NFC.Bytes(b)
   544  		}
   545  		// TODO: the punycode converters require strings as input.
   546  		s = string(b)
   547  	}
   548  	return s, bidi, err
   549  }
   550  
   551  // A labelIter allows iterating over domain name labels.
   552  type labelIter struct {
   553  	orig     string
   554  	slice    []string
   555  	curStart int
   556  	curEnd   int
   557  	i        int
   558  }
   559  
   560  func (l *labelIter) reset() {
   561  	l.curStart = 0
   562  	l.curEnd = 0
   563  	l.i = 0
   564  }
   565  
   566  func (l *labelIter) done() bool {
   567  	return l.curStart >= len(l.orig)
   568  }
   569  
   570  func (l *labelIter) result() string {
   571  	if l.slice != nil {
   572  		return strings.Join(l.slice, ".")
   573  	}
   574  	return l.orig
   575  }
   576  
   577  func (l *labelIter) label() string {
   578  	if l.slice != nil {
   579  		return l.slice[l.i]
   580  	}
   581  	p := strings.IndexByte(l.orig[l.curStart:], '.')
   582  	l.curEnd = l.curStart + p
   583  	if p == -1 {
   584  		l.curEnd = len(l.orig)
   585  	}
   586  	return l.orig[l.curStart:l.curEnd]
   587  }
   588  
   589  // next sets the value to the next label. It skips the last label if it is empty.
   590  func (l *labelIter) next() {
   591  	l.i++
   592  	if l.slice != nil {
   593  		if l.i >= len(l.slice) || l.i == len(l.slice)-1 && l.slice[l.i] == "" {
   594  			l.curStart = len(l.orig)
   595  		}
   596  	} else {
   597  		l.curStart = l.curEnd + 1
   598  		if l.curStart == len(l.orig)-1 && l.orig[l.curStart] == '.' {
   599  			l.curStart = len(l.orig)
   600  		}
   601  	}
   602  }
   603  
   604  func (l *labelIter) set(s string) {
   605  	if l.slice == nil {
   606  		l.slice = strings.Split(l.orig, ".")
   607  	}
   608  	l.slice[l.i] = s
   609  }
   610  
   611  // acePrefix is the ASCII Compatible Encoding prefix.
   612  const acePrefix = "xn--"
   613  
   614  func (p *Profile) simplify(cat category) category {
   615  	switch cat {
   616  	case disallowedSTD3Mapped:
   617  		if p.useSTD3Rules {
   618  			cat = disallowed
   619  		} else {
   620  			cat = mapped
   621  		}
   622  	case disallowedSTD3Valid:
   623  		if p.useSTD3Rules {
   624  			cat = disallowed
   625  		} else {
   626  			cat = valid
   627  		}
   628  	case deviation:
   629  		if !p.transitional {
   630  			cat = valid
   631  		}
   632  	case validNV8, validXV8:
   633  		// TODO: handle V2008
   634  		cat = valid
   635  	}
   636  	return cat
   637  }
   638  
   639  func validateFromPunycode(p *Profile, s string) error {
   640  	if !norm.NFC.IsNormalString(s) {
   641  		return &labelError{s, "V1"}
   642  	}
   643  	// TODO: detect whether string may have to be normalized in the following
   644  	// loop.
   645  	for i := 0; i < len(s); {
   646  		v, sz := trie.lookupString(s[i:])
   647  		if sz == 0 {
   648  			return runeError(utf8.RuneError)
   649  		}
   650  		if c := p.simplify(info(v).category()); c != valid && c != deviation {
   651  			return &labelError{s, "V6"}
   652  		}
   653  		i += sz
   654  	}
   655  	return nil
   656  }
   657  
   658  const (
   659  	zwnj = "\u200c"
   660  	zwj  = "\u200d"
   661  )
   662  
   663  type joinState int8
   664  
   665  const (
   666  	stateStart joinState = iota
   667  	stateVirama
   668  	stateBefore
   669  	stateBeforeVirama
   670  	stateAfter
   671  	stateFAIL
   672  )
   673  
   674  var joinStates = [][numJoinTypes]joinState{
   675  	stateStart: {
   676  		joiningL:   stateBefore,
   677  		joiningD:   stateBefore,
   678  		joinZWNJ:   stateFAIL,
   679  		joinZWJ:    stateFAIL,
   680  		joinVirama: stateVirama,
   681  	},
   682  	stateVirama: {
   683  		joiningL: stateBefore,
   684  		joiningD: stateBefore,
   685  	},
   686  	stateBefore: {
   687  		joiningL:   stateBefore,
   688  		joiningD:   stateBefore,
   689  		joiningT:   stateBefore,
   690  		joinZWNJ:   stateAfter,
   691  		joinZWJ:    stateFAIL,
   692  		joinVirama: stateBeforeVirama,
   693  	},
   694  	stateBeforeVirama: {
   695  		joiningL: stateBefore,
   696  		joiningD: stateBefore,
   697  		joiningT: stateBefore,
   698  	},
   699  	stateAfter: {
   700  		joiningL:   stateFAIL,
   701  		joiningD:   stateBefore,
   702  		joiningT:   stateAfter,
   703  		joiningR:   stateStart,
   704  		joinZWNJ:   stateFAIL,
   705  		joinZWJ:    stateFAIL,
   706  		joinVirama: stateAfter, // no-op as we can't accept joiners here
   707  	},
   708  	stateFAIL: {
   709  		0:          stateFAIL,
   710  		joiningL:   stateFAIL,
   711  		joiningD:   stateFAIL,
   712  		joiningT:   stateFAIL,
   713  		joiningR:   stateFAIL,
   714  		joinZWNJ:   stateFAIL,
   715  		joinZWJ:    stateFAIL,
   716  		joinVirama: stateFAIL,
   717  	},
   718  }
   719  
   720  // validateLabel validates the criteria from Section 4.1. Item 1, 4, and 6 are
   721  // already implicitly satisfied by the overall implementation.
   722  func (p *Profile) validateLabel(s string) (err error) {
   723  	if s == "" {
   724  		if p.verifyDNSLength {
   725  			return &labelError{s, "A4"}
   726  		}
   727  		return nil
   728  	}
   729  	if p.checkHyphens {
   730  		if len(s) > 4 && s[2] == '-' && s[3] == '-' {
   731  			return &labelError{s, "V2"}
   732  		}
   733  		if s[0] == '-' || s[len(s)-1] == '-' {
   734  			return &labelError{s, "V3"}
   735  		}
   736  	}
   737  	if !p.checkJoiners {
   738  		return nil
   739  	}
   740  	trie := p.trie // p.checkJoiners is only set if trie is set.
   741  	// TODO: merge the use of this in the trie.
   742  	v, sz := trie.lookupString(s)
   743  	x := info(v)
   744  	if x.isModifier() {
   745  		return &labelError{s, "V5"}
   746  	}
   747  	// Quickly return in the absence of zero-width (non) joiners.
   748  	if strings.Index(s, zwj) == -1 && strings.Index(s, zwnj) == -1 {
   749  		return nil
   750  	}
   751  	st := stateStart
   752  	for i := 0; ; {
   753  		jt := x.joinType()
   754  		if s[i:i+sz] == zwj {
   755  			jt = joinZWJ
   756  		} else if s[i:i+sz] == zwnj {
   757  			jt = joinZWNJ
   758  		}
   759  		st = joinStates[st][jt]
   760  		if x.isViramaModifier() {
   761  			st = joinStates[st][joinVirama]
   762  		}
   763  		if i += sz; i == len(s) {
   764  			break
   765  		}
   766  		v, sz = trie.lookupString(s[i:])
   767  		x = info(v)
   768  	}
   769  	if st == stateFAIL || st == stateAfter {
   770  		return &labelError{s, "C"}
   771  	}
   772  	return nil
   773  }
   774  
   775  func ascii(s string) bool {
   776  	for i := 0; i < len(s); i++ {
   777  		if s[i] >= utf8.RuneSelf {
   778  			return false
   779  		}
   780  	}
   781  	return true
   782  }
   783  

View as plain text