idna9.0.0.go 18 KB

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