The reconcile package is used for DOM reconcilation in Isomorphic Go web applications.

idna.go 18KB

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