idna10.0.0.go 21 KB

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