idna.go 18 KB

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