idna.go 24 KB

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