idna.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. // Copied from the golang.org/x/text repo; 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 converts a domain or domain label to its ASCII form. For example,
  37. // ToASCII("bücher.example.com") is "xn--bcher-kva.example.com", and
  38. // ToASCII("golang") is "golang". If an error is encountered it will return
  39. // an error and a (partially) processed result.
  40. func ToASCII(s string) (string, error) {
  41. return Resolve.process(s, true)
  42. }
  43. // ToUnicode converts a domain or domain label to its Unicode form. For example,
  44. // ToUnicode("xn--bcher-kva.example.com") is "bücher.example.com", and
  45. // ToUnicode("golang") is "golang". If an error is encountered it will return
  46. // an error and a (partially) processed result.
  47. func ToUnicode(s string) (string, error) {
  48. return NonTransitional.process(s, false)
  49. }
  50. // An Option configures a Profile at creation time.
  51. type Option func(*options)
  52. // Transitional sets a Profile to use the Transitional mapping as defined
  53. // in UTS #46.
  54. func Transitional(transitional bool) Option {
  55. return func(o *options) { o.transitional = true }
  56. }
  57. // VerifyDNSLength sets whether a Profile should fail if any of the IDN parts
  58. // are longer than allowed by the RFC.
  59. func VerifyDNSLength(verify bool) Option {
  60. return func(o *options) { o.verifyDNSLength = verify }
  61. }
  62. // IgnoreSTD3Rules sets whether ASCII characters outside the A-Z, a-z, 0-9 and
  63. // the hyphen should be allowed. By default this is not allowed, but IDNA2003,
  64. // and as a consequence UTS #46, allows this to be overridden to support
  65. // browsers that allow characters outside this range, for example a '_' (U+005F
  66. // LOW LINE). See http://www.rfc- editor.org/std/std3.txt for more details.
  67. func IgnoreSTD3Rules(ignore bool) Option {
  68. return func(o *options) { o.ignoreSTD3Rules = ignore }
  69. }
  70. type options struct {
  71. transitional bool
  72. ignoreSTD3Rules bool
  73. verifyDNSLength bool
  74. }
  75. // A Profile defines the configuration of a IDNA mapper.
  76. type Profile struct {
  77. options
  78. }
  79. func apply(o *options, opts []Option) {
  80. for _, f := range opts {
  81. f(o)
  82. }
  83. }
  84. // New creates a new Profile.
  85. // With no options, the returned profile is the non-transitional profile as
  86. // defined in UTS #46.
  87. func New(o ...Option) *Profile {
  88. p := &Profile{}
  89. apply(&p.options, o)
  90. return p
  91. }
  92. // ToASCII converts a domain or domain label to its ASCII form. For example,
  93. // ToASCII("bücher.example.com") is "xn--bcher-kva.example.com", and
  94. // ToASCII("golang") is "golang". If an error is encountered it will return
  95. // an error and a (partially) processed result.
  96. func (p *Profile) ToASCII(s string) (string, error) {
  97. return p.process(s, true)
  98. }
  99. // ToUnicode converts a domain or domain label to its Unicode form. For example,
  100. // ToUnicode("xn--bcher-kva.example.com") is "bücher.example.com", and
  101. // ToUnicode("golang") is "golang". If an error is encountered it will return
  102. // an error and a (partially) processed result.
  103. func (p *Profile) ToUnicode(s string) (string, error) {
  104. pp := *p
  105. pp.transitional = false
  106. return pp.process(s, false)
  107. }
  108. // String reports a string with a description of the profile for debugging
  109. // purposes. The string format may change with different versions.
  110. func (p *Profile) String() string {
  111. s := ""
  112. if p.transitional {
  113. s = "Transitional"
  114. } else {
  115. s = "NonTransitional"
  116. }
  117. if p.ignoreSTD3Rules {
  118. s += ":NoSTD3Rules"
  119. }
  120. return s
  121. }
  122. var (
  123. // Resolve is the recommended profile for resolving domain names.
  124. // The configuration of this profile may change over time.
  125. Resolve = resolve
  126. // Display is the recommended profile for displaying domain names.
  127. // The configuration of this profile may change over time.
  128. Display = display
  129. // NonTransitional defines a profile that implements the Transitional
  130. // mapping as defined in UTS #46 with no additional constraints.
  131. NonTransitional = nonTransitional
  132. resolve = &Profile{options{transitional: true}}
  133. display = &Profile{}
  134. nonTransitional = &Profile{}
  135. // TODO: profiles
  136. // V2008: strict IDNA2008
  137. // Register: recommended for approving domain names: nontransitional, but
  138. // bundle or block deviation characters.
  139. )
  140. type labelError struct{ label, code_ string }
  141. func (e labelError) code() string { return e.code_ }
  142. func (e labelError) Error() string {
  143. return fmt.Sprintf("idna: invalid label %q", e.label)
  144. }
  145. type runeError rune
  146. func (e runeError) code() string { return "P1" }
  147. func (e runeError) Error() string {
  148. return fmt.Sprintf("idna: disallowed rune %U", e)
  149. }
  150. // process implements the algorithm described in section 4 of UTS #46,
  151. // see http://www.unicode.org/reports/tr46.
  152. func (p *Profile) process(s string, toASCII bool) (string, error) {
  153. var (
  154. b []byte
  155. err error
  156. k, i int
  157. )
  158. for i < len(s) {
  159. v, sz := trie.lookupString(s[i:])
  160. start := i
  161. i += sz
  162. // Copy bytes not copied so far.
  163. switch p.simplify(info(v).category()) {
  164. case valid:
  165. continue
  166. case disallowed:
  167. if err == nil {
  168. r, _ := utf8.DecodeRuneInString(s[i:])
  169. err = runeError(r)
  170. }
  171. continue
  172. case mapped, deviation:
  173. b = append(b, s[k:start]...)
  174. b = info(v).appendMapping(b, s[start:i])
  175. case ignored:
  176. b = append(b, s[k:start]...)
  177. // drop the rune
  178. case unknown:
  179. b = append(b, s[k:start]...)
  180. b = append(b, "\ufffd"...)
  181. }
  182. k = i
  183. }
  184. if k == 0 {
  185. // No changes so far.
  186. s = norm.NFC.String(s)
  187. } else {
  188. b = append(b, s[k:]...)
  189. if norm.NFC.QuickSpan(b) != len(b) {
  190. b = norm.NFC.Bytes(b)
  191. }
  192. // TODO: the punycode converters require strings as input.
  193. s = string(b)
  194. }
  195. // Remove leading empty labels
  196. for ; len(s) > 0 && s[0] == '.'; s = s[1:] {
  197. }
  198. if s == "" {
  199. return "", &labelError{s, "A4"}
  200. }
  201. labels := labelIter{orig: s}
  202. for ; !labels.done(); labels.next() {
  203. label := labels.label()
  204. if label == "" {
  205. // Empty labels are not okay. The label iterator skips the last
  206. // label if it is empty.
  207. if err == nil {
  208. err = &labelError{s, "A4"}
  209. }
  210. continue
  211. }
  212. if strings.HasPrefix(label, acePrefix) {
  213. u, err2 := decode(label[len(acePrefix):])
  214. if err2 != nil {
  215. if err == nil {
  216. err = err2
  217. }
  218. // Spec says keep the old label.
  219. continue
  220. }
  221. labels.set(u)
  222. if err == nil {
  223. err = p.validateFromPunycode(u)
  224. }
  225. if err == nil {
  226. err = NonTransitional.validate(u)
  227. }
  228. } else if err == nil {
  229. err = p.validate(label)
  230. }
  231. }
  232. if toASCII {
  233. for labels.reset(); !labels.done(); labels.next() {
  234. label := labels.label()
  235. if !ascii(label) {
  236. a, err2 := encode(acePrefix, label)
  237. if err == nil {
  238. err = err2
  239. }
  240. label = a
  241. labels.set(a)
  242. }
  243. n := len(label)
  244. if p.verifyDNSLength && err == nil && (n == 0 || n > 63) {
  245. err = &labelError{label, "A4"}
  246. }
  247. }
  248. }
  249. s = labels.result()
  250. if toASCII && p.verifyDNSLength && err == nil {
  251. // Compute the length of the domain name minus the root label and its dot.
  252. n := len(s)
  253. if n > 0 && s[n-1] == '.' {
  254. n--
  255. }
  256. if len(s) < 1 || n > 253 {
  257. err = &labelError{s, "A4"}
  258. }
  259. }
  260. return s, err
  261. }
  262. // A labelIter allows iterating over domain name labels.
  263. type labelIter struct {
  264. orig string
  265. slice []string
  266. curStart int
  267. curEnd int
  268. i int
  269. }
  270. func (l *labelIter) reset() {
  271. l.curStart = 0
  272. l.curEnd = 0
  273. l.i = 0
  274. }
  275. func (l *labelIter) done() bool {
  276. return l.curStart >= len(l.orig)
  277. }
  278. func (l *labelIter) result() string {
  279. if l.slice != nil {
  280. return strings.Join(l.slice, ".")
  281. }
  282. return l.orig
  283. }
  284. func (l *labelIter) label() string {
  285. if l.slice != nil {
  286. return l.slice[l.i]
  287. }
  288. p := strings.IndexByte(l.orig[l.curStart:], '.')
  289. l.curEnd = l.curStart + p
  290. if p == -1 {
  291. l.curEnd = len(l.orig)
  292. }
  293. return l.orig[l.curStart:l.curEnd]
  294. }
  295. // next sets the value to the next label. It skips the last label if it is empty.
  296. func (l *labelIter) next() {
  297. l.i++
  298. if l.slice != nil {
  299. if l.i >= len(l.slice) || l.i == len(l.slice)-1 && l.slice[l.i] == "" {
  300. l.curStart = len(l.orig)
  301. }
  302. } else {
  303. l.curStart = l.curEnd + 1
  304. if l.curStart == len(l.orig)-1 && l.orig[l.curStart] == '.' {
  305. l.curStart = len(l.orig)
  306. }
  307. }
  308. }
  309. func (l *labelIter) set(s string) {
  310. if l.slice == nil {
  311. l.slice = strings.Split(l.orig, ".")
  312. }
  313. l.slice[l.i] = s
  314. }
  315. // acePrefix is the ASCII Compatible Encoding prefix.
  316. const acePrefix = "xn--"
  317. func (p *Profile) simplify(cat category) category {
  318. switch cat {
  319. case disallowedSTD3Mapped:
  320. if !p.ignoreSTD3Rules {
  321. cat = disallowed
  322. } else {
  323. cat = mapped
  324. }
  325. case disallowedSTD3Valid:
  326. if !p.ignoreSTD3Rules {
  327. cat = disallowed
  328. } else {
  329. cat = valid
  330. }
  331. case deviation:
  332. if !p.transitional {
  333. cat = valid
  334. }
  335. case validNV8, validXV8:
  336. // TODO: handle V2008
  337. cat = valid
  338. }
  339. return cat
  340. }
  341. func (p *Profile) validateFromPunycode(s string) error {
  342. if !norm.NFC.IsNormalString(s) {
  343. return &labelError{s, "V1"}
  344. }
  345. for i := 0; i < len(s); {
  346. v, sz := trie.lookupString(s[i:])
  347. if c := p.simplify(info(v).category()); c != valid && c != deviation {
  348. return &labelError{s, "V6"}
  349. }
  350. i += sz
  351. }
  352. return nil
  353. }
  354. const (
  355. zwnj = "\u200c"
  356. zwj = "\u200d"
  357. )
  358. type joinState int8
  359. const (
  360. stateStart joinState = iota
  361. stateVirama
  362. stateBefore
  363. stateBeforeVirama
  364. stateAfter
  365. stateFAIL
  366. )
  367. var joinStates = [][numJoinTypes]joinState{
  368. stateStart: {
  369. joiningL: stateBefore,
  370. joiningD: stateBefore,
  371. joinZWNJ: stateFAIL,
  372. joinZWJ: stateFAIL,
  373. joinVirama: stateVirama,
  374. },
  375. stateVirama: {
  376. joiningL: stateBefore,
  377. joiningD: stateBefore,
  378. },
  379. stateBefore: {
  380. joiningL: stateBefore,
  381. joiningD: stateBefore,
  382. joiningT: stateBefore,
  383. joinZWNJ: stateAfter,
  384. joinZWJ: stateFAIL,
  385. joinVirama: stateBeforeVirama,
  386. },
  387. stateBeforeVirama: {
  388. joiningL: stateBefore,
  389. joiningD: stateBefore,
  390. joiningT: stateBefore,
  391. },
  392. stateAfter: {
  393. joiningL: stateFAIL,
  394. joiningD: stateBefore,
  395. joiningT: stateAfter,
  396. joiningR: stateStart,
  397. joinZWNJ: stateFAIL,
  398. joinZWJ: stateFAIL,
  399. joinVirama: stateAfter, // no-op as we can't accept joiners here
  400. },
  401. stateFAIL: {
  402. 0: stateFAIL,
  403. joiningL: stateFAIL,
  404. joiningD: stateFAIL,
  405. joiningT: stateFAIL,
  406. joiningR: stateFAIL,
  407. joinZWNJ: stateFAIL,
  408. joinZWJ: stateFAIL,
  409. joinVirama: stateFAIL,
  410. },
  411. }
  412. // validate validates the criteria from Section 4.1. Item 1, 4, and 6 are
  413. // already implicitly satisfied by the overall implementation.
  414. func (p *Profile) validate(s string) error {
  415. if len(s) > 4 && s[2] == '-' && s[3] == '-' {
  416. return &labelError{s, "V2"}
  417. }
  418. if s[0] == '-' || s[len(s)-1] == '-' {
  419. return &labelError{s, "V3"}
  420. }
  421. // TODO: merge the use of this in the trie.
  422. v, sz := trie.lookupString(s)
  423. x := info(v)
  424. if x.isModifier() {
  425. return &labelError{s, "V5"}
  426. }
  427. if !bidirule.ValidString(s) {
  428. return &labelError{s, "B"}
  429. }
  430. // Quickly return in the absence of zero-width (non) joiners.
  431. if strings.Index(s, zwj) == -1 && strings.Index(s, zwnj) == -1 {
  432. return nil
  433. }
  434. st := stateStart
  435. for i := 0; ; {
  436. jt := x.joinType()
  437. if s[i:i+sz] == zwj {
  438. jt = joinZWJ
  439. } else if s[i:i+sz] == zwnj {
  440. jt = joinZWNJ
  441. }
  442. st = joinStates[st][jt]
  443. if x.isViramaModifier() {
  444. st = joinStates[st][joinVirama]
  445. }
  446. if i += sz; i == len(s) {
  447. break
  448. }
  449. v, sz = trie.lookupString(s[i:])
  450. x = info(v)
  451. }
  452. if st == stateFAIL || st == stateAfter {
  453. return &labelError{s, "C"}
  454. }
  455. return nil
  456. }
  457. func ascii(s string) bool {
  458. for i := 0; i < len(s); i++ {
  459. if s[i] >= utf8.RuneSelf {
  460. return false
  461. }
  462. }
  463. return true
  464. }