gen.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. // Copyright 2012 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // +build ignore
  5. package main
  6. // This program generates table.go and table_test.go.
  7. // Invoke as:
  8. //
  9. // go run gen.go -version "xxx" >table.go
  10. // go run gen.go -version "xxx" -test >table_test.go
  11. //
  12. // The version is derived from information found at
  13. // https://hg.mozilla.org/mozilla-central/log/tip/netwerk/dns/effective_tld_names.dat
  14. //
  15. // To fetch a particular hg revision, such as 05b11a8d1ace, pass
  16. // -url "https://hg.mozilla.org/mozilla-central/raw-file/05b11a8d1ace/netwerk/dns/effective_tld_names.dat"
  17. import (
  18. "bufio"
  19. "bytes"
  20. "flag"
  21. "fmt"
  22. "go/format"
  23. "io"
  24. "net/http"
  25. "os"
  26. "regexp"
  27. "sort"
  28. "strings"
  29. "code.google.com/p/go.net/idna"
  30. )
  31. const (
  32. nodesBitsChildren = 9
  33. nodesBitsICANN = 1
  34. nodesBitsTextOffset = 15
  35. nodesBitsTextLength = 6
  36. childrenBitsWildcard = 1
  37. childrenBitsNodeType = 2
  38. childrenBitsHi = 14
  39. childrenBitsLo = 14
  40. )
  41. var (
  42. maxChildren int
  43. maxTextOffset int
  44. maxTextLength int
  45. maxHi uint32
  46. maxLo uint32
  47. )
  48. func max(a, b int) int {
  49. if a < b {
  50. return b
  51. }
  52. return a
  53. }
  54. func u32max(a, b uint32) uint32 {
  55. if a < b {
  56. return b
  57. }
  58. return a
  59. }
  60. const (
  61. nodeTypeNormal = 0
  62. nodeTypeException = 1
  63. nodeTypeParentOnly = 2
  64. numNodeType = 3
  65. )
  66. func nodeTypeStr(n int) string {
  67. switch n {
  68. case nodeTypeNormal:
  69. return "+"
  70. case nodeTypeException:
  71. return "!"
  72. case nodeTypeParentOnly:
  73. return "o"
  74. }
  75. panic("unreachable")
  76. }
  77. var (
  78. labelEncoding = map[string]uint32{}
  79. labelsList = []string{}
  80. labelsMap = map[string]bool{}
  81. rules = []string{}
  82. // validSuffix is used to check that the entries in the public suffix list
  83. // are in canonical form (after Punycode encoding). Specifically, capital
  84. // letters are not allowed.
  85. validSuffix = regexp.MustCompile(`^[a-z0-9_\!\*\-\.]+$`)
  86. crush = flag.Bool("crush", true, "make the generated node text as small as possible")
  87. subset = flag.Bool("subset", false, "generate only a subset of the full table, for debugging")
  88. url = flag.String("url",
  89. "https://publicsuffix.org/list/effective_tld_names.dat",
  90. "URL of the publicsuffix.org list. If empty, stdin is read instead")
  91. v = flag.Bool("v", false, "verbose output (to stderr)")
  92. version = flag.String("version", "", "the effective_tld_names.dat version")
  93. test = flag.Bool("test", false, "generate table_test.go")
  94. )
  95. func main() {
  96. if err := main1(); err != nil {
  97. fmt.Fprintln(os.Stderr, err)
  98. os.Exit(1)
  99. }
  100. }
  101. func main1() error {
  102. flag.Parse()
  103. if nodesBitsTextLength+nodesBitsTextOffset+nodesBitsICANN+nodesBitsChildren > 32 {
  104. return fmt.Errorf("not enough bits to encode the nodes table")
  105. }
  106. if childrenBitsLo+childrenBitsHi+childrenBitsNodeType+childrenBitsWildcard > 32 {
  107. return fmt.Errorf("not enough bits to encode the children table")
  108. }
  109. if *version == "" {
  110. return fmt.Errorf("-version was not specified")
  111. }
  112. var r io.Reader = os.Stdin
  113. if *url != "" {
  114. res, err := http.Get(*url)
  115. if err != nil {
  116. return err
  117. }
  118. if res.StatusCode != http.StatusOK {
  119. return fmt.Errorf("bad GET status for %s: %d", *url, res.Status)
  120. }
  121. r = res.Body
  122. defer res.Body.Close()
  123. }
  124. var root node
  125. icann := false
  126. buf := new(bytes.Buffer)
  127. br := bufio.NewReader(r)
  128. for {
  129. s, err := br.ReadString('\n')
  130. if err != nil {
  131. if err == io.EOF {
  132. break
  133. }
  134. return err
  135. }
  136. s = strings.TrimSpace(s)
  137. if strings.Contains(s, "BEGIN ICANN DOMAINS") {
  138. icann = true
  139. continue
  140. }
  141. if strings.Contains(s, "END ICANN DOMAINS") {
  142. icann = false
  143. continue
  144. }
  145. if s == "" || strings.HasPrefix(s, "//") {
  146. continue
  147. }
  148. s, err = idna.ToASCII(s)
  149. if err != nil {
  150. return err
  151. }
  152. if !validSuffix.MatchString(s) {
  153. return fmt.Errorf("bad publicsuffix.org list data: %q", s)
  154. }
  155. if *subset {
  156. switch {
  157. case s == "ac.jp" || strings.HasSuffix(s, ".ac.jp"):
  158. case s == "ak.us" || strings.HasSuffix(s, ".ak.us"):
  159. case s == "ao" || strings.HasSuffix(s, ".ao"):
  160. case s == "ar" || strings.HasSuffix(s, ".ar"):
  161. case s == "arpa" || strings.HasSuffix(s, ".arpa"):
  162. case s == "cy" || strings.HasSuffix(s, ".cy"):
  163. case s == "dyndns.org" || strings.HasSuffix(s, ".dyndns.org"):
  164. case s == "jp":
  165. case s == "kobe.jp" || strings.HasSuffix(s, ".kobe.jp"):
  166. case s == "kyoto.jp" || strings.HasSuffix(s, ".kyoto.jp"):
  167. case s == "om" || strings.HasSuffix(s, ".om"):
  168. case s == "uk" || strings.HasSuffix(s, ".uk"):
  169. case s == "uk.com" || strings.HasSuffix(s, ".uk.com"):
  170. case s == "tw" || strings.HasSuffix(s, ".tw"):
  171. case s == "zw" || strings.HasSuffix(s, ".zw"):
  172. case s == "xn--p1ai" || strings.HasSuffix(s, ".xn--p1ai"):
  173. // xn--p1ai is Russian-Cyrillic "рф".
  174. default:
  175. continue
  176. }
  177. }
  178. rules = append(rules, s)
  179. nt, wildcard := nodeTypeNormal, false
  180. switch {
  181. case strings.HasPrefix(s, "*."):
  182. s, nt = s[2:], nodeTypeParentOnly
  183. wildcard = true
  184. case strings.HasPrefix(s, "!"):
  185. s, nt = s[1:], nodeTypeException
  186. }
  187. labels := strings.Split(s, ".")
  188. for n, i := &root, len(labels)-1; i >= 0; i-- {
  189. label := labels[i]
  190. n = n.child(label)
  191. if i == 0 {
  192. if nt != nodeTypeParentOnly && n.nodeType == nodeTypeParentOnly {
  193. n.nodeType = nt
  194. }
  195. n.icann = n.icann && icann
  196. n.wildcard = n.wildcard || wildcard
  197. }
  198. labelsMap[label] = true
  199. }
  200. }
  201. labelsList = make([]string, 0, len(labelsMap))
  202. for label := range labelsMap {
  203. labelsList = append(labelsList, label)
  204. }
  205. sort.Strings(labelsList)
  206. p := printReal
  207. if *test {
  208. p = printTest
  209. }
  210. if err := p(buf, &root); err != nil {
  211. return err
  212. }
  213. b, err := format.Source(buf.Bytes())
  214. if err != nil {
  215. return err
  216. }
  217. _, err = os.Stdout.Write(b)
  218. return err
  219. }
  220. func printTest(w io.Writer, n *node) error {
  221. fmt.Fprintf(w, "// generated by go run gen.go; DO NOT EDIT\n\n")
  222. fmt.Fprintf(w, "package publicsuffix\n\nvar rules = [...]string{\n")
  223. for _, rule := range rules {
  224. fmt.Fprintf(w, "%q,\n", rule)
  225. }
  226. fmt.Fprintf(w, "}\n\nvar nodeLabels = [...]string{\n")
  227. if err := n.walk(w, printNodeLabel); err != nil {
  228. return err
  229. }
  230. fmt.Fprintf(w, "}\n")
  231. return nil
  232. }
  233. func printReal(w io.Writer, n *node) error {
  234. const header = `// generated by go run gen.go; DO NOT EDIT
  235. package publicsuffix
  236. const version = %q
  237. const (
  238. nodesBitsChildren = %d
  239. nodesBitsICANN = %d
  240. nodesBitsTextOffset = %d
  241. nodesBitsTextLength = %d
  242. childrenBitsWildcard = %d
  243. childrenBitsNodeType = %d
  244. childrenBitsHi = %d
  245. childrenBitsLo = %d
  246. )
  247. const (
  248. nodeTypeNormal = %d
  249. nodeTypeException = %d
  250. nodeTypeParentOnly = %d
  251. )
  252. // numTLD is the number of top level domains.
  253. const numTLD = %d
  254. `
  255. fmt.Fprintf(w, header, *version,
  256. nodesBitsChildren, nodesBitsICANN, nodesBitsTextOffset, nodesBitsTextLength,
  257. childrenBitsWildcard, childrenBitsNodeType, childrenBitsHi, childrenBitsLo,
  258. nodeTypeNormal, nodeTypeException, nodeTypeParentOnly, len(n.children))
  259. text := makeText()
  260. if text == "" {
  261. return fmt.Errorf("internal error: makeText returned no text")
  262. }
  263. for _, label := range labelsList {
  264. offset, length := strings.Index(text, label), len(label)
  265. if offset < 0 {
  266. return fmt.Errorf("internal error: could not find %q in text %q", label, text)
  267. }
  268. maxTextOffset, maxTextLength = max(maxTextOffset, offset), max(maxTextLength, length)
  269. if offset >= 1<<nodesBitsTextOffset || length >= 1<<nodesBitsTextLength {
  270. return fmt.Errorf("text offset/length is too large: %d/%d", offset, length)
  271. }
  272. labelEncoding[label] = uint32(offset)<<nodesBitsTextLength | uint32(length)
  273. }
  274. fmt.Fprintf(w, "// Text is the combined text of all labels.\nconst text = ")
  275. for len(text) > 0 {
  276. n, plus := len(text), ""
  277. if n > 64 {
  278. n, plus = 64, " +"
  279. }
  280. fmt.Fprintf(w, "%q%s\n", text[:n], plus)
  281. text = text[n:]
  282. }
  283. n.walk(w, assignIndexes)
  284. fmt.Fprintf(w, `
  285. // nodes is the list of nodes. Each node is represented as a uint32, which
  286. // encodes the node's children, wildcard bit and node type (as an index into
  287. // the children array), ICANN bit and text.
  288. //
  289. // In the //-comment after each node's data, the nodes indexes of the children
  290. // are formatted as (n0x1234-n0x1256), with * denoting the wildcard bit. The
  291. // nodeType is printed as + for normal, ! for exception, and o for parent-only
  292. // nodes that have children but don't match a domain label in their own right.
  293. // An I denotes an ICANN domain.
  294. //
  295. // The layout within the uint32, from MSB to LSB, is:
  296. // [%2d bits] unused
  297. // [%2d bits] children index
  298. // [%2d bits] ICANN bit
  299. // [%2d bits] text index
  300. // [%2d bits] text length
  301. var nodes = [...]uint32{
  302. `,
  303. 32-nodesBitsChildren-nodesBitsICANN-nodesBitsTextOffset-nodesBitsTextLength,
  304. nodesBitsChildren, nodesBitsICANN, nodesBitsTextOffset, nodesBitsTextLength)
  305. if err := n.walk(w, printNode); err != nil {
  306. return err
  307. }
  308. fmt.Fprintf(w, `}
  309. // children is the list of nodes' children, the parent's wildcard bit and the
  310. // parent's node type. If a node has no children then their children index
  311. // will be in the range [0, 6), depending on the wildcard bit and node type.
  312. //
  313. // The layout within the uint32, from MSB to LSB, is:
  314. // [%2d bits] unused
  315. // [%2d bits] wildcard bit
  316. // [%2d bits] node type
  317. // [%2d bits] high nodes index (exclusive) of children
  318. // [%2d bits] low nodes index (inclusive) of children
  319. var children=[...]uint32{
  320. `,
  321. 32-childrenBitsWildcard-childrenBitsNodeType-childrenBitsHi-childrenBitsLo,
  322. childrenBitsWildcard, childrenBitsNodeType, childrenBitsHi, childrenBitsLo)
  323. for i, c := range childrenEncoding {
  324. s := "---------------"
  325. lo := c & (1<<childrenBitsLo - 1)
  326. hi := (c >> childrenBitsLo) & (1<<childrenBitsHi - 1)
  327. if lo != hi {
  328. s = fmt.Sprintf("n0x%04x-n0x%04x", lo, hi)
  329. }
  330. nodeType := int(c>>(childrenBitsLo+childrenBitsHi)) & (1<<childrenBitsNodeType - 1)
  331. wildcard := c>>(childrenBitsLo+childrenBitsHi+childrenBitsNodeType) != 0
  332. fmt.Fprintf(w, "0x%08x, // c0x%04x (%s)%s %s\n",
  333. c, i, s, wildcardStr(wildcard), nodeTypeStr(nodeType))
  334. }
  335. fmt.Fprintf(w, "}\n\n")
  336. fmt.Fprintf(w, "// max children %d (capacity %d)\n", maxChildren, 1<<nodesBitsChildren-1)
  337. fmt.Fprintf(w, "// max text offset %d (capacity %d)\n", maxTextOffset, 1<<nodesBitsTextOffset-1)
  338. fmt.Fprintf(w, "// max text length %d (capacity %d)\n", maxTextLength, 1<<nodesBitsTextLength-1)
  339. fmt.Fprintf(w, "// max hi %d (capacity %d)\n", maxHi, 1<<childrenBitsHi-1)
  340. fmt.Fprintf(w, "// max lo %d (capacity %d)\n", maxLo, 1<<childrenBitsLo-1)
  341. return nil
  342. }
  343. type node struct {
  344. label string
  345. nodeType int
  346. icann bool
  347. wildcard bool
  348. // nodesIndex and childrenIndex are the index of this node in the nodes
  349. // and the index of its children offset/length in the children arrays.
  350. nodesIndex, childrenIndex int
  351. // firstChild is the index of this node's first child, or zero if this
  352. // node has no children.
  353. firstChild int
  354. // children are the node's children, in strictly increasing node label order.
  355. children []*node
  356. }
  357. func (n *node) walk(w io.Writer, f func(w1 io.Writer, n1 *node) error) error {
  358. if err := f(w, n); err != nil {
  359. return err
  360. }
  361. for _, c := range n.children {
  362. if err := c.walk(w, f); err != nil {
  363. return err
  364. }
  365. }
  366. return nil
  367. }
  368. // child returns the child of n with the given label. The child is created if
  369. // it did not exist beforehand.
  370. func (n *node) child(label string) *node {
  371. for _, c := range n.children {
  372. if c.label == label {
  373. return c
  374. }
  375. }
  376. c := &node{
  377. label: label,
  378. nodeType: nodeTypeParentOnly,
  379. icann: true,
  380. }
  381. n.children = append(n.children, c)
  382. sort.Sort(byLabel(n.children))
  383. return c
  384. }
  385. type byLabel []*node
  386. func (b byLabel) Len() int { return len(b) }
  387. func (b byLabel) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
  388. func (b byLabel) Less(i, j int) bool { return b[i].label < b[j].label }
  389. var nextNodesIndex int
  390. // childrenEncoding are the encoded entries in the generated children array.
  391. // All these pre-defined entries have no children.
  392. var childrenEncoding = []uint32{
  393. 0 << (childrenBitsLo + childrenBitsHi), // Without wildcard bit, nodeTypeNormal.
  394. 1 << (childrenBitsLo + childrenBitsHi), // Without wildcard bit, nodeTypeException.
  395. 2 << (childrenBitsLo + childrenBitsHi), // Without wildcard bit, nodeTypeParentOnly.
  396. 4 << (childrenBitsLo + childrenBitsHi), // With wildcard bit, nodeTypeNormal.
  397. 5 << (childrenBitsLo + childrenBitsHi), // With wildcard bit, nodeTypeException.
  398. 6 << (childrenBitsLo + childrenBitsHi), // With wildcard bit, nodeTypeParentOnly.
  399. }
  400. var firstCallToAssignIndexes = true
  401. func assignIndexes(w io.Writer, n *node) error {
  402. if len(n.children) != 0 {
  403. // Assign nodesIndex.
  404. n.firstChild = nextNodesIndex
  405. for _, c := range n.children {
  406. c.nodesIndex = nextNodesIndex
  407. nextNodesIndex++
  408. }
  409. // The root node's children is implicit.
  410. if firstCallToAssignIndexes {
  411. firstCallToAssignIndexes = false
  412. return nil
  413. }
  414. // Assign childrenIndex.
  415. maxChildren = max(maxChildren, len(childrenEncoding))
  416. if len(childrenEncoding) >= 1<<nodesBitsChildren {
  417. return fmt.Errorf("children table is too large")
  418. }
  419. n.childrenIndex = len(childrenEncoding)
  420. lo := uint32(n.firstChild)
  421. hi := lo + uint32(len(n.children))
  422. maxLo, maxHi = u32max(maxLo, lo), u32max(maxHi, hi)
  423. if lo >= 1<<childrenBitsLo || hi >= 1<<childrenBitsHi {
  424. return fmt.Errorf("children lo/hi is too large: %d/%d", lo, hi)
  425. }
  426. enc := hi<<childrenBitsLo | lo
  427. enc |= uint32(n.nodeType) << (childrenBitsLo + childrenBitsHi)
  428. if n.wildcard {
  429. enc |= 1 << (childrenBitsLo + childrenBitsHi + childrenBitsNodeType)
  430. }
  431. childrenEncoding = append(childrenEncoding, enc)
  432. } else {
  433. n.childrenIndex = n.nodeType
  434. if n.wildcard {
  435. n.childrenIndex += numNodeType
  436. }
  437. }
  438. return nil
  439. }
  440. func printNode(w io.Writer, n *node) error {
  441. for _, c := range n.children {
  442. s := "---------------"
  443. if len(c.children) != 0 {
  444. s = fmt.Sprintf("n0x%04x-n0x%04x", c.firstChild, c.firstChild+len(c.children))
  445. }
  446. encoding := labelEncoding[c.label]
  447. if c.icann {
  448. encoding |= 1 << (nodesBitsTextLength + nodesBitsTextOffset)
  449. }
  450. encoding |= uint32(c.childrenIndex) << (nodesBitsTextLength + nodesBitsTextOffset + nodesBitsICANN)
  451. fmt.Fprintf(w, "0x%08x, // n0x%04x c0x%04x (%s)%s %s %s %s\n",
  452. encoding, c.nodesIndex, c.childrenIndex, s, wildcardStr(c.wildcard),
  453. nodeTypeStr(c.nodeType), icannStr(c.icann), c.label,
  454. )
  455. }
  456. return nil
  457. }
  458. func printNodeLabel(w io.Writer, n *node) error {
  459. for _, c := range n.children {
  460. fmt.Fprintf(w, "%q,\n", c.label)
  461. }
  462. return nil
  463. }
  464. func icannStr(icann bool) string {
  465. if icann {
  466. return "I"
  467. }
  468. return " "
  469. }
  470. func wildcardStr(wildcard bool) string {
  471. if wildcard {
  472. return "*"
  473. }
  474. return " "
  475. }
  476. // makeText combines all the strings in labelsList to form one giant string.
  477. // If the crush flag is true, then overlapping strings will be merged: "arpa"
  478. // and "parliament" could yield "arparliament".
  479. func makeText() string {
  480. if !*crush {
  481. return strings.Join(labelsList, "")
  482. }
  483. beforeLength := 0
  484. for _, s := range labelsList {
  485. beforeLength += len(s)
  486. }
  487. // Make a copy of labelsList.
  488. ss := append(make([]string, 0, len(labelsList)), labelsList...)
  489. // Remove strings that are substrings of other strings.
  490. for changed := true; changed; {
  491. changed = false
  492. for i, s := range ss {
  493. if s == "" {
  494. continue
  495. }
  496. for j, t := range ss {
  497. if i != j && t != "" && strings.Contains(s, t) {
  498. changed = true
  499. ss[j] = ""
  500. }
  501. }
  502. }
  503. }
  504. // Remove the empty strings.
  505. sort.Strings(ss)
  506. for len(ss) > 0 && ss[0] == "" {
  507. ss = ss[1:]
  508. }
  509. // Join strings where one suffix matches another prefix.
  510. for {
  511. // Find best i, j, k such that ss[i][len-k:] == ss[j][:k],
  512. // maximizing overlap length k.
  513. besti := -1
  514. bestj := -1
  515. bestk := 0
  516. for i, s := range ss {
  517. if s == "" {
  518. continue
  519. }
  520. for j, t := range ss {
  521. if i == j {
  522. continue
  523. }
  524. for k := bestk + 1; k <= len(s) && k <= len(t); k++ {
  525. if s[len(s)-k:] == t[:k] {
  526. besti = i
  527. bestj = j
  528. bestk = k
  529. }
  530. }
  531. }
  532. }
  533. if bestk > 0 {
  534. if *v {
  535. fmt.Fprintf(os.Stderr, "%d-length overlap at (%4d,%4d) out of (%4d,%4d): %q and %q\n",
  536. bestk, besti, bestj, len(ss), len(ss), ss[besti], ss[bestj])
  537. }
  538. ss[besti] += ss[bestj][bestk:]
  539. ss[bestj] = ""
  540. continue
  541. }
  542. break
  543. }
  544. text := strings.Join(ss, "")
  545. if *v {
  546. fmt.Fprintf(os.Stderr, "crushed %d bytes to become %d bytes\n", beforeLength, len(text))
  547. }
  548. return text
  549. }