Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 

2607 righe
66 KiB

  1. // Copyright 2009 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. // Package dnsmessage provides a mostly RFC 1035 compliant implementation of
  5. // DNS message packing and unpacking.
  6. //
  7. // The package also supports messages with Extension Mechanisms for DNS
  8. // (EDNS(0)) as defined in RFC 6891.
  9. //
  10. // This implementation is designed to minimize heap allocations and avoid
  11. // unnecessary packing and unpacking as much as possible.
  12. package dnsmessage
  13. import (
  14. "errors"
  15. )
  16. // Message formats
  17. // A Type is a type of DNS request and response.
  18. type Type uint16
  19. const (
  20. // ResourceHeader.Type and Question.Type
  21. TypeA Type = 1
  22. TypeNS Type = 2
  23. TypeCNAME Type = 5
  24. TypeSOA Type = 6
  25. TypePTR Type = 12
  26. TypeMX Type = 15
  27. TypeTXT Type = 16
  28. TypeAAAA Type = 28
  29. TypeSRV Type = 33
  30. TypeOPT Type = 41
  31. // Question.Type
  32. TypeWKS Type = 11
  33. TypeHINFO Type = 13
  34. TypeMINFO Type = 14
  35. TypeAXFR Type = 252
  36. TypeALL Type = 255
  37. )
  38. var typeNames = map[Type]string{
  39. TypeA: "TypeA",
  40. TypeNS: "TypeNS",
  41. TypeCNAME: "TypeCNAME",
  42. TypeSOA: "TypeSOA",
  43. TypePTR: "TypePTR",
  44. TypeMX: "TypeMX",
  45. TypeTXT: "TypeTXT",
  46. TypeAAAA: "TypeAAAA",
  47. TypeSRV: "TypeSRV",
  48. TypeOPT: "TypeOPT",
  49. TypeWKS: "TypeWKS",
  50. TypeHINFO: "TypeHINFO",
  51. TypeMINFO: "TypeMINFO",
  52. TypeAXFR: "TypeAXFR",
  53. TypeALL: "TypeALL",
  54. }
  55. // String implements fmt.Stringer.String.
  56. func (t Type) String() string {
  57. if n, ok := typeNames[t]; ok {
  58. return n
  59. }
  60. return printUint16(uint16(t))
  61. }
  62. // GoString implements fmt.GoStringer.GoString.
  63. func (t Type) GoString() string {
  64. if n, ok := typeNames[t]; ok {
  65. return "dnsmessage." + n
  66. }
  67. return printUint16(uint16(t))
  68. }
  69. // A Class is a type of network.
  70. type Class uint16
  71. const (
  72. // ResourceHeader.Class and Question.Class
  73. ClassINET Class = 1
  74. ClassCSNET Class = 2
  75. ClassCHAOS Class = 3
  76. ClassHESIOD Class = 4
  77. // Question.Class
  78. ClassANY Class = 255
  79. )
  80. var classNames = map[Class]string{
  81. ClassINET: "ClassINET",
  82. ClassCSNET: "ClassCSNET",
  83. ClassCHAOS: "ClassCHAOS",
  84. ClassHESIOD: "ClassHESIOD",
  85. ClassANY: "ClassANY",
  86. }
  87. // String implements fmt.Stringer.String.
  88. func (c Class) String() string {
  89. if n, ok := classNames[c]; ok {
  90. return n
  91. }
  92. return printUint16(uint16(c))
  93. }
  94. // GoString implements fmt.GoStringer.GoString.
  95. func (c Class) GoString() string {
  96. if n, ok := classNames[c]; ok {
  97. return "dnsmessage." + n
  98. }
  99. return printUint16(uint16(c))
  100. }
  101. // An OpCode is a DNS operation code.
  102. type OpCode uint16
  103. // GoString implements fmt.GoStringer.GoString.
  104. func (o OpCode) GoString() string {
  105. return printUint16(uint16(o))
  106. }
  107. // An RCode is a DNS response status code.
  108. type RCode uint16
  109. const (
  110. // Message.Rcode
  111. RCodeSuccess RCode = 0
  112. RCodeFormatError RCode = 1
  113. RCodeServerFailure RCode = 2
  114. RCodeNameError RCode = 3
  115. RCodeNotImplemented RCode = 4
  116. RCodeRefused RCode = 5
  117. )
  118. var rCodeNames = map[RCode]string{
  119. RCodeSuccess: "RCodeSuccess",
  120. RCodeFormatError: "RCodeFormatError",
  121. RCodeServerFailure: "RCodeServerFailure",
  122. RCodeNameError: "RCodeNameError",
  123. RCodeNotImplemented: "RCodeNotImplemented",
  124. RCodeRefused: "RCodeRefused",
  125. }
  126. // String implements fmt.Stringer.String.
  127. func (r RCode) String() string {
  128. if n, ok := rCodeNames[r]; ok {
  129. return n
  130. }
  131. return printUint16(uint16(r))
  132. }
  133. // GoString implements fmt.GoStringer.GoString.
  134. func (r RCode) GoString() string {
  135. if n, ok := rCodeNames[r]; ok {
  136. return "dnsmessage." + n
  137. }
  138. return printUint16(uint16(r))
  139. }
  140. func printPaddedUint8(i uint8) string {
  141. b := byte(i)
  142. return string([]byte{
  143. b/100 + '0',
  144. b/10%10 + '0',
  145. b%10 + '0',
  146. })
  147. }
  148. func printUint8Bytes(buf []byte, i uint8) []byte {
  149. b := byte(i)
  150. if i >= 100 {
  151. buf = append(buf, b/100+'0')
  152. }
  153. if i >= 10 {
  154. buf = append(buf, b/10%10+'0')
  155. }
  156. return append(buf, b%10+'0')
  157. }
  158. func printByteSlice(b []byte) string {
  159. if len(b) == 0 {
  160. return ""
  161. }
  162. buf := make([]byte, 0, 5*len(b))
  163. buf = printUint8Bytes(buf, uint8(b[0]))
  164. for _, n := range b[1:] {
  165. buf = append(buf, ',', ' ')
  166. buf = printUint8Bytes(buf, uint8(n))
  167. }
  168. return string(buf)
  169. }
  170. const hexDigits = "0123456789abcdef"
  171. func printString(str []byte) string {
  172. buf := make([]byte, 0, len(str))
  173. for i := 0; i < len(str); i++ {
  174. c := str[i]
  175. if c == '.' || c == '-' || c == ' ' ||
  176. 'A' <= c && c <= 'Z' ||
  177. 'a' <= c && c <= 'z' ||
  178. '0' <= c && c <= '9' {
  179. buf = append(buf, c)
  180. continue
  181. }
  182. upper := c >> 4
  183. lower := (c << 4) >> 4
  184. buf = append(
  185. buf,
  186. '\\',
  187. 'x',
  188. hexDigits[upper],
  189. hexDigits[lower],
  190. )
  191. }
  192. return string(buf)
  193. }
  194. func printUint16(i uint16) string {
  195. return printUint32(uint32(i))
  196. }
  197. func printUint32(i uint32) string {
  198. // Max value is 4294967295.
  199. buf := make([]byte, 10)
  200. for b, d := buf, uint32(1000000000); d > 0; d /= 10 {
  201. b[0] = byte(i/d%10 + '0')
  202. if b[0] == '0' && len(b) == len(buf) && len(buf) > 1 {
  203. buf = buf[1:]
  204. }
  205. b = b[1:]
  206. i %= d
  207. }
  208. return string(buf)
  209. }
  210. func printBool(b bool) string {
  211. if b {
  212. return "true"
  213. }
  214. return "false"
  215. }
  216. var (
  217. // ErrNotStarted indicates that the prerequisite information isn't
  218. // available yet because the previous records haven't been appropriately
  219. // parsed, skipped or finished.
  220. ErrNotStarted = errors.New("parsing/packing of this type isn't available yet")
  221. // ErrSectionDone indicated that all records in the section have been
  222. // parsed or finished.
  223. ErrSectionDone = errors.New("parsing/packing of this section has completed")
  224. errBaseLen = errors.New("insufficient data for base length type")
  225. errCalcLen = errors.New("insufficient data for calculated length type")
  226. errReserved = errors.New("segment prefix is reserved")
  227. errTooManyPtr = errors.New("too many pointers (>10)")
  228. errInvalidPtr = errors.New("invalid pointer")
  229. errNilResouceBody = errors.New("nil resource body")
  230. errResourceLen = errors.New("insufficient data for resource body length")
  231. errSegTooLong = errors.New("segment length too long")
  232. errZeroSegLen = errors.New("zero length segment")
  233. errResTooLong = errors.New("resource length too long")
  234. errTooManyQuestions = errors.New("too many Questions to pack (>65535)")
  235. errTooManyAnswers = errors.New("too many Answers to pack (>65535)")
  236. errTooManyAuthorities = errors.New("too many Authorities to pack (>65535)")
  237. errTooManyAdditionals = errors.New("too many Additionals to pack (>65535)")
  238. errNonCanonicalName = errors.New("name is not in canonical format (it must end with a .)")
  239. errStringTooLong = errors.New("character string exceeds maximum length (255)")
  240. errCompressedSRV = errors.New("compressed name in SRV resource data")
  241. )
  242. // Internal constants.
  243. const (
  244. // packStartingCap is the default initial buffer size allocated during
  245. // packing.
  246. //
  247. // The starting capacity doesn't matter too much, but most DNS responses
  248. // Will be <= 512 bytes as it is the limit for DNS over UDP.
  249. packStartingCap = 512
  250. // uint16Len is the length (in bytes) of a uint16.
  251. uint16Len = 2
  252. // uint32Len is the length (in bytes) of a uint32.
  253. uint32Len = 4
  254. // headerLen is the length (in bytes) of a DNS header.
  255. //
  256. // A header is comprised of 6 uint16s and no padding.
  257. headerLen = 6 * uint16Len
  258. )
  259. type nestedError struct {
  260. // s is the current level's error message.
  261. s string
  262. // err is the nested error.
  263. err error
  264. }
  265. // nestedError implements error.Error.
  266. func (e *nestedError) Error() string {
  267. return e.s + ": " + e.err.Error()
  268. }
  269. // Header is a representation of a DNS message header.
  270. type Header struct {
  271. ID uint16
  272. Response bool
  273. OpCode OpCode
  274. Authoritative bool
  275. Truncated bool
  276. RecursionDesired bool
  277. RecursionAvailable bool
  278. RCode RCode
  279. }
  280. func (m *Header) pack() (id uint16, bits uint16) {
  281. id = m.ID
  282. bits = uint16(m.OpCode)<<11 | uint16(m.RCode)
  283. if m.RecursionAvailable {
  284. bits |= headerBitRA
  285. }
  286. if m.RecursionDesired {
  287. bits |= headerBitRD
  288. }
  289. if m.Truncated {
  290. bits |= headerBitTC
  291. }
  292. if m.Authoritative {
  293. bits |= headerBitAA
  294. }
  295. if m.Response {
  296. bits |= headerBitQR
  297. }
  298. return
  299. }
  300. // GoString implements fmt.GoStringer.GoString.
  301. func (m *Header) GoString() string {
  302. return "dnsmessage.Header{" +
  303. "ID: " + printUint16(m.ID) + ", " +
  304. "Response: " + printBool(m.Response) + ", " +
  305. "OpCode: " + m.OpCode.GoString() + ", " +
  306. "Authoritative: " + printBool(m.Authoritative) + ", " +
  307. "Truncated: " + printBool(m.Truncated) + ", " +
  308. "RecursionDesired: " + printBool(m.RecursionDesired) + ", " +
  309. "RecursionAvailable: " + printBool(m.RecursionAvailable) + ", " +
  310. "RCode: " + m.RCode.GoString() + "}"
  311. }
  312. // Message is a representation of a DNS message.
  313. type Message struct {
  314. Header
  315. Questions []Question
  316. Answers []Resource
  317. Authorities []Resource
  318. Additionals []Resource
  319. }
  320. type section uint8
  321. const (
  322. sectionNotStarted section = iota
  323. sectionHeader
  324. sectionQuestions
  325. sectionAnswers
  326. sectionAuthorities
  327. sectionAdditionals
  328. sectionDone
  329. headerBitQR = 1 << 15 // query/response (response=1)
  330. headerBitAA = 1 << 10 // authoritative
  331. headerBitTC = 1 << 9 // truncated
  332. headerBitRD = 1 << 8 // recursion desired
  333. headerBitRA = 1 << 7 // recursion available
  334. )
  335. var sectionNames = map[section]string{
  336. sectionHeader: "header",
  337. sectionQuestions: "Question",
  338. sectionAnswers: "Answer",
  339. sectionAuthorities: "Authority",
  340. sectionAdditionals: "Additional",
  341. }
  342. // header is the wire format for a DNS message header.
  343. type header struct {
  344. id uint16
  345. bits uint16
  346. questions uint16
  347. answers uint16
  348. authorities uint16
  349. additionals uint16
  350. }
  351. func (h *header) count(sec section) uint16 {
  352. switch sec {
  353. case sectionQuestions:
  354. return h.questions
  355. case sectionAnswers:
  356. return h.answers
  357. case sectionAuthorities:
  358. return h.authorities
  359. case sectionAdditionals:
  360. return h.additionals
  361. }
  362. return 0
  363. }
  364. // pack appends the wire format of the header to msg.
  365. func (h *header) pack(msg []byte) []byte {
  366. msg = packUint16(msg, h.id)
  367. msg = packUint16(msg, h.bits)
  368. msg = packUint16(msg, h.questions)
  369. msg = packUint16(msg, h.answers)
  370. msg = packUint16(msg, h.authorities)
  371. return packUint16(msg, h.additionals)
  372. }
  373. func (h *header) unpack(msg []byte, off int) (int, error) {
  374. newOff := off
  375. var err error
  376. if h.id, newOff, err = unpackUint16(msg, newOff); err != nil {
  377. return off, &nestedError{"id", err}
  378. }
  379. if h.bits, newOff, err = unpackUint16(msg, newOff); err != nil {
  380. return off, &nestedError{"bits", err}
  381. }
  382. if h.questions, newOff, err = unpackUint16(msg, newOff); err != nil {
  383. return off, &nestedError{"questions", err}
  384. }
  385. if h.answers, newOff, err = unpackUint16(msg, newOff); err != nil {
  386. return off, &nestedError{"answers", err}
  387. }
  388. if h.authorities, newOff, err = unpackUint16(msg, newOff); err != nil {
  389. return off, &nestedError{"authorities", err}
  390. }
  391. if h.additionals, newOff, err = unpackUint16(msg, newOff); err != nil {
  392. return off, &nestedError{"additionals", err}
  393. }
  394. return newOff, nil
  395. }
  396. func (h *header) header() Header {
  397. return Header{
  398. ID: h.id,
  399. Response: (h.bits & headerBitQR) != 0,
  400. OpCode: OpCode(h.bits>>11) & 0xF,
  401. Authoritative: (h.bits & headerBitAA) != 0,
  402. Truncated: (h.bits & headerBitTC) != 0,
  403. RecursionDesired: (h.bits & headerBitRD) != 0,
  404. RecursionAvailable: (h.bits & headerBitRA) != 0,
  405. RCode: RCode(h.bits & 0xF),
  406. }
  407. }
  408. // A Resource is a DNS resource record.
  409. type Resource struct {
  410. Header ResourceHeader
  411. Body ResourceBody
  412. }
  413. func (r *Resource) GoString() string {
  414. return "dnsmessage.Resource{" +
  415. "Header: " + r.Header.GoString() +
  416. ", Body: &" + r.Body.GoString() +
  417. "}"
  418. }
  419. // A ResourceBody is a DNS resource record minus the header.
  420. type ResourceBody interface {
  421. // pack packs a Resource except for its header.
  422. pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error)
  423. // realType returns the actual type of the Resource. This is used to
  424. // fill in the header Type field.
  425. realType() Type
  426. // GoString implements fmt.GoStringer.GoString.
  427. GoString() string
  428. }
  429. // pack appends the wire format of the Resource to msg.
  430. func (r *Resource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) {
  431. if r.Body == nil {
  432. return msg, errNilResouceBody
  433. }
  434. oldMsg := msg
  435. r.Header.Type = r.Body.realType()
  436. msg, lenOff, err := r.Header.pack(msg, compression, compressionOff)
  437. if err != nil {
  438. return msg, &nestedError{"ResourceHeader", err}
  439. }
  440. preLen := len(msg)
  441. msg, err = r.Body.pack(msg, compression, compressionOff)
  442. if err != nil {
  443. return msg, &nestedError{"content", err}
  444. }
  445. if err := r.Header.fixLen(msg, lenOff, preLen); err != nil {
  446. return oldMsg, err
  447. }
  448. return msg, nil
  449. }
  450. // A Parser allows incrementally parsing a DNS message.
  451. //
  452. // When parsing is started, the Header is parsed. Next, each Question can be
  453. // either parsed or skipped. Alternatively, all Questions can be skipped at
  454. // once. When all Questions have been parsed, attempting to parse Questions
  455. // will return (nil, nil) and attempting to skip Questions will return
  456. // (true, nil). After all Questions have been either parsed or skipped, all
  457. // Answers, Authorities and Additionals can be either parsed or skipped in the
  458. // same way, and each type of Resource must be fully parsed or skipped before
  459. // proceeding to the next type of Resource.
  460. //
  461. // Note that there is no requirement to fully skip or parse the message.
  462. type Parser struct {
  463. msg []byte
  464. header header
  465. section section
  466. off int
  467. index int
  468. resHeaderValid bool
  469. resHeader ResourceHeader
  470. }
  471. // Start parses the header and enables the parsing of Questions.
  472. func (p *Parser) Start(msg []byte) (Header, error) {
  473. if p.msg != nil {
  474. *p = Parser{}
  475. }
  476. p.msg = msg
  477. var err error
  478. if p.off, err = p.header.unpack(msg, 0); err != nil {
  479. return Header{}, &nestedError{"unpacking header", err}
  480. }
  481. p.section = sectionQuestions
  482. return p.header.header(), nil
  483. }
  484. func (p *Parser) checkAdvance(sec section) error {
  485. if p.section < sec {
  486. return ErrNotStarted
  487. }
  488. if p.section > sec {
  489. return ErrSectionDone
  490. }
  491. p.resHeaderValid = false
  492. if p.index == int(p.header.count(sec)) {
  493. p.index = 0
  494. p.section++
  495. return ErrSectionDone
  496. }
  497. return nil
  498. }
  499. func (p *Parser) resource(sec section) (Resource, error) {
  500. var r Resource
  501. var err error
  502. r.Header, err = p.resourceHeader(sec)
  503. if err != nil {
  504. return r, err
  505. }
  506. p.resHeaderValid = false
  507. r.Body, p.off, err = unpackResourceBody(p.msg, p.off, r.Header)
  508. if err != nil {
  509. return Resource{}, &nestedError{"unpacking " + sectionNames[sec], err}
  510. }
  511. p.index++
  512. return r, nil
  513. }
  514. func (p *Parser) resourceHeader(sec section) (ResourceHeader, error) {
  515. if p.resHeaderValid {
  516. return p.resHeader, nil
  517. }
  518. if err := p.checkAdvance(sec); err != nil {
  519. return ResourceHeader{}, err
  520. }
  521. var hdr ResourceHeader
  522. off, err := hdr.unpack(p.msg, p.off)
  523. if err != nil {
  524. return ResourceHeader{}, err
  525. }
  526. p.resHeaderValid = true
  527. p.resHeader = hdr
  528. p.off = off
  529. return hdr, nil
  530. }
  531. func (p *Parser) skipResource(sec section) error {
  532. if p.resHeaderValid {
  533. newOff := p.off + int(p.resHeader.Length)
  534. if newOff > len(p.msg) {
  535. return errResourceLen
  536. }
  537. p.off = newOff
  538. p.resHeaderValid = false
  539. p.index++
  540. return nil
  541. }
  542. if err := p.checkAdvance(sec); err != nil {
  543. return err
  544. }
  545. var err error
  546. p.off, err = skipResource(p.msg, p.off)
  547. if err != nil {
  548. return &nestedError{"skipping: " + sectionNames[sec], err}
  549. }
  550. p.index++
  551. return nil
  552. }
  553. // Question parses a single Question.
  554. func (p *Parser) Question() (Question, error) {
  555. if err := p.checkAdvance(sectionQuestions); err != nil {
  556. return Question{}, err
  557. }
  558. var name Name
  559. off, err := name.unpack(p.msg, p.off)
  560. if err != nil {
  561. return Question{}, &nestedError{"unpacking Question.Name", err}
  562. }
  563. typ, off, err := unpackType(p.msg, off)
  564. if err != nil {
  565. return Question{}, &nestedError{"unpacking Question.Type", err}
  566. }
  567. class, off, err := unpackClass(p.msg, off)
  568. if err != nil {
  569. return Question{}, &nestedError{"unpacking Question.Class", err}
  570. }
  571. p.off = off
  572. p.index++
  573. return Question{name, typ, class}, nil
  574. }
  575. // AllQuestions parses all Questions.
  576. func (p *Parser) AllQuestions() ([]Question, error) {
  577. // Multiple questions are valid according to the spec,
  578. // but servers don't actually support them. There will
  579. // be at most one question here.
  580. //
  581. // Do not pre-allocate based on info in p.header, since
  582. // the data is untrusted.
  583. qs := []Question{}
  584. for {
  585. q, err := p.Question()
  586. if err == ErrSectionDone {
  587. return qs, nil
  588. }
  589. if err != nil {
  590. return nil, err
  591. }
  592. qs = append(qs, q)
  593. }
  594. }
  595. // SkipQuestion skips a single Question.
  596. func (p *Parser) SkipQuestion() error {
  597. if err := p.checkAdvance(sectionQuestions); err != nil {
  598. return err
  599. }
  600. off, err := skipName(p.msg, p.off)
  601. if err != nil {
  602. return &nestedError{"skipping Question Name", err}
  603. }
  604. if off, err = skipType(p.msg, off); err != nil {
  605. return &nestedError{"skipping Question Type", err}
  606. }
  607. if off, err = skipClass(p.msg, off); err != nil {
  608. return &nestedError{"skipping Question Class", err}
  609. }
  610. p.off = off
  611. p.index++
  612. return nil
  613. }
  614. // SkipAllQuestions skips all Questions.
  615. func (p *Parser) SkipAllQuestions() error {
  616. for {
  617. if err := p.SkipQuestion(); err == ErrSectionDone {
  618. return nil
  619. } else if err != nil {
  620. return err
  621. }
  622. }
  623. }
  624. // AnswerHeader parses a single Answer ResourceHeader.
  625. func (p *Parser) AnswerHeader() (ResourceHeader, error) {
  626. return p.resourceHeader(sectionAnswers)
  627. }
  628. // Answer parses a single Answer Resource.
  629. func (p *Parser) Answer() (Resource, error) {
  630. return p.resource(sectionAnswers)
  631. }
  632. // AllAnswers parses all Answer Resources.
  633. func (p *Parser) AllAnswers() ([]Resource, error) {
  634. // The most common query is for A/AAAA, which usually returns
  635. // a handful of IPs.
  636. //
  637. // Pre-allocate up to a certain limit, since p.header is
  638. // untrusted data.
  639. n := int(p.header.answers)
  640. if n > 20 {
  641. n = 20
  642. }
  643. as := make([]Resource, 0, n)
  644. for {
  645. a, err := p.Answer()
  646. if err == ErrSectionDone {
  647. return as, nil
  648. }
  649. if err != nil {
  650. return nil, err
  651. }
  652. as = append(as, a)
  653. }
  654. }
  655. // SkipAnswer skips a single Answer Resource.
  656. func (p *Parser) SkipAnswer() error {
  657. return p.skipResource(sectionAnswers)
  658. }
  659. // SkipAllAnswers skips all Answer Resources.
  660. func (p *Parser) SkipAllAnswers() error {
  661. for {
  662. if err := p.SkipAnswer(); err == ErrSectionDone {
  663. return nil
  664. } else if err != nil {
  665. return err
  666. }
  667. }
  668. }
  669. // AuthorityHeader parses a single Authority ResourceHeader.
  670. func (p *Parser) AuthorityHeader() (ResourceHeader, error) {
  671. return p.resourceHeader(sectionAuthorities)
  672. }
  673. // Authority parses a single Authority Resource.
  674. func (p *Parser) Authority() (Resource, error) {
  675. return p.resource(sectionAuthorities)
  676. }
  677. // AllAuthorities parses all Authority Resources.
  678. func (p *Parser) AllAuthorities() ([]Resource, error) {
  679. // Authorities contains SOA in case of NXDOMAIN and friends,
  680. // otherwise it is empty.
  681. //
  682. // Pre-allocate up to a certain limit, since p.header is
  683. // untrusted data.
  684. n := int(p.header.authorities)
  685. if n > 10 {
  686. n = 10
  687. }
  688. as := make([]Resource, 0, n)
  689. for {
  690. a, err := p.Authority()
  691. if err == ErrSectionDone {
  692. return as, nil
  693. }
  694. if err != nil {
  695. return nil, err
  696. }
  697. as = append(as, a)
  698. }
  699. }
  700. // SkipAuthority skips a single Authority Resource.
  701. func (p *Parser) SkipAuthority() error {
  702. return p.skipResource(sectionAuthorities)
  703. }
  704. // SkipAllAuthorities skips all Authority Resources.
  705. func (p *Parser) SkipAllAuthorities() error {
  706. for {
  707. if err := p.SkipAuthority(); err == ErrSectionDone {
  708. return nil
  709. } else if err != nil {
  710. return err
  711. }
  712. }
  713. }
  714. // AdditionalHeader parses a single Additional ResourceHeader.
  715. func (p *Parser) AdditionalHeader() (ResourceHeader, error) {
  716. return p.resourceHeader(sectionAdditionals)
  717. }
  718. // Additional parses a single Additional Resource.
  719. func (p *Parser) Additional() (Resource, error) {
  720. return p.resource(sectionAdditionals)
  721. }
  722. // AllAdditionals parses all Additional Resources.
  723. func (p *Parser) AllAdditionals() ([]Resource, error) {
  724. // Additionals usually contain OPT, and sometimes A/AAAA
  725. // glue records.
  726. //
  727. // Pre-allocate up to a certain limit, since p.header is
  728. // untrusted data.
  729. n := int(p.header.additionals)
  730. if n > 10 {
  731. n = 10
  732. }
  733. as := make([]Resource, 0, n)
  734. for {
  735. a, err := p.Additional()
  736. if err == ErrSectionDone {
  737. return as, nil
  738. }
  739. if err != nil {
  740. return nil, err
  741. }
  742. as = append(as, a)
  743. }
  744. }
  745. // SkipAdditional skips a single Additional Resource.
  746. func (p *Parser) SkipAdditional() error {
  747. return p.skipResource(sectionAdditionals)
  748. }
  749. // SkipAllAdditionals skips all Additional Resources.
  750. func (p *Parser) SkipAllAdditionals() error {
  751. for {
  752. if err := p.SkipAdditional(); err == ErrSectionDone {
  753. return nil
  754. } else if err != nil {
  755. return err
  756. }
  757. }
  758. }
  759. // CNAMEResource parses a single CNAMEResource.
  760. //
  761. // One of the XXXHeader methods must have been called before calling this
  762. // method.
  763. func (p *Parser) CNAMEResource() (CNAMEResource, error) {
  764. if !p.resHeaderValid || p.resHeader.Type != TypeCNAME {
  765. return CNAMEResource{}, ErrNotStarted
  766. }
  767. r, err := unpackCNAMEResource(p.msg, p.off)
  768. if err != nil {
  769. return CNAMEResource{}, err
  770. }
  771. p.off += int(p.resHeader.Length)
  772. p.resHeaderValid = false
  773. p.index++
  774. return r, nil
  775. }
  776. // MXResource parses a single MXResource.
  777. //
  778. // One of the XXXHeader methods must have been called before calling this
  779. // method.
  780. func (p *Parser) MXResource() (MXResource, error) {
  781. if !p.resHeaderValid || p.resHeader.Type != TypeMX {
  782. return MXResource{}, ErrNotStarted
  783. }
  784. r, err := unpackMXResource(p.msg, p.off)
  785. if err != nil {
  786. return MXResource{}, err
  787. }
  788. p.off += int(p.resHeader.Length)
  789. p.resHeaderValid = false
  790. p.index++
  791. return r, nil
  792. }
  793. // NSResource parses a single NSResource.
  794. //
  795. // One of the XXXHeader methods must have been called before calling this
  796. // method.
  797. func (p *Parser) NSResource() (NSResource, error) {
  798. if !p.resHeaderValid || p.resHeader.Type != TypeNS {
  799. return NSResource{}, ErrNotStarted
  800. }
  801. r, err := unpackNSResource(p.msg, p.off)
  802. if err != nil {
  803. return NSResource{}, err
  804. }
  805. p.off += int(p.resHeader.Length)
  806. p.resHeaderValid = false
  807. p.index++
  808. return r, nil
  809. }
  810. // PTRResource parses a single PTRResource.
  811. //
  812. // One of the XXXHeader methods must have been called before calling this
  813. // method.
  814. func (p *Parser) PTRResource() (PTRResource, error) {
  815. if !p.resHeaderValid || p.resHeader.Type != TypePTR {
  816. return PTRResource{}, ErrNotStarted
  817. }
  818. r, err := unpackPTRResource(p.msg, p.off)
  819. if err != nil {
  820. return PTRResource{}, err
  821. }
  822. p.off += int(p.resHeader.Length)
  823. p.resHeaderValid = false
  824. p.index++
  825. return r, nil
  826. }
  827. // SOAResource parses a single SOAResource.
  828. //
  829. // One of the XXXHeader methods must have been called before calling this
  830. // method.
  831. func (p *Parser) SOAResource() (SOAResource, error) {
  832. if !p.resHeaderValid || p.resHeader.Type != TypeSOA {
  833. return SOAResource{}, ErrNotStarted
  834. }
  835. r, err := unpackSOAResource(p.msg, p.off)
  836. if err != nil {
  837. return SOAResource{}, err
  838. }
  839. p.off += int(p.resHeader.Length)
  840. p.resHeaderValid = false
  841. p.index++
  842. return r, nil
  843. }
  844. // TXTResource parses a single TXTResource.
  845. //
  846. // One of the XXXHeader methods must have been called before calling this
  847. // method.
  848. func (p *Parser) TXTResource() (TXTResource, error) {
  849. if !p.resHeaderValid || p.resHeader.Type != TypeTXT {
  850. return TXTResource{}, ErrNotStarted
  851. }
  852. r, err := unpackTXTResource(p.msg, p.off, p.resHeader.Length)
  853. if err != nil {
  854. return TXTResource{}, err
  855. }
  856. p.off += int(p.resHeader.Length)
  857. p.resHeaderValid = false
  858. p.index++
  859. return r, nil
  860. }
  861. // SRVResource parses a single SRVResource.
  862. //
  863. // One of the XXXHeader methods must have been called before calling this
  864. // method.
  865. func (p *Parser) SRVResource() (SRVResource, error) {
  866. if !p.resHeaderValid || p.resHeader.Type != TypeSRV {
  867. return SRVResource{}, ErrNotStarted
  868. }
  869. r, err := unpackSRVResource(p.msg, p.off)
  870. if err != nil {
  871. return SRVResource{}, err
  872. }
  873. p.off += int(p.resHeader.Length)
  874. p.resHeaderValid = false
  875. p.index++
  876. return r, nil
  877. }
  878. // AResource parses a single AResource.
  879. //
  880. // One of the XXXHeader methods must have been called before calling this
  881. // method.
  882. func (p *Parser) AResource() (AResource, error) {
  883. if !p.resHeaderValid || p.resHeader.Type != TypeA {
  884. return AResource{}, ErrNotStarted
  885. }
  886. r, err := unpackAResource(p.msg, p.off)
  887. if err != nil {
  888. return AResource{}, err
  889. }
  890. p.off += int(p.resHeader.Length)
  891. p.resHeaderValid = false
  892. p.index++
  893. return r, nil
  894. }
  895. // AAAAResource parses a single AAAAResource.
  896. //
  897. // One of the XXXHeader methods must have been called before calling this
  898. // method.
  899. func (p *Parser) AAAAResource() (AAAAResource, error) {
  900. if !p.resHeaderValid || p.resHeader.Type != TypeAAAA {
  901. return AAAAResource{}, ErrNotStarted
  902. }
  903. r, err := unpackAAAAResource(p.msg, p.off)
  904. if err != nil {
  905. return AAAAResource{}, err
  906. }
  907. p.off += int(p.resHeader.Length)
  908. p.resHeaderValid = false
  909. p.index++
  910. return r, nil
  911. }
  912. // OPTResource parses a single OPTResource.
  913. //
  914. // One of the XXXHeader methods must have been called before calling this
  915. // method.
  916. func (p *Parser) OPTResource() (OPTResource, error) {
  917. if !p.resHeaderValid || p.resHeader.Type != TypeOPT {
  918. return OPTResource{}, ErrNotStarted
  919. }
  920. r, err := unpackOPTResource(p.msg, p.off, p.resHeader.Length)
  921. if err != nil {
  922. return OPTResource{}, err
  923. }
  924. p.off += int(p.resHeader.Length)
  925. p.resHeaderValid = false
  926. p.index++
  927. return r, nil
  928. }
  929. // Unpack parses a full Message.
  930. func (m *Message) Unpack(msg []byte) error {
  931. var p Parser
  932. var err error
  933. if m.Header, err = p.Start(msg); err != nil {
  934. return err
  935. }
  936. if m.Questions, err = p.AllQuestions(); err != nil {
  937. return err
  938. }
  939. if m.Answers, err = p.AllAnswers(); err != nil {
  940. return err
  941. }
  942. if m.Authorities, err = p.AllAuthorities(); err != nil {
  943. return err
  944. }
  945. if m.Additionals, err = p.AllAdditionals(); err != nil {
  946. return err
  947. }
  948. return nil
  949. }
  950. // Pack packs a full Message.
  951. func (m *Message) Pack() ([]byte, error) {
  952. return m.AppendPack(make([]byte, 0, packStartingCap))
  953. }
  954. // AppendPack is like Pack but appends the full Message to b and returns the
  955. // extended buffer.
  956. func (m *Message) AppendPack(b []byte) ([]byte, error) {
  957. // Validate the lengths. It is very unlikely that anyone will try to
  958. // pack more than 65535 of any particular type, but it is possible and
  959. // we should fail gracefully.
  960. if len(m.Questions) > int(^uint16(0)) {
  961. return nil, errTooManyQuestions
  962. }
  963. if len(m.Answers) > int(^uint16(0)) {
  964. return nil, errTooManyAnswers
  965. }
  966. if len(m.Authorities) > int(^uint16(0)) {
  967. return nil, errTooManyAuthorities
  968. }
  969. if len(m.Additionals) > int(^uint16(0)) {
  970. return nil, errTooManyAdditionals
  971. }
  972. var h header
  973. h.id, h.bits = m.Header.pack()
  974. h.questions = uint16(len(m.Questions))
  975. h.answers = uint16(len(m.Answers))
  976. h.authorities = uint16(len(m.Authorities))
  977. h.additionals = uint16(len(m.Additionals))
  978. compressionOff := len(b)
  979. msg := h.pack(b)
  980. // RFC 1035 allows (but does not require) compression for packing. RFC
  981. // 1035 requires unpacking implementations to support compression, so
  982. // unconditionally enabling it is fine.
  983. //
  984. // DNS lookups are typically done over UDP, and RFC 1035 states that UDP
  985. // DNS messages can be a maximum of 512 bytes long. Without compression,
  986. // many DNS response messages are over this limit, so enabling
  987. // compression will help ensure compliance.
  988. compression := map[string]int{}
  989. for i := range m.Questions {
  990. var err error
  991. if msg, err = m.Questions[i].pack(msg, compression, compressionOff); err != nil {
  992. return nil, &nestedError{"packing Question", err}
  993. }
  994. }
  995. for i := range m.Answers {
  996. var err error
  997. if msg, err = m.Answers[i].pack(msg, compression, compressionOff); err != nil {
  998. return nil, &nestedError{"packing Answer", err}
  999. }
  1000. }
  1001. for i := range m.Authorities {
  1002. var err error
  1003. if msg, err = m.Authorities[i].pack(msg, compression, compressionOff); err != nil {
  1004. return nil, &nestedError{"packing Authority", err}
  1005. }
  1006. }
  1007. for i := range m.Additionals {
  1008. var err error
  1009. if msg, err = m.Additionals[i].pack(msg, compression, compressionOff); err != nil {
  1010. return nil, &nestedError{"packing Additional", err}
  1011. }
  1012. }
  1013. return msg, nil
  1014. }
  1015. // GoString implements fmt.GoStringer.GoString.
  1016. func (m *Message) GoString() string {
  1017. s := "dnsmessage.Message{Header: " + m.Header.GoString() + ", " +
  1018. "Questions: []dnsmessage.Question{"
  1019. if len(m.Questions) > 0 {
  1020. s += m.Questions[0].GoString()
  1021. for _, q := range m.Questions[1:] {
  1022. s += ", " + q.GoString()
  1023. }
  1024. }
  1025. s += "}, Answers: []dnsmessage.Resource{"
  1026. if len(m.Answers) > 0 {
  1027. s += m.Answers[0].GoString()
  1028. for _, a := range m.Answers[1:] {
  1029. s += ", " + a.GoString()
  1030. }
  1031. }
  1032. s += "}, Authorities: []dnsmessage.Resource{"
  1033. if len(m.Authorities) > 0 {
  1034. s += m.Authorities[0].GoString()
  1035. for _, a := range m.Authorities[1:] {
  1036. s += ", " + a.GoString()
  1037. }
  1038. }
  1039. s += "}, Additionals: []dnsmessage.Resource{"
  1040. if len(m.Additionals) > 0 {
  1041. s += m.Additionals[0].GoString()
  1042. for _, a := range m.Additionals[1:] {
  1043. s += ", " + a.GoString()
  1044. }
  1045. }
  1046. return s + "}}"
  1047. }
  1048. // A Builder allows incrementally packing a DNS message.
  1049. //
  1050. // Example usage:
  1051. // buf := make([]byte, 2, 514)
  1052. // b := NewBuilder(buf, Header{...})
  1053. // b.EnableCompression()
  1054. // // Optionally start a section and add things to that section.
  1055. // // Repeat adding sections as necessary.
  1056. // buf, err := b.Finish()
  1057. // // If err is nil, buf[2:] will contain the built bytes.
  1058. type Builder struct {
  1059. // msg is the storage for the message being built.
  1060. msg []byte
  1061. // section keeps track of the current section being built.
  1062. section section
  1063. // header keeps track of what should go in the header when Finish is
  1064. // called.
  1065. header header
  1066. // start is the starting index of the bytes allocated in msg for header.
  1067. start int
  1068. // compression is a mapping from name suffixes to their starting index
  1069. // in msg.
  1070. compression map[string]int
  1071. }
  1072. // NewBuilder creates a new builder with compression disabled.
  1073. //
  1074. // Note: Most users will want to immediately enable compression with the
  1075. // EnableCompression method. See that method's comment for why you may or may
  1076. // not want to enable compression.
  1077. //
  1078. // The DNS message is appended to the provided initial buffer buf (which may be
  1079. // nil) as it is built. The final message is returned by the (*Builder).Finish
  1080. // method, which may return the same underlying array if there was sufficient
  1081. // capacity in the slice.
  1082. func NewBuilder(buf []byte, h Header) Builder {
  1083. if buf == nil {
  1084. buf = make([]byte, 0, packStartingCap)
  1085. }
  1086. b := Builder{msg: buf, start: len(buf)}
  1087. b.header.id, b.header.bits = h.pack()
  1088. var hb [headerLen]byte
  1089. b.msg = append(b.msg, hb[:]...)
  1090. b.section = sectionHeader
  1091. return b
  1092. }
  1093. // EnableCompression enables compression in the Builder.
  1094. //
  1095. // Leaving compression disabled avoids compression related allocations, but can
  1096. // result in larger message sizes. Be careful with this mode as it can cause
  1097. // messages to exceed the UDP size limit.
  1098. //
  1099. // According to RFC 1035, section 4.1.4, the use of compression is optional, but
  1100. // all implementations must accept both compressed and uncompressed DNS
  1101. // messages.
  1102. //
  1103. // Compression should be enabled before any sections are added for best results.
  1104. func (b *Builder) EnableCompression() {
  1105. b.compression = map[string]int{}
  1106. }
  1107. func (b *Builder) startCheck(s section) error {
  1108. if b.section <= sectionNotStarted {
  1109. return ErrNotStarted
  1110. }
  1111. if b.section > s {
  1112. return ErrSectionDone
  1113. }
  1114. return nil
  1115. }
  1116. // StartQuestions prepares the builder for packing Questions.
  1117. func (b *Builder) StartQuestions() error {
  1118. if err := b.startCheck(sectionQuestions); err != nil {
  1119. return err
  1120. }
  1121. b.section = sectionQuestions
  1122. return nil
  1123. }
  1124. // StartAnswers prepares the builder for packing Answers.
  1125. func (b *Builder) StartAnswers() error {
  1126. if err := b.startCheck(sectionAnswers); err != nil {
  1127. return err
  1128. }
  1129. b.section = sectionAnswers
  1130. return nil
  1131. }
  1132. // StartAuthorities prepares the builder for packing Authorities.
  1133. func (b *Builder) StartAuthorities() error {
  1134. if err := b.startCheck(sectionAuthorities); err != nil {
  1135. return err
  1136. }
  1137. b.section = sectionAuthorities
  1138. return nil
  1139. }
  1140. // StartAdditionals prepares the builder for packing Additionals.
  1141. func (b *Builder) StartAdditionals() error {
  1142. if err := b.startCheck(sectionAdditionals); err != nil {
  1143. return err
  1144. }
  1145. b.section = sectionAdditionals
  1146. return nil
  1147. }
  1148. func (b *Builder) incrementSectionCount() error {
  1149. var count *uint16
  1150. var err error
  1151. switch b.section {
  1152. case sectionQuestions:
  1153. count = &b.header.questions
  1154. err = errTooManyQuestions
  1155. case sectionAnswers:
  1156. count = &b.header.answers
  1157. err = errTooManyAnswers
  1158. case sectionAuthorities:
  1159. count = &b.header.authorities
  1160. err = errTooManyAuthorities
  1161. case sectionAdditionals:
  1162. count = &b.header.additionals
  1163. err = errTooManyAdditionals
  1164. }
  1165. if *count == ^uint16(0) {
  1166. return err
  1167. }
  1168. *count++
  1169. return nil
  1170. }
  1171. // Question adds a single Question.
  1172. func (b *Builder) Question(q Question) error {
  1173. if b.section < sectionQuestions {
  1174. return ErrNotStarted
  1175. }
  1176. if b.section > sectionQuestions {
  1177. return ErrSectionDone
  1178. }
  1179. msg, err := q.pack(b.msg, b.compression, b.start)
  1180. if err != nil {
  1181. return err
  1182. }
  1183. if err := b.incrementSectionCount(); err != nil {
  1184. return err
  1185. }
  1186. b.msg = msg
  1187. return nil
  1188. }
  1189. func (b *Builder) checkResourceSection() error {
  1190. if b.section < sectionAnswers {
  1191. return ErrNotStarted
  1192. }
  1193. if b.section > sectionAdditionals {
  1194. return ErrSectionDone
  1195. }
  1196. return nil
  1197. }
  1198. // CNAMEResource adds a single CNAMEResource.
  1199. func (b *Builder) CNAMEResource(h ResourceHeader, r CNAMEResource) error {
  1200. if err := b.checkResourceSection(); err != nil {
  1201. return err
  1202. }
  1203. h.Type = r.realType()
  1204. msg, lenOff, err := h.pack(b.msg, b.compression, b.start)
  1205. if err != nil {
  1206. return &nestedError{"ResourceHeader", err}
  1207. }
  1208. preLen := len(msg)
  1209. if msg, err = r.pack(msg, b.compression, b.start); err != nil {
  1210. return &nestedError{"CNAMEResource body", err}
  1211. }
  1212. if err := h.fixLen(msg, lenOff, preLen); err != nil {
  1213. return err
  1214. }
  1215. if err := b.incrementSectionCount(); err != nil {
  1216. return err
  1217. }
  1218. b.msg = msg
  1219. return nil
  1220. }
  1221. // MXResource adds a single MXResource.
  1222. func (b *Builder) MXResource(h ResourceHeader, r MXResource) error {
  1223. if err := b.checkResourceSection(); err != nil {
  1224. return err
  1225. }
  1226. h.Type = r.realType()
  1227. msg, lenOff, err := h.pack(b.msg, b.compression, b.start)
  1228. if err != nil {
  1229. return &nestedError{"ResourceHeader", err}
  1230. }
  1231. preLen := len(msg)
  1232. if msg, err = r.pack(msg, b.compression, b.start); err != nil {
  1233. return &nestedError{"MXResource body", err}
  1234. }
  1235. if err := h.fixLen(msg, lenOff, preLen); err != nil {
  1236. return err
  1237. }
  1238. if err := b.incrementSectionCount(); err != nil {
  1239. return err
  1240. }
  1241. b.msg = msg
  1242. return nil
  1243. }
  1244. // NSResource adds a single NSResource.
  1245. func (b *Builder) NSResource(h ResourceHeader, r NSResource) error {
  1246. if err := b.checkResourceSection(); err != nil {
  1247. return err
  1248. }
  1249. h.Type = r.realType()
  1250. msg, lenOff, err := h.pack(b.msg, b.compression, b.start)
  1251. if err != nil {
  1252. return &nestedError{"ResourceHeader", err}
  1253. }
  1254. preLen := len(msg)
  1255. if msg, err = r.pack(msg, b.compression, b.start); err != nil {
  1256. return &nestedError{"NSResource body", err}
  1257. }
  1258. if err := h.fixLen(msg, lenOff, preLen); err != nil {
  1259. return err
  1260. }
  1261. if err := b.incrementSectionCount(); err != nil {
  1262. return err
  1263. }
  1264. b.msg = msg
  1265. return nil
  1266. }
  1267. // PTRResource adds a single PTRResource.
  1268. func (b *Builder) PTRResource(h ResourceHeader, r PTRResource) error {
  1269. if err := b.checkResourceSection(); err != nil {
  1270. return err
  1271. }
  1272. h.Type = r.realType()
  1273. msg, lenOff, err := h.pack(b.msg, b.compression, b.start)
  1274. if err != nil {
  1275. return &nestedError{"ResourceHeader", err}
  1276. }
  1277. preLen := len(msg)
  1278. if msg, err = r.pack(msg, b.compression, b.start); err != nil {
  1279. return &nestedError{"PTRResource body", err}
  1280. }
  1281. if err := h.fixLen(msg, lenOff, preLen); err != nil {
  1282. return err
  1283. }
  1284. if err := b.incrementSectionCount(); err != nil {
  1285. return err
  1286. }
  1287. b.msg = msg
  1288. return nil
  1289. }
  1290. // SOAResource adds a single SOAResource.
  1291. func (b *Builder) SOAResource(h ResourceHeader, r SOAResource) error {
  1292. if err := b.checkResourceSection(); err != nil {
  1293. return err
  1294. }
  1295. h.Type = r.realType()
  1296. msg, lenOff, err := h.pack(b.msg, b.compression, b.start)
  1297. if err != nil {
  1298. return &nestedError{"ResourceHeader", err}
  1299. }
  1300. preLen := len(msg)
  1301. if msg, err = r.pack(msg, b.compression, b.start); err != nil {
  1302. return &nestedError{"SOAResource body", err}
  1303. }
  1304. if err := h.fixLen(msg, lenOff, preLen); err != nil {
  1305. return err
  1306. }
  1307. if err := b.incrementSectionCount(); err != nil {
  1308. return err
  1309. }
  1310. b.msg = msg
  1311. return nil
  1312. }
  1313. // TXTResource adds a single TXTResource.
  1314. func (b *Builder) TXTResource(h ResourceHeader, r TXTResource) error {
  1315. if err := b.checkResourceSection(); err != nil {
  1316. return err
  1317. }
  1318. h.Type = r.realType()
  1319. msg, lenOff, err := h.pack(b.msg, b.compression, b.start)
  1320. if err != nil {
  1321. return &nestedError{"ResourceHeader", err}
  1322. }
  1323. preLen := len(msg)
  1324. if msg, err = r.pack(msg, b.compression, b.start); err != nil {
  1325. return &nestedError{"TXTResource body", err}
  1326. }
  1327. if err := h.fixLen(msg, lenOff, preLen); err != nil {
  1328. return err
  1329. }
  1330. if err := b.incrementSectionCount(); err != nil {
  1331. return err
  1332. }
  1333. b.msg = msg
  1334. return nil
  1335. }
  1336. // SRVResource adds a single SRVResource.
  1337. func (b *Builder) SRVResource(h ResourceHeader, r SRVResource) error {
  1338. if err := b.checkResourceSection(); err != nil {
  1339. return err
  1340. }
  1341. h.Type = r.realType()
  1342. msg, lenOff, err := h.pack(b.msg, b.compression, b.start)
  1343. if err != nil {
  1344. return &nestedError{"ResourceHeader", err}
  1345. }
  1346. preLen := len(msg)
  1347. if msg, err = r.pack(msg, b.compression, b.start); err != nil {
  1348. return &nestedError{"SRVResource body", err}
  1349. }
  1350. if err := h.fixLen(msg, lenOff, preLen); err != nil {
  1351. return err
  1352. }
  1353. if err := b.incrementSectionCount(); err != nil {
  1354. return err
  1355. }
  1356. b.msg = msg
  1357. return nil
  1358. }
  1359. // AResource adds a single AResource.
  1360. func (b *Builder) AResource(h ResourceHeader, r AResource) error {
  1361. if err := b.checkResourceSection(); err != nil {
  1362. return err
  1363. }
  1364. h.Type = r.realType()
  1365. msg, lenOff, err := h.pack(b.msg, b.compression, b.start)
  1366. if err != nil {
  1367. return &nestedError{"ResourceHeader", err}
  1368. }
  1369. preLen := len(msg)
  1370. if msg, err = r.pack(msg, b.compression, b.start); err != nil {
  1371. return &nestedError{"AResource body", err}
  1372. }
  1373. if err := h.fixLen(msg, lenOff, preLen); err != nil {
  1374. return err
  1375. }
  1376. if err := b.incrementSectionCount(); err != nil {
  1377. return err
  1378. }
  1379. b.msg = msg
  1380. return nil
  1381. }
  1382. // AAAAResource adds a single AAAAResource.
  1383. func (b *Builder) AAAAResource(h ResourceHeader, r AAAAResource) error {
  1384. if err := b.checkResourceSection(); err != nil {
  1385. return err
  1386. }
  1387. h.Type = r.realType()
  1388. msg, lenOff, err := h.pack(b.msg, b.compression, b.start)
  1389. if err != nil {
  1390. return &nestedError{"ResourceHeader", err}
  1391. }
  1392. preLen := len(msg)
  1393. if msg, err = r.pack(msg, b.compression, b.start); err != nil {
  1394. return &nestedError{"AAAAResource body", err}
  1395. }
  1396. if err := h.fixLen(msg, lenOff, preLen); err != nil {
  1397. return err
  1398. }
  1399. if err := b.incrementSectionCount(); err != nil {
  1400. return err
  1401. }
  1402. b.msg = msg
  1403. return nil
  1404. }
  1405. // OPTResource adds a single OPTResource.
  1406. func (b *Builder) OPTResource(h ResourceHeader, r OPTResource) error {
  1407. if err := b.checkResourceSection(); err != nil {
  1408. return err
  1409. }
  1410. h.Type = r.realType()
  1411. msg, lenOff, err := h.pack(b.msg, b.compression, b.start)
  1412. if err != nil {
  1413. return &nestedError{"ResourceHeader", err}
  1414. }
  1415. preLen := len(msg)
  1416. if msg, err = r.pack(msg, b.compression, b.start); err != nil {
  1417. return &nestedError{"OPTResource body", err}
  1418. }
  1419. if err := h.fixLen(msg, lenOff, preLen); err != nil {
  1420. return err
  1421. }
  1422. if err := b.incrementSectionCount(); err != nil {
  1423. return err
  1424. }
  1425. b.msg = msg
  1426. return nil
  1427. }
  1428. // Finish ends message building and generates a binary message.
  1429. func (b *Builder) Finish() ([]byte, error) {
  1430. if b.section < sectionHeader {
  1431. return nil, ErrNotStarted
  1432. }
  1433. b.section = sectionDone
  1434. // Space for the header was allocated in NewBuilder.
  1435. b.header.pack(b.msg[b.start:b.start])
  1436. return b.msg, nil
  1437. }
  1438. // A ResourceHeader is the header of a DNS resource record. There are
  1439. // many types of DNS resource records, but they all share the same header.
  1440. type ResourceHeader struct {
  1441. // Name is the domain name for which this resource record pertains.
  1442. Name Name
  1443. // Type is the type of DNS resource record.
  1444. //
  1445. // This field will be set automatically during packing.
  1446. Type Type
  1447. // Class is the class of network to which this DNS resource record
  1448. // pertains.
  1449. Class Class
  1450. // TTL is the length of time (measured in seconds) which this resource
  1451. // record is valid for (time to live). All Resources in a set should
  1452. // have the same TTL (RFC 2181 Section 5.2).
  1453. TTL uint32
  1454. // Length is the length of data in the resource record after the header.
  1455. //
  1456. // This field will be set automatically during packing.
  1457. Length uint16
  1458. }
  1459. // GoString implements fmt.GoStringer.GoString.
  1460. func (h *ResourceHeader) GoString() string {
  1461. return "dnsmessage.ResourceHeader{" +
  1462. "Name: " + h.Name.GoString() + ", " +
  1463. "Type: " + h.Type.GoString() + ", " +
  1464. "Class: " + h.Class.GoString() + ", " +
  1465. "TTL: " + printUint32(h.TTL) + ", " +
  1466. "Length: " + printUint16(h.Length) + "}"
  1467. }
  1468. // pack appends the wire format of the ResourceHeader to oldMsg.
  1469. //
  1470. // lenOff is the offset in msg where the Length field was packed.
  1471. func (h *ResourceHeader) pack(oldMsg []byte, compression map[string]int, compressionOff int) (msg []byte, lenOff int, err error) {
  1472. msg = oldMsg
  1473. if msg, err = h.Name.pack(msg, compression, compressionOff); err != nil {
  1474. return oldMsg, 0, &nestedError{"Name", err}
  1475. }
  1476. msg = packType(msg, h.Type)
  1477. msg = packClass(msg, h.Class)
  1478. msg = packUint32(msg, h.TTL)
  1479. lenOff = len(msg)
  1480. msg = packUint16(msg, h.Length)
  1481. return msg, lenOff, nil
  1482. }
  1483. func (h *ResourceHeader) unpack(msg []byte, off int) (int, error) {
  1484. newOff := off
  1485. var err error
  1486. if newOff, err = h.Name.unpack(msg, newOff); err != nil {
  1487. return off, &nestedError{"Name", err}
  1488. }
  1489. if h.Type, newOff, err = unpackType(msg, newOff); err != nil {
  1490. return off, &nestedError{"Type", err}
  1491. }
  1492. if h.Class, newOff, err = unpackClass(msg, newOff); err != nil {
  1493. return off, &nestedError{"Class", err}
  1494. }
  1495. if h.TTL, newOff, err = unpackUint32(msg, newOff); err != nil {
  1496. return off, &nestedError{"TTL", err}
  1497. }
  1498. if h.Length, newOff, err = unpackUint16(msg, newOff); err != nil {
  1499. return off, &nestedError{"Length", err}
  1500. }
  1501. return newOff, nil
  1502. }
  1503. // fixLen updates a packed ResourceHeader to include the length of the
  1504. // ResourceBody.
  1505. //
  1506. // lenOff is the offset of the ResourceHeader.Length field in msg.
  1507. //
  1508. // preLen is the length that msg was before the ResourceBody was packed.
  1509. func (h *ResourceHeader) fixLen(msg []byte, lenOff int, preLen int) error {
  1510. conLen := len(msg) - preLen
  1511. if conLen > int(^uint16(0)) {
  1512. return errResTooLong
  1513. }
  1514. // Fill in the length now that we know how long the content is.
  1515. packUint16(msg[lenOff:lenOff], uint16(conLen))
  1516. h.Length = uint16(conLen)
  1517. return nil
  1518. }
  1519. // EDNS(0) wire costants.
  1520. const (
  1521. edns0Version = 0
  1522. edns0DNSSECOK = 0x00008000
  1523. ednsVersionMask = 0x00ff0000
  1524. edns0DNSSECOKMask = 0x00ff8000
  1525. )
  1526. // SetEDNS0 configures h for EDNS(0).
  1527. //
  1528. // The provided extRCode must be an extedned RCode.
  1529. func (h *ResourceHeader) SetEDNS0(udpPayloadLen int, extRCode RCode, dnssecOK bool) error {
  1530. h.Name = Name{Data: [nameLen]byte{'.'}, Length: 1} // RFC 6891 section 6.1.2
  1531. h.Type = TypeOPT
  1532. h.Class = Class(udpPayloadLen)
  1533. h.TTL = uint32(extRCode) >> 4 << 24
  1534. if dnssecOK {
  1535. h.TTL |= edns0DNSSECOK
  1536. }
  1537. return nil
  1538. }
  1539. // DNSSECAllowed reports whether the DNSSEC OK bit is set.
  1540. func (h *ResourceHeader) DNSSECAllowed() bool {
  1541. return h.TTL&edns0DNSSECOKMask == edns0DNSSECOK // RFC 6891 section 6.1.3
  1542. }
  1543. // ExtendedRCode returns an extended RCode.
  1544. //
  1545. // The provided rcode must be the RCode in DNS message header.
  1546. func (h *ResourceHeader) ExtendedRCode(rcode RCode) RCode {
  1547. if h.TTL&ednsVersionMask == edns0Version { // RFC 6891 section 6.1.3
  1548. return RCode(h.TTL>>24<<4) | rcode
  1549. }
  1550. return rcode
  1551. }
  1552. func skipResource(msg []byte, off int) (int, error) {
  1553. newOff, err := skipName(msg, off)
  1554. if err != nil {
  1555. return off, &nestedError{"Name", err}
  1556. }
  1557. if newOff, err = skipType(msg, newOff); err != nil {
  1558. return off, &nestedError{"Type", err}
  1559. }
  1560. if newOff, err = skipClass(msg, newOff); err != nil {
  1561. return off, &nestedError{"Class", err}
  1562. }
  1563. if newOff, err = skipUint32(msg, newOff); err != nil {
  1564. return off, &nestedError{"TTL", err}
  1565. }
  1566. length, newOff, err := unpackUint16(msg, newOff)
  1567. if err != nil {
  1568. return off, &nestedError{"Length", err}
  1569. }
  1570. if newOff += int(length); newOff > len(msg) {
  1571. return off, errResourceLen
  1572. }
  1573. return newOff, nil
  1574. }
  1575. // packUint16 appends the wire format of field to msg.
  1576. func packUint16(msg []byte, field uint16) []byte {
  1577. return append(msg, byte(field>>8), byte(field))
  1578. }
  1579. func unpackUint16(msg []byte, off int) (uint16, int, error) {
  1580. if off+uint16Len > len(msg) {
  1581. return 0, off, errBaseLen
  1582. }
  1583. return uint16(msg[off])<<8 | uint16(msg[off+1]), off + uint16Len, nil
  1584. }
  1585. func skipUint16(msg []byte, off int) (int, error) {
  1586. if off+uint16Len > len(msg) {
  1587. return off, errBaseLen
  1588. }
  1589. return off + uint16Len, nil
  1590. }
  1591. // packType appends the wire format of field to msg.
  1592. func packType(msg []byte, field Type) []byte {
  1593. return packUint16(msg, uint16(field))
  1594. }
  1595. func unpackType(msg []byte, off int) (Type, int, error) {
  1596. t, o, err := unpackUint16(msg, off)
  1597. return Type(t), o, err
  1598. }
  1599. func skipType(msg []byte, off int) (int, error) {
  1600. return skipUint16(msg, off)
  1601. }
  1602. // packClass appends the wire format of field to msg.
  1603. func packClass(msg []byte, field Class) []byte {
  1604. return packUint16(msg, uint16(field))
  1605. }
  1606. func unpackClass(msg []byte, off int) (Class, int, error) {
  1607. c, o, err := unpackUint16(msg, off)
  1608. return Class(c), o, err
  1609. }
  1610. func skipClass(msg []byte, off int) (int, error) {
  1611. return skipUint16(msg, off)
  1612. }
  1613. // packUint32 appends the wire format of field to msg.
  1614. func packUint32(msg []byte, field uint32) []byte {
  1615. return append(
  1616. msg,
  1617. byte(field>>24),
  1618. byte(field>>16),
  1619. byte(field>>8),
  1620. byte(field),
  1621. )
  1622. }
  1623. func unpackUint32(msg []byte, off int) (uint32, int, error) {
  1624. if off+uint32Len > len(msg) {
  1625. return 0, off, errBaseLen
  1626. }
  1627. v := uint32(msg[off])<<24 | uint32(msg[off+1])<<16 | uint32(msg[off+2])<<8 | uint32(msg[off+3])
  1628. return v, off + uint32Len, nil
  1629. }
  1630. func skipUint32(msg []byte, off int) (int, error) {
  1631. if off+uint32Len > len(msg) {
  1632. return off, errBaseLen
  1633. }
  1634. return off + uint32Len, nil
  1635. }
  1636. // packText appends the wire format of field to msg.
  1637. func packText(msg []byte, field string) ([]byte, error) {
  1638. l := len(field)
  1639. if l > 255 {
  1640. return nil, errStringTooLong
  1641. }
  1642. msg = append(msg, byte(l))
  1643. msg = append(msg, field...)
  1644. return msg, nil
  1645. }
  1646. func unpackText(msg []byte, off int) (string, int, error) {
  1647. if off >= len(msg) {
  1648. return "", off, errBaseLen
  1649. }
  1650. beginOff := off + 1
  1651. endOff := beginOff + int(msg[off])
  1652. if endOff > len(msg) {
  1653. return "", off, errCalcLen
  1654. }
  1655. return string(msg[beginOff:endOff]), endOff, nil
  1656. }
  1657. func skipText(msg []byte, off int) (int, error) {
  1658. if off >= len(msg) {
  1659. return off, errBaseLen
  1660. }
  1661. endOff := off + 1 + int(msg[off])
  1662. if endOff > len(msg) {
  1663. return off, errCalcLen
  1664. }
  1665. return endOff, nil
  1666. }
  1667. // packBytes appends the wire format of field to msg.
  1668. func packBytes(msg []byte, field []byte) []byte {
  1669. return append(msg, field...)
  1670. }
  1671. func unpackBytes(msg []byte, off int, field []byte) (int, error) {
  1672. newOff := off + len(field)
  1673. if newOff > len(msg) {
  1674. return off, errBaseLen
  1675. }
  1676. copy(field, msg[off:newOff])
  1677. return newOff, nil
  1678. }
  1679. func skipBytes(msg []byte, off int, field []byte) (int, error) {
  1680. newOff := off + len(field)
  1681. if newOff > len(msg) {
  1682. return off, errBaseLen
  1683. }
  1684. return newOff, nil
  1685. }
  1686. const nameLen = 255
  1687. // A Name is a non-encoded domain name. It is used instead of strings to avoid
  1688. // allocations.
  1689. type Name struct {
  1690. Data [nameLen]byte
  1691. Length uint8
  1692. }
  1693. // NewName creates a new Name from a string.
  1694. func NewName(name string) (Name, error) {
  1695. if len([]byte(name)) > nameLen {
  1696. return Name{}, errCalcLen
  1697. }
  1698. n := Name{Length: uint8(len(name))}
  1699. copy(n.Data[:], []byte(name))
  1700. return n, nil
  1701. }
  1702. // MustNewName creates a new Name from a string and panics on error.
  1703. func MustNewName(name string) Name {
  1704. n, err := NewName(name)
  1705. if err != nil {
  1706. panic("creating name: " + err.Error())
  1707. }
  1708. return n
  1709. }
  1710. // String implements fmt.Stringer.String.
  1711. func (n Name) String() string {
  1712. return string(n.Data[:n.Length])
  1713. }
  1714. // GoString implements fmt.GoStringer.GoString.
  1715. func (n *Name) GoString() string {
  1716. return `dnsmessage.MustNewName("` + printString(n.Data[:n.Length]) + `")`
  1717. }
  1718. // pack appends the wire format of the Name to msg.
  1719. //
  1720. // Domain names are a sequence of counted strings split at the dots. They end
  1721. // with a zero-length string. Compression can be used to reuse domain suffixes.
  1722. //
  1723. // The compression map will be updated with new domain suffixes. If compression
  1724. // is nil, compression will not be used.
  1725. func (n *Name) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) {
  1726. oldMsg := msg
  1727. // Add a trailing dot to canonicalize name.
  1728. if n.Length == 0 || n.Data[n.Length-1] != '.' {
  1729. return oldMsg, errNonCanonicalName
  1730. }
  1731. // Allow root domain.
  1732. if n.Data[0] == '.' && n.Length == 1 {
  1733. return append(msg, 0), nil
  1734. }
  1735. // Emit sequence of counted strings, chopping at dots.
  1736. for i, begin := 0, 0; i < int(n.Length); i++ {
  1737. // Check for the end of the segment.
  1738. if n.Data[i] == '.' {
  1739. // The two most significant bits have special meaning.
  1740. // It isn't allowed for segments to be long enough to
  1741. // need them.
  1742. if i-begin >= 1<<6 {
  1743. return oldMsg, errSegTooLong
  1744. }
  1745. // Segments must have a non-zero length.
  1746. if i-begin == 0 {
  1747. return oldMsg, errZeroSegLen
  1748. }
  1749. msg = append(msg, byte(i-begin))
  1750. for j := begin; j < i; j++ {
  1751. msg = append(msg, n.Data[j])
  1752. }
  1753. begin = i + 1
  1754. continue
  1755. }
  1756. // We can only compress domain suffixes starting with a new
  1757. // segment. A pointer is two bytes with the two most significant
  1758. // bits set to 1 to indicate that it is a pointer.
  1759. if (i == 0 || n.Data[i-1] == '.') && compression != nil {
  1760. if ptr, ok := compression[string(n.Data[i:])]; ok {
  1761. // Hit. Emit a pointer instead of the rest of
  1762. // the domain.
  1763. return append(msg, byte(ptr>>8|0xC0), byte(ptr)), nil
  1764. }
  1765. // Miss. Add the suffix to the compression table if the
  1766. // offset can be stored in the available 14 bytes.
  1767. if len(msg) <= int(^uint16(0)>>2) {
  1768. compression[string(n.Data[i:])] = len(msg) - compressionOff
  1769. }
  1770. }
  1771. }
  1772. return append(msg, 0), nil
  1773. }
  1774. // unpack unpacks a domain name.
  1775. func (n *Name) unpack(msg []byte, off int) (int, error) {
  1776. return n.unpackCompressed(msg, off, true /* allowCompression */)
  1777. }
  1778. func (n *Name) unpackCompressed(msg []byte, off int, allowCompression bool) (int, error) {
  1779. // currOff is the current working offset.
  1780. currOff := off
  1781. // newOff is the offset where the next record will start. Pointers lead
  1782. // to data that belongs to other names and thus doesn't count towards to
  1783. // the usage of this name.
  1784. newOff := off
  1785. // ptr is the number of pointers followed.
  1786. var ptr int
  1787. // Name is a slice representation of the name data.
  1788. name := n.Data[:0]
  1789. Loop:
  1790. for {
  1791. if currOff >= len(msg) {
  1792. return off, errBaseLen
  1793. }
  1794. c := int(msg[currOff])
  1795. currOff++
  1796. switch c & 0xC0 {
  1797. case 0x00: // String segment
  1798. if c == 0x00 {
  1799. // A zero length signals the end of the name.
  1800. break Loop
  1801. }
  1802. endOff := currOff + c
  1803. if endOff > len(msg) {
  1804. return off, errCalcLen
  1805. }
  1806. name = append(name, msg[currOff:endOff]...)
  1807. name = append(name, '.')
  1808. currOff = endOff
  1809. case 0xC0: // Pointer
  1810. if !allowCompression {
  1811. return off, errCompressedSRV
  1812. }
  1813. if currOff >= len(msg) {
  1814. return off, errInvalidPtr
  1815. }
  1816. c1 := msg[currOff]
  1817. currOff++
  1818. if ptr == 0 {
  1819. newOff = currOff
  1820. }
  1821. // Don't follow too many pointers, maybe there's a loop.
  1822. if ptr++; ptr > 10 {
  1823. return off, errTooManyPtr
  1824. }
  1825. currOff = (c^0xC0)<<8 | int(c1)
  1826. default:
  1827. // Prefixes 0x80 and 0x40 are reserved.
  1828. return off, errReserved
  1829. }
  1830. }
  1831. if len(name) == 0 {
  1832. name = append(name, '.')
  1833. }
  1834. if len(name) > len(n.Data) {
  1835. return off, errCalcLen
  1836. }
  1837. n.Length = uint8(len(name))
  1838. if ptr == 0 {
  1839. newOff = currOff
  1840. }
  1841. return newOff, nil
  1842. }
  1843. func skipName(msg []byte, off int) (int, error) {
  1844. // newOff is the offset where the next record will start. Pointers lead
  1845. // to data that belongs to other names and thus doesn't count towards to
  1846. // the usage of this name.
  1847. newOff := off
  1848. Loop:
  1849. for {
  1850. if newOff >= len(msg) {
  1851. return off, errBaseLen
  1852. }
  1853. c := int(msg[newOff])
  1854. newOff++
  1855. switch c & 0xC0 {
  1856. case 0x00:
  1857. if c == 0x00 {
  1858. // A zero length signals the end of the name.
  1859. break Loop
  1860. }
  1861. // literal string
  1862. newOff += c
  1863. if newOff > len(msg) {
  1864. return off, errCalcLen
  1865. }
  1866. case 0xC0:
  1867. // Pointer to somewhere else in msg.
  1868. // Pointers are two bytes.
  1869. newOff++
  1870. // Don't follow the pointer as the data here has ended.
  1871. break Loop
  1872. default:
  1873. // Prefixes 0x80 and 0x40 are reserved.
  1874. return off, errReserved
  1875. }
  1876. }
  1877. return newOff, nil
  1878. }
  1879. // A Question is a DNS query.
  1880. type Question struct {
  1881. Name Name
  1882. Type Type
  1883. Class Class
  1884. }
  1885. // pack appends the wire format of the Question to msg.
  1886. func (q *Question) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) {
  1887. msg, err := q.Name.pack(msg, compression, compressionOff)
  1888. if err != nil {
  1889. return msg, &nestedError{"Name", err}
  1890. }
  1891. msg = packType(msg, q.Type)
  1892. return packClass(msg, q.Class), nil
  1893. }
  1894. // GoString implements fmt.GoStringer.GoString.
  1895. func (q *Question) GoString() string {
  1896. return "dnsmessage.Question{" +
  1897. "Name: " + q.Name.GoString() + ", " +
  1898. "Type: " + q.Type.GoString() + ", " +
  1899. "Class: " + q.Class.GoString() + "}"
  1900. }
  1901. func unpackResourceBody(msg []byte, off int, hdr ResourceHeader) (ResourceBody, int, error) {
  1902. var (
  1903. r ResourceBody
  1904. err error
  1905. name string
  1906. )
  1907. switch hdr.Type {
  1908. case TypeA:
  1909. var rb AResource
  1910. rb, err = unpackAResource(msg, off)
  1911. r = &rb
  1912. name = "A"
  1913. case TypeNS:
  1914. var rb NSResource
  1915. rb, err = unpackNSResource(msg, off)
  1916. r = &rb
  1917. name = "NS"
  1918. case TypeCNAME:
  1919. var rb CNAMEResource
  1920. rb, err = unpackCNAMEResource(msg, off)
  1921. r = &rb
  1922. name = "CNAME"
  1923. case TypeSOA:
  1924. var rb SOAResource
  1925. rb, err = unpackSOAResource(msg, off)
  1926. r = &rb
  1927. name = "SOA"
  1928. case TypePTR:
  1929. var rb PTRResource
  1930. rb, err = unpackPTRResource(msg, off)
  1931. r = &rb
  1932. name = "PTR"
  1933. case TypeMX:
  1934. var rb MXResource
  1935. rb, err = unpackMXResource(msg, off)
  1936. r = &rb
  1937. name = "MX"
  1938. case TypeTXT:
  1939. var rb TXTResource
  1940. rb, err = unpackTXTResource(msg, off, hdr.Length)
  1941. r = &rb
  1942. name = "TXT"
  1943. case TypeAAAA:
  1944. var rb AAAAResource
  1945. rb, err = unpackAAAAResource(msg, off)
  1946. r = &rb
  1947. name = "AAAA"
  1948. case TypeSRV:
  1949. var rb SRVResource
  1950. rb, err = unpackSRVResource(msg, off)
  1951. r = &rb
  1952. name = "SRV"
  1953. case TypeOPT:
  1954. var rb OPTResource
  1955. rb, err = unpackOPTResource(msg, off, hdr.Length)
  1956. r = &rb
  1957. name = "OPT"
  1958. }
  1959. if err != nil {
  1960. return nil, off, &nestedError{name + " record", err}
  1961. }
  1962. if r == nil {
  1963. return nil, off, errors.New("invalid resource type: " + string(hdr.Type+'0'))
  1964. }
  1965. return r, off + int(hdr.Length), nil
  1966. }
  1967. // A CNAMEResource is a CNAME Resource record.
  1968. type CNAMEResource struct {
  1969. CNAME Name
  1970. }
  1971. func (r *CNAMEResource) realType() Type {
  1972. return TypeCNAME
  1973. }
  1974. // pack appends the wire format of the CNAMEResource to msg.
  1975. func (r *CNAMEResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) {
  1976. return r.CNAME.pack(msg, compression, compressionOff)
  1977. }
  1978. // GoString implements fmt.GoStringer.GoString.
  1979. func (r *CNAMEResource) GoString() string {
  1980. return "dnsmessage.CNAMEResource{CNAME: " + r.CNAME.GoString() + "}"
  1981. }
  1982. func unpackCNAMEResource(msg []byte, off int) (CNAMEResource, error) {
  1983. var cname Name
  1984. if _, err := cname.unpack(msg, off); err != nil {
  1985. return CNAMEResource{}, err
  1986. }
  1987. return CNAMEResource{cname}, nil
  1988. }
  1989. // An MXResource is an MX Resource record.
  1990. type MXResource struct {
  1991. Pref uint16
  1992. MX Name
  1993. }
  1994. func (r *MXResource) realType() Type {
  1995. return TypeMX
  1996. }
  1997. // pack appends the wire format of the MXResource to msg.
  1998. func (r *MXResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) {
  1999. oldMsg := msg
  2000. msg = packUint16(msg, r.Pref)
  2001. msg, err := r.MX.pack(msg, compression, compressionOff)
  2002. if err != nil {
  2003. return oldMsg, &nestedError{"MXResource.MX", err}
  2004. }
  2005. return msg, nil
  2006. }
  2007. // GoString implements fmt.GoStringer.GoString.
  2008. func (r *MXResource) GoString() string {
  2009. return "dnsmessage.MXResource{" +
  2010. "Pref: " + printUint16(r.Pref) + ", " +
  2011. "MX: " + r.MX.GoString() + "}"
  2012. }
  2013. func unpackMXResource(msg []byte, off int) (MXResource, error) {
  2014. pref, off, err := unpackUint16(msg, off)
  2015. if err != nil {
  2016. return MXResource{}, &nestedError{"Pref", err}
  2017. }
  2018. var mx Name
  2019. if _, err := mx.unpack(msg, off); err != nil {
  2020. return MXResource{}, &nestedError{"MX", err}
  2021. }
  2022. return MXResource{pref, mx}, nil
  2023. }
  2024. // An NSResource is an NS Resource record.
  2025. type NSResource struct {
  2026. NS Name
  2027. }
  2028. func (r *NSResource) realType() Type {
  2029. return TypeNS
  2030. }
  2031. // pack appends the wire format of the NSResource to msg.
  2032. func (r *NSResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) {
  2033. return r.NS.pack(msg, compression, compressionOff)
  2034. }
  2035. // GoString implements fmt.GoStringer.GoString.
  2036. func (r *NSResource) GoString() string {
  2037. return "dnsmessage.NSResource{NS: " + r.NS.GoString() + "}"
  2038. }
  2039. func unpackNSResource(msg []byte, off int) (NSResource, error) {
  2040. var ns Name
  2041. if _, err := ns.unpack(msg, off); err != nil {
  2042. return NSResource{}, err
  2043. }
  2044. return NSResource{ns}, nil
  2045. }
  2046. // A PTRResource is a PTR Resource record.
  2047. type PTRResource struct {
  2048. PTR Name
  2049. }
  2050. func (r *PTRResource) realType() Type {
  2051. return TypePTR
  2052. }
  2053. // pack appends the wire format of the PTRResource to msg.
  2054. func (r *PTRResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) {
  2055. return r.PTR.pack(msg, compression, compressionOff)
  2056. }
  2057. // GoString implements fmt.GoStringer.GoString.
  2058. func (r *PTRResource) GoString() string {
  2059. return "dnsmessage.PTRResource{PTR: " + r.PTR.GoString() + "}"
  2060. }
  2061. func unpackPTRResource(msg []byte, off int) (PTRResource, error) {
  2062. var ptr Name
  2063. if _, err := ptr.unpack(msg, off); err != nil {
  2064. return PTRResource{}, err
  2065. }
  2066. return PTRResource{ptr}, nil
  2067. }
  2068. // An SOAResource is an SOA Resource record.
  2069. type SOAResource struct {
  2070. NS Name
  2071. MBox Name
  2072. Serial uint32
  2073. Refresh uint32
  2074. Retry uint32
  2075. Expire uint32
  2076. // MinTTL the is the default TTL of Resources records which did not
  2077. // contain a TTL value and the TTL of negative responses. (RFC 2308
  2078. // Section 4)
  2079. MinTTL uint32
  2080. }
  2081. func (r *SOAResource) realType() Type {
  2082. return TypeSOA
  2083. }
  2084. // pack appends the wire format of the SOAResource to msg.
  2085. func (r *SOAResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) {
  2086. oldMsg := msg
  2087. msg, err := r.NS.pack(msg, compression, compressionOff)
  2088. if err != nil {
  2089. return oldMsg, &nestedError{"SOAResource.NS", err}
  2090. }
  2091. msg, err = r.MBox.pack(msg, compression, compressionOff)
  2092. if err != nil {
  2093. return oldMsg, &nestedError{"SOAResource.MBox", err}
  2094. }
  2095. msg = packUint32(msg, r.Serial)
  2096. msg = packUint32(msg, r.Refresh)
  2097. msg = packUint32(msg, r.Retry)
  2098. msg = packUint32(msg, r.Expire)
  2099. return packUint32(msg, r.MinTTL), nil
  2100. }
  2101. // GoString implements fmt.GoStringer.GoString.
  2102. func (r *SOAResource) GoString() string {
  2103. return "dnsmessage.SOAResource{" +
  2104. "NS: " + r.NS.GoString() + ", " +
  2105. "MBox: " + r.MBox.GoString() + ", " +
  2106. "Serial: " + printUint32(r.Serial) + ", " +
  2107. "Refresh: " + printUint32(r.Refresh) + ", " +
  2108. "Retry: " + printUint32(r.Retry) + ", " +
  2109. "Expire: " + printUint32(r.Expire) + ", " +
  2110. "MinTTL: " + printUint32(r.MinTTL) + "}"
  2111. }
  2112. func unpackSOAResource(msg []byte, off int) (SOAResource, error) {
  2113. var ns Name
  2114. off, err := ns.unpack(msg, off)
  2115. if err != nil {
  2116. return SOAResource{}, &nestedError{"NS", err}
  2117. }
  2118. var mbox Name
  2119. if off, err = mbox.unpack(msg, off); err != nil {
  2120. return SOAResource{}, &nestedError{"MBox", err}
  2121. }
  2122. serial, off, err := unpackUint32(msg, off)
  2123. if err != nil {
  2124. return SOAResource{}, &nestedError{"Serial", err}
  2125. }
  2126. refresh, off, err := unpackUint32(msg, off)
  2127. if err != nil {
  2128. return SOAResource{}, &nestedError{"Refresh", err}
  2129. }
  2130. retry, off, err := unpackUint32(msg, off)
  2131. if err != nil {
  2132. return SOAResource{}, &nestedError{"Retry", err}
  2133. }
  2134. expire, off, err := unpackUint32(msg, off)
  2135. if err != nil {
  2136. return SOAResource{}, &nestedError{"Expire", err}
  2137. }
  2138. minTTL, _, err := unpackUint32(msg, off)
  2139. if err != nil {
  2140. return SOAResource{}, &nestedError{"MinTTL", err}
  2141. }
  2142. return SOAResource{ns, mbox, serial, refresh, retry, expire, minTTL}, nil
  2143. }
  2144. // A TXTResource is a TXT Resource record.
  2145. type TXTResource struct {
  2146. TXT []string
  2147. }
  2148. func (r *TXTResource) realType() Type {
  2149. return TypeTXT
  2150. }
  2151. // pack appends the wire format of the TXTResource to msg.
  2152. func (r *TXTResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) {
  2153. oldMsg := msg
  2154. for _, s := range r.TXT {
  2155. var err error
  2156. msg, err = packText(msg, s)
  2157. if err != nil {
  2158. return oldMsg, err
  2159. }
  2160. }
  2161. return msg, nil
  2162. }
  2163. // GoString implements fmt.GoStringer.GoString.
  2164. func (r *TXTResource) GoString() string {
  2165. s := "dnsmessage.TXTResource{TXT: []string{"
  2166. if len(r.TXT) == 0 {
  2167. return s + "}}"
  2168. }
  2169. s += `"` + printString([]byte(r.TXT[0]))
  2170. for _, t := range r.TXT[1:] {
  2171. s += `", "` + printString([]byte(t))
  2172. }
  2173. return s + `"}}`
  2174. }
  2175. func unpackTXTResource(msg []byte, off int, length uint16) (TXTResource, error) {
  2176. txts := make([]string, 0, 1)
  2177. for n := uint16(0); n < length; {
  2178. var t string
  2179. var err error
  2180. if t, off, err = unpackText(msg, off); err != nil {
  2181. return TXTResource{}, &nestedError{"text", err}
  2182. }
  2183. // Check if we got too many bytes.
  2184. if length-n < uint16(len(t))+1 {
  2185. return TXTResource{}, errCalcLen
  2186. }
  2187. n += uint16(len(t)) + 1
  2188. txts = append(txts, t)
  2189. }
  2190. return TXTResource{txts}, nil
  2191. }
  2192. // An SRVResource is an SRV Resource record.
  2193. type SRVResource struct {
  2194. Priority uint16
  2195. Weight uint16
  2196. Port uint16
  2197. Target Name // Not compressed as per RFC 2782.
  2198. }
  2199. func (r *SRVResource) realType() Type {
  2200. return TypeSRV
  2201. }
  2202. // pack appends the wire format of the SRVResource to msg.
  2203. func (r *SRVResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) {
  2204. oldMsg := msg
  2205. msg = packUint16(msg, r.Priority)
  2206. msg = packUint16(msg, r.Weight)
  2207. msg = packUint16(msg, r.Port)
  2208. msg, err := r.Target.pack(msg, nil, compressionOff)
  2209. if err != nil {
  2210. return oldMsg, &nestedError{"SRVResource.Target", err}
  2211. }
  2212. return msg, nil
  2213. }
  2214. // GoString implements fmt.GoStringer.GoString.
  2215. func (r *SRVResource) GoString() string {
  2216. return "dnsmessage.SRVResource{" +
  2217. "Priority: " + printUint16(r.Priority) + ", " +
  2218. "Weight: " + printUint16(r.Weight) + ", " +
  2219. "Port: " + printUint16(r.Port) + ", " +
  2220. "Target: " + r.Target.GoString() + "}"
  2221. }
  2222. func unpackSRVResource(msg []byte, off int) (SRVResource, error) {
  2223. priority, off, err := unpackUint16(msg, off)
  2224. if err != nil {
  2225. return SRVResource{}, &nestedError{"Priority", err}
  2226. }
  2227. weight, off, err := unpackUint16(msg, off)
  2228. if err != nil {
  2229. return SRVResource{}, &nestedError{"Weight", err}
  2230. }
  2231. port, off, err := unpackUint16(msg, off)
  2232. if err != nil {
  2233. return SRVResource{}, &nestedError{"Port", err}
  2234. }
  2235. var target Name
  2236. if _, err := target.unpackCompressed(msg, off, false /* allowCompression */); err != nil {
  2237. return SRVResource{}, &nestedError{"Target", err}
  2238. }
  2239. return SRVResource{priority, weight, port, target}, nil
  2240. }
  2241. // An AResource is an A Resource record.
  2242. type AResource struct {
  2243. A [4]byte
  2244. }
  2245. func (r *AResource) realType() Type {
  2246. return TypeA
  2247. }
  2248. // pack appends the wire format of the AResource to msg.
  2249. func (r *AResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) {
  2250. return packBytes(msg, r.A[:]), nil
  2251. }
  2252. // GoString implements fmt.GoStringer.GoString.
  2253. func (r *AResource) GoString() string {
  2254. return "dnsmessage.AResource{" +
  2255. "A: [4]byte{" + printByteSlice(r.A[:]) + "}}"
  2256. }
  2257. func unpackAResource(msg []byte, off int) (AResource, error) {
  2258. var a [4]byte
  2259. if _, err := unpackBytes(msg, off, a[:]); err != nil {
  2260. return AResource{}, err
  2261. }
  2262. return AResource{a}, nil
  2263. }
  2264. // An AAAAResource is an AAAA Resource record.
  2265. type AAAAResource struct {
  2266. AAAA [16]byte
  2267. }
  2268. func (r *AAAAResource) realType() Type {
  2269. return TypeAAAA
  2270. }
  2271. // GoString implements fmt.GoStringer.GoString.
  2272. func (r *AAAAResource) GoString() string {
  2273. return "dnsmessage.AAAAResource{" +
  2274. "AAAA: [16]byte{" + printByteSlice(r.AAAA[:]) + "}}"
  2275. }
  2276. // pack appends the wire format of the AAAAResource to msg.
  2277. func (r *AAAAResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) {
  2278. return packBytes(msg, r.AAAA[:]), nil
  2279. }
  2280. func unpackAAAAResource(msg []byte, off int) (AAAAResource, error) {
  2281. var aaaa [16]byte
  2282. if _, err := unpackBytes(msg, off, aaaa[:]); err != nil {
  2283. return AAAAResource{}, err
  2284. }
  2285. return AAAAResource{aaaa}, nil
  2286. }
  2287. // An OPTResource is an OPT pseudo Resource record.
  2288. //
  2289. // The pseudo resource record is part of the extension mechanisms for DNS
  2290. // as defined in RFC 6891.
  2291. type OPTResource struct {
  2292. Options []Option
  2293. }
  2294. // An Option represents a DNS message option within OPTResource.
  2295. //
  2296. // The message option is part of the extension mechanisms for DNS as
  2297. // defined in RFC 6891.
  2298. type Option struct {
  2299. Code uint16 // option code
  2300. Data []byte
  2301. }
  2302. // GoString implements fmt.GoStringer.GoString.
  2303. func (o *Option) GoString() string {
  2304. return "dnsmessage.Option{" +
  2305. "Code: " + printUint16(o.Code) + ", " +
  2306. "Data: []byte{" + printByteSlice(o.Data) + "}}"
  2307. }
  2308. func (r *OPTResource) realType() Type {
  2309. return TypeOPT
  2310. }
  2311. func (r *OPTResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) {
  2312. for _, opt := range r.Options {
  2313. msg = packUint16(msg, opt.Code)
  2314. l := uint16(len(opt.Data))
  2315. msg = packUint16(msg, l)
  2316. msg = packBytes(msg, opt.Data)
  2317. }
  2318. return msg, nil
  2319. }
  2320. // GoString implements fmt.GoStringer.GoString.
  2321. func (r *OPTResource) GoString() string {
  2322. s := "dnsmessage.OPTResource{Options: []dnsmessage.Option{"
  2323. if len(r.Options) == 0 {
  2324. return s + "}}"
  2325. }
  2326. s += r.Options[0].GoString()
  2327. for _, o := range r.Options[1:] {
  2328. s += ", " + o.GoString()
  2329. }
  2330. return s + "}}"
  2331. }
  2332. func unpackOPTResource(msg []byte, off int, length uint16) (OPTResource, error) {
  2333. var opts []Option
  2334. for oldOff := off; off < oldOff+int(length); {
  2335. var err error
  2336. var o Option
  2337. o.Code, off, err = unpackUint16(msg, off)
  2338. if err != nil {
  2339. return OPTResource{}, &nestedError{"Code", err}
  2340. }
  2341. var l uint16
  2342. l, off, err = unpackUint16(msg, off)
  2343. if err != nil {
  2344. return OPTResource{}, &nestedError{"Data", err}
  2345. }
  2346. o.Data = make([]byte, l)
  2347. if copy(o.Data, msg[off:]) != int(l) {
  2348. return OPTResource{}, &nestedError{"Data", errCalcLen}
  2349. }
  2350. off += int(l)
  2351. opts = append(opts, o)
  2352. }
  2353. return OPTResource{opts}, nil
  2354. }