gen.go 15 KB

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