You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2001 lines
49 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. // This implementation is designed to minimize heap allocations and avoid
  8. // unnecessary packing and unpacking as much as possible.
  9. package dnsmessage
  10. import (
  11. "errors"
  12. )
  13. // Packet formats
  14. // A Type is a type of DNS request and response.
  15. type Type uint16
  16. // A Class is a type of network.
  17. type Class uint16
  18. // An OpCode is a DNS operation code.
  19. type OpCode uint16
  20. // An RCode is a DNS response status code.
  21. type RCode uint16
  22. // Wire constants.
  23. const (
  24. // ResourceHeader.Type and Question.Type
  25. TypeA Type = 1
  26. TypeNS Type = 2
  27. TypeCNAME Type = 5
  28. TypeSOA Type = 6
  29. TypePTR Type = 12
  30. TypeMX Type = 15
  31. TypeTXT Type = 16
  32. TypeAAAA Type = 28
  33. TypeSRV Type = 33
  34. // Question.Type
  35. TypeWKS Type = 11
  36. TypeHINFO Type = 13
  37. TypeMINFO Type = 14
  38. TypeAXFR Type = 252
  39. TypeALL Type = 255
  40. // ResourceHeader.Class and Question.Class
  41. ClassINET Class = 1
  42. ClassCSNET Class = 2
  43. ClassCHAOS Class = 3
  44. ClassHESIOD Class = 4
  45. // Question.Class
  46. ClassANY Class = 255
  47. // Message.Rcode
  48. RCodeSuccess RCode = 0
  49. RCodeFormatError RCode = 1
  50. RCodeServerFailure RCode = 2
  51. RCodeNameError RCode = 3
  52. RCodeNotImplemented RCode = 4
  53. RCodeRefused RCode = 5
  54. )
  55. var (
  56. // ErrNotStarted indicates that the prerequisite information isn't
  57. // available yet because the previous records haven't been appropriately
  58. // parsed, skipped or finished.
  59. ErrNotStarted = errors.New("parsing/packing of this type isn't available yet")
  60. // ErrSectionDone indicated that all records in the section have been
  61. // parsed or finished.
  62. ErrSectionDone = errors.New("parsing/packing of this section has completed")
  63. errBaseLen = errors.New("insufficient data for base length type")
  64. errCalcLen = errors.New("insufficient data for calculated length type")
  65. errReserved = errors.New("segment prefix is reserved")
  66. errTooManyPtr = errors.New("too many pointers (>10)")
  67. errInvalidPtr = errors.New("invalid pointer")
  68. errNilResouceBody = errors.New("nil resource body")
  69. errResourceLen = errors.New("insufficient data for resource body length")
  70. errSegTooLong = errors.New("segment length too long")
  71. errZeroSegLen = errors.New("zero length segment")
  72. errResTooLong = errors.New("resource length too long")
  73. errTooManyQuestions = errors.New("too many Questions to pack (>65535)")
  74. errTooManyAnswers = errors.New("too many Answers to pack (>65535)")
  75. errTooManyAuthorities = errors.New("too many Authorities to pack (>65535)")
  76. errTooManyAdditionals = errors.New("too many Additionals to pack (>65535)")
  77. errNonCanonicalName = errors.New("name is not in canonical format (it must end with a .)")
  78. )
  79. // Internal constants.
  80. const (
  81. // packStartingCap is the default initial buffer size allocated during
  82. // packing.
  83. //
  84. // The starting capacity doesn't matter too much, but most DNS responses
  85. // Will be <= 512 bytes as it is the limit for DNS over UDP.
  86. packStartingCap = 512
  87. // uint16Len is the length (in bytes) of a uint16.
  88. uint16Len = 2
  89. // uint32Len is the length (in bytes) of a uint32.
  90. uint32Len = 4
  91. // headerLen is the length (in bytes) of a DNS header.
  92. //
  93. // A header is comprised of 6 uint16s and no padding.
  94. headerLen = 6 * uint16Len
  95. )
  96. type nestedError struct {
  97. // s is the current level's error message.
  98. s string
  99. // err is the nested error.
  100. err error
  101. }
  102. // nestedError implements error.Error.
  103. func (e *nestedError) Error() string {
  104. return e.s + ": " + e.err.Error()
  105. }
  106. // Header is a representation of a DNS message header.
  107. type Header struct {
  108. ID uint16
  109. Response bool
  110. OpCode OpCode
  111. Authoritative bool
  112. Truncated bool
  113. RecursionDesired bool
  114. RecursionAvailable bool
  115. RCode RCode
  116. }
  117. func (m *Header) pack() (id uint16, bits uint16) {
  118. id = m.ID
  119. bits = uint16(m.OpCode)<<11 | uint16(m.RCode)
  120. if m.RecursionAvailable {
  121. bits |= headerBitRA
  122. }
  123. if m.RecursionDesired {
  124. bits |= headerBitRD
  125. }
  126. if m.Truncated {
  127. bits |= headerBitTC
  128. }
  129. if m.Authoritative {
  130. bits |= headerBitAA
  131. }
  132. if m.Response {
  133. bits |= headerBitQR
  134. }
  135. return
  136. }
  137. // Message is a representation of a DNS message.
  138. type Message struct {
  139. Header
  140. Questions []Question
  141. Answers []Resource
  142. Authorities []Resource
  143. Additionals []Resource
  144. }
  145. type section uint8
  146. const (
  147. sectionNotStarted section = iota
  148. sectionHeader
  149. sectionQuestions
  150. sectionAnswers
  151. sectionAuthorities
  152. sectionAdditionals
  153. sectionDone
  154. headerBitQR = 1 << 15 // query/response (response=1)
  155. headerBitAA = 1 << 10 // authoritative
  156. headerBitTC = 1 << 9 // truncated
  157. headerBitRD = 1 << 8 // recursion desired
  158. headerBitRA = 1 << 7 // recursion available
  159. )
  160. var sectionNames = map[section]string{
  161. sectionHeader: "header",
  162. sectionQuestions: "Question",
  163. sectionAnswers: "Answer",
  164. sectionAuthorities: "Authority",
  165. sectionAdditionals: "Additional",
  166. }
  167. // header is the wire format for a DNS message header.
  168. type header struct {
  169. id uint16
  170. bits uint16
  171. questions uint16
  172. answers uint16
  173. authorities uint16
  174. additionals uint16
  175. }
  176. func (h *header) count(sec section) uint16 {
  177. switch sec {
  178. case sectionQuestions:
  179. return h.questions
  180. case sectionAnswers:
  181. return h.answers
  182. case sectionAuthorities:
  183. return h.authorities
  184. case sectionAdditionals:
  185. return h.additionals
  186. }
  187. return 0
  188. }
  189. func (h *header) pack(msg []byte) []byte {
  190. msg = packUint16(msg, h.id)
  191. msg = packUint16(msg, h.bits)
  192. msg = packUint16(msg, h.questions)
  193. msg = packUint16(msg, h.answers)
  194. msg = packUint16(msg, h.authorities)
  195. return packUint16(msg, h.additionals)
  196. }
  197. func (h *header) unpack(msg []byte, off int) (int, error) {
  198. newOff := off
  199. var err error
  200. if h.id, newOff, err = unpackUint16(msg, newOff); err != nil {
  201. return off, &nestedError{"id", err}
  202. }
  203. if h.bits, newOff, err = unpackUint16(msg, newOff); err != nil {
  204. return off, &nestedError{"bits", err}
  205. }
  206. if h.questions, newOff, err = unpackUint16(msg, newOff); err != nil {
  207. return off, &nestedError{"questions", err}
  208. }
  209. if h.answers, newOff, err = unpackUint16(msg, newOff); err != nil {
  210. return off, &nestedError{"answers", err}
  211. }
  212. if h.authorities, newOff, err = unpackUint16(msg, newOff); err != nil {
  213. return off, &nestedError{"authorities", err}
  214. }
  215. if h.additionals, newOff, err = unpackUint16(msg, newOff); err != nil {
  216. return off, &nestedError{"additionals", err}
  217. }
  218. return newOff, nil
  219. }
  220. func (h *header) header() Header {
  221. return Header{
  222. ID: h.id,
  223. Response: (h.bits & headerBitQR) != 0,
  224. OpCode: OpCode(h.bits>>11) & 0xF,
  225. Authoritative: (h.bits & headerBitAA) != 0,
  226. Truncated: (h.bits & headerBitTC) != 0,
  227. RecursionDesired: (h.bits & headerBitRD) != 0,
  228. RecursionAvailable: (h.bits & headerBitRA) != 0,
  229. RCode: RCode(h.bits & 0xF),
  230. }
  231. }
  232. // A Resource is a DNS resource record.
  233. type Resource struct {
  234. Header ResourceHeader
  235. Body ResourceBody
  236. }
  237. // A ResourceBody is a DNS resource record minus the header.
  238. type ResourceBody interface {
  239. // pack packs a Resource except for its header.
  240. pack(msg []byte, compression map[string]int) ([]byte, error)
  241. // realType returns the actual type of the Resource. This is used to
  242. // fill in the header Type field.
  243. realType() Type
  244. }
  245. func (r *Resource) pack(msg []byte, compression map[string]int) ([]byte, error) {
  246. if r.Body == nil {
  247. return msg, errNilResouceBody
  248. }
  249. oldMsg := msg
  250. r.Header.Type = r.Body.realType()
  251. msg, length, err := r.Header.pack(msg, compression)
  252. if err != nil {
  253. return msg, &nestedError{"ResourceHeader", err}
  254. }
  255. preLen := len(msg)
  256. msg, err = r.Body.pack(msg, compression)
  257. if err != nil {
  258. return msg, &nestedError{"content", err}
  259. }
  260. if err := r.Header.fixLen(msg, length, preLen); err != nil {
  261. return oldMsg, err
  262. }
  263. return msg, nil
  264. }
  265. // A Parser allows incrementally parsing a DNS message.
  266. //
  267. // When parsing is started, the Header is parsed. Next, each Question can be
  268. // either parsed or skipped. Alternatively, all Questions can be skipped at
  269. // once. When all Questions have been parsed, attempting to parse Questions
  270. // will return (nil, nil) and attempting to skip Questions will return
  271. // (true, nil). After all Questions have been either parsed or skipped, all
  272. // Answers, Authorities and Additionals can be either parsed or skipped in the
  273. // same way, and each type of Resource must be fully parsed or skipped before
  274. // proceeding to the next type of Resource.
  275. //
  276. // Note that there is no requirement to fully skip or parse the message.
  277. type Parser struct {
  278. msg []byte
  279. header header
  280. section section
  281. off int
  282. index int
  283. resHeaderValid bool
  284. resHeader ResourceHeader
  285. }
  286. // Start parses the header and enables the parsing of Questions.
  287. func (p *Parser) Start(msg []byte) (Header, error) {
  288. if p.msg != nil {
  289. *p = Parser{}
  290. }
  291. p.msg = msg
  292. var err error
  293. if p.off, err = p.header.unpack(msg, 0); err != nil {
  294. return Header{}, &nestedError{"unpacking header", err}
  295. }
  296. p.section = sectionQuestions
  297. return p.header.header(), nil
  298. }
  299. func (p *Parser) checkAdvance(sec section) error {
  300. if p.section < sec {
  301. return ErrNotStarted
  302. }
  303. if p.section > sec {
  304. return ErrSectionDone
  305. }
  306. p.resHeaderValid = false
  307. if p.index == int(p.header.count(sec)) {
  308. p.index = 0
  309. p.section++
  310. return ErrSectionDone
  311. }
  312. return nil
  313. }
  314. func (p *Parser) resource(sec section) (Resource, error) {
  315. var r Resource
  316. var err error
  317. r.Header, err = p.resourceHeader(sec)
  318. if err != nil {
  319. return r, err
  320. }
  321. p.resHeaderValid = false
  322. r.Body, p.off, err = unpackResourceBody(p.msg, p.off, r.Header)
  323. if err != nil {
  324. return Resource{}, &nestedError{"unpacking " + sectionNames[sec], err}
  325. }
  326. p.index++
  327. return r, nil
  328. }
  329. func (p *Parser) resourceHeader(sec section) (ResourceHeader, error) {
  330. if p.resHeaderValid {
  331. return p.resHeader, nil
  332. }
  333. if err := p.checkAdvance(sec); err != nil {
  334. return ResourceHeader{}, err
  335. }
  336. var hdr ResourceHeader
  337. off, err := hdr.unpack(p.msg, p.off)
  338. if err != nil {
  339. return ResourceHeader{}, err
  340. }
  341. p.resHeaderValid = true
  342. p.resHeader = hdr
  343. p.off = off
  344. return hdr, nil
  345. }
  346. func (p *Parser) skipResource(sec section) error {
  347. if p.resHeaderValid {
  348. newOff := p.off + int(p.resHeader.Length)
  349. if newOff > len(p.msg) {
  350. return errResourceLen
  351. }
  352. p.off = newOff
  353. p.resHeaderValid = false
  354. p.index++
  355. return nil
  356. }
  357. if err := p.checkAdvance(sec); err != nil {
  358. return err
  359. }
  360. var err error
  361. p.off, err = skipResource(p.msg, p.off)
  362. if err != nil {
  363. return &nestedError{"skipping: " + sectionNames[sec], err}
  364. }
  365. p.index++
  366. return nil
  367. }
  368. // Question parses a single Question.
  369. func (p *Parser) Question() (Question, error) {
  370. if err := p.checkAdvance(sectionQuestions); err != nil {
  371. return Question{}, err
  372. }
  373. var name Name
  374. off, err := name.unpack(p.msg, p.off)
  375. if err != nil {
  376. return Question{}, &nestedError{"unpacking Question.Name", err}
  377. }
  378. typ, off, err := unpackType(p.msg, off)
  379. if err != nil {
  380. return Question{}, &nestedError{"unpacking Question.Type", err}
  381. }
  382. class, off, err := unpackClass(p.msg, off)
  383. if err != nil {
  384. return Question{}, &nestedError{"unpacking Question.Class", err}
  385. }
  386. p.off = off
  387. p.index++
  388. return Question{name, typ, class}, nil
  389. }
  390. // AllQuestions parses all Questions.
  391. func (p *Parser) AllQuestions() ([]Question, error) {
  392. qs := make([]Question, 0, p.header.questions)
  393. for {
  394. q, err := p.Question()
  395. if err == ErrSectionDone {
  396. return qs, nil
  397. }
  398. if err != nil {
  399. return nil, err
  400. }
  401. qs = append(qs, q)
  402. }
  403. }
  404. // SkipQuestion skips a single Question.
  405. func (p *Parser) SkipQuestion() error {
  406. if err := p.checkAdvance(sectionQuestions); err != nil {
  407. return err
  408. }
  409. off, err := skipName(p.msg, p.off)
  410. if err != nil {
  411. return &nestedError{"skipping Question Name", err}
  412. }
  413. if off, err = skipType(p.msg, off); err != nil {
  414. return &nestedError{"skipping Question Type", err}
  415. }
  416. if off, err = skipClass(p.msg, off); err != nil {
  417. return &nestedError{"skipping Question Class", err}
  418. }
  419. p.off = off
  420. p.index++
  421. return nil
  422. }
  423. // SkipAllQuestions skips all Questions.
  424. func (p *Parser) SkipAllQuestions() error {
  425. for {
  426. if err := p.SkipQuestion(); err == ErrSectionDone {
  427. return nil
  428. } else if err != nil {
  429. return err
  430. }
  431. }
  432. }
  433. // AnswerHeader parses a single Answer ResourceHeader.
  434. func (p *Parser) AnswerHeader() (ResourceHeader, error) {
  435. return p.resourceHeader(sectionAnswers)
  436. }
  437. // Answer parses a single Answer Resource.
  438. func (p *Parser) Answer() (Resource, error) {
  439. return p.resource(sectionAnswers)
  440. }
  441. // AllAnswers parses all Answer Resources.
  442. func (p *Parser) AllAnswers() ([]Resource, error) {
  443. as := make([]Resource, 0, p.header.answers)
  444. for {
  445. a, err := p.Answer()
  446. if err == ErrSectionDone {
  447. return as, nil
  448. }
  449. if err != nil {
  450. return nil, err
  451. }
  452. as = append(as, a)
  453. }
  454. }
  455. // SkipAnswer skips a single Answer Resource.
  456. func (p *Parser) SkipAnswer() error {
  457. return p.skipResource(sectionAnswers)
  458. }
  459. // SkipAllAnswers skips all Answer Resources.
  460. func (p *Parser) SkipAllAnswers() error {
  461. for {
  462. if err := p.SkipAnswer(); err == ErrSectionDone {
  463. return nil
  464. } else if err != nil {
  465. return err
  466. }
  467. }
  468. }
  469. // AuthorityHeader parses a single Authority ResourceHeader.
  470. func (p *Parser) AuthorityHeader() (ResourceHeader, error) {
  471. return p.resourceHeader(sectionAuthorities)
  472. }
  473. // Authority parses a single Authority Resource.
  474. func (p *Parser) Authority() (Resource, error) {
  475. return p.resource(sectionAuthorities)
  476. }
  477. // AllAuthorities parses all Authority Resources.
  478. func (p *Parser) AllAuthorities() ([]Resource, error) {
  479. as := make([]Resource, 0, p.header.authorities)
  480. for {
  481. a, err := p.Authority()
  482. if err == ErrSectionDone {
  483. return as, nil
  484. }
  485. if err != nil {
  486. return nil, err
  487. }
  488. as = append(as, a)
  489. }
  490. }
  491. // SkipAuthority skips a single Authority Resource.
  492. func (p *Parser) SkipAuthority() error {
  493. return p.skipResource(sectionAuthorities)
  494. }
  495. // SkipAllAuthorities skips all Authority Resources.
  496. func (p *Parser) SkipAllAuthorities() error {
  497. for {
  498. if err := p.SkipAuthority(); err == ErrSectionDone {
  499. return nil
  500. } else if err != nil {
  501. return err
  502. }
  503. }
  504. }
  505. // AdditionalHeader parses a single Additional ResourceHeader.
  506. func (p *Parser) AdditionalHeader() (ResourceHeader, error) {
  507. return p.resourceHeader(sectionAdditionals)
  508. }
  509. // Additional parses a single Additional Resource.
  510. func (p *Parser) Additional() (Resource, error) {
  511. return p.resource(sectionAdditionals)
  512. }
  513. // AllAdditionals parses all Additional Resources.
  514. func (p *Parser) AllAdditionals() ([]Resource, error) {
  515. as := make([]Resource, 0, p.header.additionals)
  516. for {
  517. a, err := p.Additional()
  518. if err == ErrSectionDone {
  519. return as, nil
  520. }
  521. if err != nil {
  522. return nil, err
  523. }
  524. as = append(as, a)
  525. }
  526. }
  527. // SkipAdditional skips a single Additional Resource.
  528. func (p *Parser) SkipAdditional() error {
  529. return p.skipResource(sectionAdditionals)
  530. }
  531. // SkipAllAdditionals skips all Additional Resources.
  532. func (p *Parser) SkipAllAdditionals() error {
  533. for {
  534. if err := p.SkipAdditional(); err == ErrSectionDone {
  535. return nil
  536. } else if err != nil {
  537. return err
  538. }
  539. }
  540. }
  541. // CNAMEResource parses a single CNAMEResource.
  542. //
  543. // One of the XXXHeader methods must have been called before calling this
  544. // method.
  545. func (p *Parser) CNAMEResource() (CNAMEResource, error) {
  546. if !p.resHeaderValid || p.resHeader.Type != TypeCNAME {
  547. return CNAMEResource{}, ErrNotStarted
  548. }
  549. r, err := unpackCNAMEResource(p.msg, p.off)
  550. if err != nil {
  551. return CNAMEResource{}, err
  552. }
  553. p.off += int(p.resHeader.Length)
  554. p.resHeaderValid = false
  555. p.index++
  556. return r, nil
  557. }
  558. // MXResource parses a single MXResource.
  559. //
  560. // One of the XXXHeader methods must have been called before calling this
  561. // method.
  562. func (p *Parser) MXResource() (MXResource, error) {
  563. if !p.resHeaderValid || p.resHeader.Type != TypeMX {
  564. return MXResource{}, ErrNotStarted
  565. }
  566. r, err := unpackMXResource(p.msg, p.off)
  567. if err != nil {
  568. return MXResource{}, err
  569. }
  570. p.off += int(p.resHeader.Length)
  571. p.resHeaderValid = false
  572. p.index++
  573. return r, nil
  574. }
  575. // NSResource parses a single NSResource.
  576. //
  577. // One of the XXXHeader methods must have been called before calling this
  578. // method.
  579. func (p *Parser) NSResource() (NSResource, error) {
  580. if !p.resHeaderValid || p.resHeader.Type != TypeNS {
  581. return NSResource{}, ErrNotStarted
  582. }
  583. r, err := unpackNSResource(p.msg, p.off)
  584. if err != nil {
  585. return NSResource{}, err
  586. }
  587. p.off += int(p.resHeader.Length)
  588. p.resHeaderValid = false
  589. p.index++
  590. return r, nil
  591. }
  592. // PTRResource parses a single PTRResource.
  593. //
  594. // One of the XXXHeader methods must have been called before calling this
  595. // method.
  596. func (p *Parser) PTRResource() (PTRResource, error) {
  597. if !p.resHeaderValid || p.resHeader.Type != TypePTR {
  598. return PTRResource{}, ErrNotStarted
  599. }
  600. r, err := unpackPTRResource(p.msg, p.off)
  601. if err != nil {
  602. return PTRResource{}, err
  603. }
  604. p.off += int(p.resHeader.Length)
  605. p.resHeaderValid = false
  606. p.index++
  607. return r, nil
  608. }
  609. // SOAResource parses a single SOAResource.
  610. //
  611. // One of the XXXHeader methods must have been called before calling this
  612. // method.
  613. func (p *Parser) SOAResource() (SOAResource, error) {
  614. if !p.resHeaderValid || p.resHeader.Type != TypeSOA {
  615. return SOAResource{}, ErrNotStarted
  616. }
  617. r, err := unpackSOAResource(p.msg, p.off)
  618. if err != nil {
  619. return SOAResource{}, err
  620. }
  621. p.off += int(p.resHeader.Length)
  622. p.resHeaderValid = false
  623. p.index++
  624. return r, nil
  625. }
  626. // TXTResource parses a single TXTResource.
  627. //
  628. // One of the XXXHeader methods must have been called before calling this
  629. // method.
  630. func (p *Parser) TXTResource() (TXTResource, error) {
  631. if !p.resHeaderValid || p.resHeader.Type != TypeTXT {
  632. return TXTResource{}, ErrNotStarted
  633. }
  634. r, err := unpackTXTResource(p.msg, p.off, p.resHeader.Length)
  635. if err != nil {
  636. return TXTResource{}, err
  637. }
  638. p.off += int(p.resHeader.Length)
  639. p.resHeaderValid = false
  640. p.index++
  641. return r, nil
  642. }
  643. // SRVResource parses a single SRVResource.
  644. //
  645. // One of the XXXHeader methods must have been called before calling this
  646. // method.
  647. func (p *Parser) SRVResource() (SRVResource, error) {
  648. if !p.resHeaderValid || p.resHeader.Type != TypeSRV {
  649. return SRVResource{}, ErrNotStarted
  650. }
  651. r, err := unpackSRVResource(p.msg, p.off)
  652. if err != nil {
  653. return SRVResource{}, err
  654. }
  655. p.off += int(p.resHeader.Length)
  656. p.resHeaderValid = false
  657. p.index++
  658. return r, nil
  659. }
  660. // AResource parses a single AResource.
  661. //
  662. // One of the XXXHeader methods must have been called before calling this
  663. // method.
  664. func (p *Parser) AResource() (AResource, error) {
  665. if !p.resHeaderValid || p.resHeader.Type != TypeA {
  666. return AResource{}, ErrNotStarted
  667. }
  668. r, err := unpackAResource(p.msg, p.off)
  669. if err != nil {
  670. return AResource{}, err
  671. }
  672. p.off += int(p.resHeader.Length)
  673. p.resHeaderValid = false
  674. p.index++
  675. return r, nil
  676. }
  677. // AAAAResource parses a single AAAAResource.
  678. //
  679. // One of the XXXHeader methods must have been called before calling this
  680. // method.
  681. func (p *Parser) AAAAResource() (AAAAResource, error) {
  682. if !p.resHeaderValid || p.resHeader.Type != TypeAAAA {
  683. return AAAAResource{}, ErrNotStarted
  684. }
  685. r, err := unpackAAAAResource(p.msg, p.off)
  686. if err != nil {
  687. return AAAAResource{}, err
  688. }
  689. p.off += int(p.resHeader.Length)
  690. p.resHeaderValid = false
  691. p.index++
  692. return r, nil
  693. }
  694. // Unpack parses a full Message.
  695. func (m *Message) Unpack(msg []byte) error {
  696. var p Parser
  697. var err error
  698. if m.Header, err = p.Start(msg); err != nil {
  699. return err
  700. }
  701. if m.Questions, err = p.AllQuestions(); err != nil {
  702. return err
  703. }
  704. if m.Answers, err = p.AllAnswers(); err != nil {
  705. return err
  706. }
  707. if m.Authorities, err = p.AllAuthorities(); err != nil {
  708. return err
  709. }
  710. if m.Additionals, err = p.AllAdditionals(); err != nil {
  711. return err
  712. }
  713. return nil
  714. }
  715. // Pack packs a full Message.
  716. func (m *Message) Pack() ([]byte, error) {
  717. return m.AppendPack(make([]byte, 0, packStartingCap))
  718. }
  719. // AppendPack is like Pack but appends the full Message to b and returns the
  720. // extended buffer.
  721. func (m *Message) AppendPack(b []byte) ([]byte, error) {
  722. // Validate the lengths. It is very unlikely that anyone will try to
  723. // pack more than 65535 of any particular type, but it is possible and
  724. // we should fail gracefully.
  725. if len(m.Questions) > int(^uint16(0)) {
  726. return nil, errTooManyQuestions
  727. }
  728. if len(m.Answers) > int(^uint16(0)) {
  729. return nil, errTooManyAnswers
  730. }
  731. if len(m.Authorities) > int(^uint16(0)) {
  732. return nil, errTooManyAuthorities
  733. }
  734. if len(m.Additionals) > int(^uint16(0)) {
  735. return nil, errTooManyAdditionals
  736. }
  737. var h header
  738. h.id, h.bits = m.Header.pack()
  739. h.questions = uint16(len(m.Questions))
  740. h.answers = uint16(len(m.Answers))
  741. h.authorities = uint16(len(m.Authorities))
  742. h.additionals = uint16(len(m.Additionals))
  743. msg := h.pack(b)
  744. // RFC 1035 allows (but does not require) compression for packing. RFC
  745. // 1035 requires unpacking implementations to support compression, so
  746. // unconditionally enabling it is fine.
  747. //
  748. // DNS lookups are typically done over UDP, and RFC 1035 states that UDP
  749. // DNS packets can be a maximum of 512 bytes long. Without compression,
  750. // many DNS response packets are over this limit, so enabling
  751. // compression will help ensure compliance.
  752. compression := map[string]int{}
  753. for i := range m.Questions {
  754. var err error
  755. if msg, err = m.Questions[i].pack(msg, compression); err != nil {
  756. return nil, &nestedError{"packing Question", err}
  757. }
  758. }
  759. for i := range m.Answers {
  760. var err error
  761. if msg, err = m.Answers[i].pack(msg, compression); err != nil {
  762. return nil, &nestedError{"packing Answer", err}
  763. }
  764. }
  765. for i := range m.Authorities {
  766. var err error
  767. if msg, err = m.Authorities[i].pack(msg, compression); err != nil {
  768. return nil, &nestedError{"packing Authority", err}
  769. }
  770. }
  771. for i := range m.Additionals {
  772. var err error
  773. if msg, err = m.Additionals[i].pack(msg, compression); err != nil {
  774. return nil, &nestedError{"packing Additional", err}
  775. }
  776. }
  777. return msg, nil
  778. }
  779. // A Builder allows incrementally packing a DNS message.
  780. type Builder struct {
  781. msg []byte
  782. header header
  783. section section
  784. compression map[string]int
  785. }
  786. // Start initializes the builder.
  787. //
  788. // buf is optional (nil is fine), but if provided, Start takes ownership of buf.
  789. func (b *Builder) Start(buf []byte, h Header) {
  790. b.StartWithoutCompression(buf, h)
  791. b.compression = map[string]int{}
  792. }
  793. // StartWithoutCompression initializes the builder with compression disabled.
  794. //
  795. // This avoids compression related allocations, but can result in larger message
  796. // sizes. Be careful with this mode as it can cause messages to exceed the UDP
  797. // size limit.
  798. //
  799. // buf is optional (nil is fine), but if provided, Start takes ownership of buf.
  800. func (b *Builder) StartWithoutCompression(buf []byte, h Header) {
  801. *b = Builder{msg: buf}
  802. b.header.id, b.header.bits = h.pack()
  803. if cap(b.msg) < headerLen {
  804. b.msg = make([]byte, 0, packStartingCap)
  805. }
  806. b.msg = b.msg[:headerLen]
  807. b.section = sectionHeader
  808. }
  809. func (b *Builder) startCheck(s section) error {
  810. if b.section <= sectionNotStarted {
  811. return ErrNotStarted
  812. }
  813. if b.section > s {
  814. return ErrSectionDone
  815. }
  816. return nil
  817. }
  818. // StartQuestions prepares the builder for packing Questions.
  819. func (b *Builder) StartQuestions() error {
  820. if err := b.startCheck(sectionQuestions); err != nil {
  821. return err
  822. }
  823. b.section = sectionQuestions
  824. return nil
  825. }
  826. // StartAnswers prepares the builder for packing Answers.
  827. func (b *Builder) StartAnswers() error {
  828. if err := b.startCheck(sectionAnswers); err != nil {
  829. return err
  830. }
  831. b.section = sectionAnswers
  832. return nil
  833. }
  834. // StartAuthorities prepares the builder for packing Authorities.
  835. func (b *Builder) StartAuthorities() error {
  836. if err := b.startCheck(sectionAuthorities); err != nil {
  837. return err
  838. }
  839. b.section = sectionAuthorities
  840. return nil
  841. }
  842. // StartAdditionals prepares the builder for packing Additionals.
  843. func (b *Builder) StartAdditionals() error {
  844. if err := b.startCheck(sectionAdditionals); err != nil {
  845. return err
  846. }
  847. b.section = sectionAdditionals
  848. return nil
  849. }
  850. func (b *Builder) incrementSectionCount() error {
  851. var count *uint16
  852. var err error
  853. switch b.section {
  854. case sectionQuestions:
  855. count = &b.header.questions
  856. err = errTooManyQuestions
  857. case sectionAnswers:
  858. count = &b.header.answers
  859. err = errTooManyAnswers
  860. case sectionAuthorities:
  861. count = &b.header.authorities
  862. err = errTooManyAuthorities
  863. case sectionAdditionals:
  864. count = &b.header.additionals
  865. err = errTooManyAdditionals
  866. }
  867. if *count == ^uint16(0) {
  868. return err
  869. }
  870. *count++
  871. return nil
  872. }
  873. // Question adds a single Question.
  874. func (b *Builder) Question(q Question) error {
  875. if b.section < sectionQuestions {
  876. return ErrNotStarted
  877. }
  878. if b.section > sectionQuestions {
  879. return ErrSectionDone
  880. }
  881. msg, err := q.pack(b.msg, b.compression)
  882. if err != nil {
  883. return err
  884. }
  885. if err := b.incrementSectionCount(); err != nil {
  886. return err
  887. }
  888. b.msg = msg
  889. return nil
  890. }
  891. func (b *Builder) checkResourceSection() error {
  892. if b.section < sectionAnswers {
  893. return ErrNotStarted
  894. }
  895. if b.section > sectionAdditionals {
  896. return ErrSectionDone
  897. }
  898. return nil
  899. }
  900. // CNAMEResource adds a single CNAMEResource.
  901. func (b *Builder) CNAMEResource(h ResourceHeader, r CNAMEResource) error {
  902. if err := b.checkResourceSection(); err != nil {
  903. return err
  904. }
  905. h.Type = r.realType()
  906. msg, length, err := h.pack(b.msg, b.compression)
  907. if err != nil {
  908. return &nestedError{"ResourceHeader", err}
  909. }
  910. preLen := len(msg)
  911. if msg, err = r.pack(msg, b.compression); err != nil {
  912. return &nestedError{"CNAMEResource body", err}
  913. }
  914. if err := h.fixLen(msg, length, preLen); err != nil {
  915. return err
  916. }
  917. if err := b.incrementSectionCount(); err != nil {
  918. return err
  919. }
  920. b.msg = msg
  921. return nil
  922. }
  923. // MXResource adds a single MXResource.
  924. func (b *Builder) MXResource(h ResourceHeader, r MXResource) error {
  925. if err := b.checkResourceSection(); err != nil {
  926. return err
  927. }
  928. h.Type = r.realType()
  929. msg, length, err := h.pack(b.msg, b.compression)
  930. if err != nil {
  931. return &nestedError{"ResourceHeader", err}
  932. }
  933. preLen := len(msg)
  934. if msg, err = r.pack(msg, b.compression); err != nil {
  935. return &nestedError{"MXResource body", err}
  936. }
  937. if err := h.fixLen(msg, length, preLen); err != nil {
  938. return err
  939. }
  940. if err := b.incrementSectionCount(); err != nil {
  941. return err
  942. }
  943. b.msg = msg
  944. return nil
  945. }
  946. // NSResource adds a single NSResource.
  947. func (b *Builder) NSResource(h ResourceHeader, r NSResource) error {
  948. if err := b.checkResourceSection(); err != nil {
  949. return err
  950. }
  951. h.Type = r.realType()
  952. msg, length, err := h.pack(b.msg, b.compression)
  953. if err != nil {
  954. return &nestedError{"ResourceHeader", err}
  955. }
  956. preLen := len(msg)
  957. if msg, err = r.pack(msg, b.compression); err != nil {
  958. return &nestedError{"NSResource body", err}
  959. }
  960. if err := h.fixLen(msg, length, preLen); err != nil {
  961. return err
  962. }
  963. if err := b.incrementSectionCount(); err != nil {
  964. return err
  965. }
  966. b.msg = msg
  967. return nil
  968. }
  969. // PTRResource adds a single PTRResource.
  970. func (b *Builder) PTRResource(h ResourceHeader, r PTRResource) error {
  971. if err := b.checkResourceSection(); err != nil {
  972. return err
  973. }
  974. h.Type = r.realType()
  975. msg, length, err := h.pack(b.msg, b.compression)
  976. if err != nil {
  977. return &nestedError{"ResourceHeader", err}
  978. }
  979. preLen := len(msg)
  980. if msg, err = r.pack(msg, b.compression); err != nil {
  981. return &nestedError{"PTRResource body", err}
  982. }
  983. if err := h.fixLen(msg, length, preLen); err != nil {
  984. return err
  985. }
  986. if err := b.incrementSectionCount(); err != nil {
  987. return err
  988. }
  989. b.msg = msg
  990. return nil
  991. }
  992. // SOAResource adds a single SOAResource.
  993. func (b *Builder) SOAResource(h ResourceHeader, r SOAResource) error {
  994. if err := b.checkResourceSection(); err != nil {
  995. return err
  996. }
  997. h.Type = r.realType()
  998. msg, length, err := h.pack(b.msg, b.compression)
  999. if err != nil {
  1000. return &nestedError{"ResourceHeader", err}
  1001. }
  1002. preLen := len(msg)
  1003. if msg, err = r.pack(msg, b.compression); err != nil {
  1004. return &nestedError{"SOAResource body", err}
  1005. }
  1006. if err := h.fixLen(msg, length, preLen); err != nil {
  1007. return err
  1008. }
  1009. if err := b.incrementSectionCount(); err != nil {
  1010. return err
  1011. }
  1012. b.msg = msg
  1013. return nil
  1014. }
  1015. // TXTResource adds a single TXTResource.
  1016. func (b *Builder) TXTResource(h ResourceHeader, r TXTResource) error {
  1017. if err := b.checkResourceSection(); err != nil {
  1018. return err
  1019. }
  1020. h.Type = r.realType()
  1021. msg, length, err := h.pack(b.msg, b.compression)
  1022. if err != nil {
  1023. return &nestedError{"ResourceHeader", err}
  1024. }
  1025. preLen := len(msg)
  1026. if msg, err = r.pack(msg, b.compression); err != nil {
  1027. return &nestedError{"TXTResource body", err}
  1028. }
  1029. if err := h.fixLen(msg, length, preLen); err != nil {
  1030. return err
  1031. }
  1032. if err := b.incrementSectionCount(); err != nil {
  1033. return err
  1034. }
  1035. b.msg = msg
  1036. return nil
  1037. }
  1038. // SRVResource adds a single SRVResource.
  1039. func (b *Builder) SRVResource(h ResourceHeader, r SRVResource) error {
  1040. if err := b.checkResourceSection(); err != nil {
  1041. return err
  1042. }
  1043. h.Type = r.realType()
  1044. msg, length, err := h.pack(b.msg, b.compression)
  1045. if err != nil {
  1046. return &nestedError{"ResourceHeader", err}
  1047. }
  1048. preLen := len(msg)
  1049. if msg, err = r.pack(msg, b.compression); err != nil {
  1050. return &nestedError{"SRVResource body", err}
  1051. }
  1052. if err := h.fixLen(msg, length, preLen); err != nil {
  1053. return err
  1054. }
  1055. if err := b.incrementSectionCount(); err != nil {
  1056. return err
  1057. }
  1058. b.msg = msg
  1059. return nil
  1060. }
  1061. // AResource adds a single AResource.
  1062. func (b *Builder) AResource(h ResourceHeader, r AResource) error {
  1063. if err := b.checkResourceSection(); err != nil {
  1064. return err
  1065. }
  1066. h.Type = r.realType()
  1067. msg, length, err := h.pack(b.msg, b.compression)
  1068. if err != nil {
  1069. return &nestedError{"ResourceHeader", err}
  1070. }
  1071. preLen := len(msg)
  1072. if msg, err = r.pack(msg, b.compression); err != nil {
  1073. return &nestedError{"AResource body", err}
  1074. }
  1075. if err := h.fixLen(msg, length, preLen); err != nil {
  1076. return err
  1077. }
  1078. if err := b.incrementSectionCount(); err != nil {
  1079. return err
  1080. }
  1081. b.msg = msg
  1082. return nil
  1083. }
  1084. // AAAAResource adds a single AAAAResource.
  1085. func (b *Builder) AAAAResource(h ResourceHeader, r AAAAResource) error {
  1086. if err := b.checkResourceSection(); err != nil {
  1087. return err
  1088. }
  1089. h.Type = r.realType()
  1090. msg, length, err := h.pack(b.msg, b.compression)
  1091. if err != nil {
  1092. return &nestedError{"ResourceHeader", err}
  1093. }
  1094. preLen := len(msg)
  1095. if msg, err = r.pack(msg, b.compression); err != nil {
  1096. return &nestedError{"AAAAResource body", err}
  1097. }
  1098. if err := h.fixLen(msg, length, preLen); err != nil {
  1099. return err
  1100. }
  1101. if err := b.incrementSectionCount(); err != nil {
  1102. return err
  1103. }
  1104. b.msg = msg
  1105. return nil
  1106. }
  1107. // Finish ends message building and generates a binary packet.
  1108. func (b *Builder) Finish() ([]byte, error) {
  1109. if b.section < sectionHeader {
  1110. return nil, ErrNotStarted
  1111. }
  1112. b.section = sectionDone
  1113. b.header.pack(b.msg[:0])
  1114. return b.msg, nil
  1115. }
  1116. // A ResourceHeader is the header of a DNS resource record. There are
  1117. // many types of DNS resource records, but they all share the same header.
  1118. type ResourceHeader struct {
  1119. // Name is the domain name for which this resource record pertains.
  1120. Name Name
  1121. // Type is the type of DNS resource record.
  1122. //
  1123. // This field will be set automatically during packing.
  1124. Type Type
  1125. // Class is the class of network to which this DNS resource record
  1126. // pertains.
  1127. Class Class
  1128. // TTL is the length of time (measured in seconds) which this resource
  1129. // record is valid for (time to live). All Resources in a set should
  1130. // have the same TTL (RFC 2181 Section 5.2).
  1131. TTL uint32
  1132. // Length is the length of data in the resource record after the header.
  1133. //
  1134. // This field will be set automatically during packing.
  1135. Length uint16
  1136. }
  1137. // pack packs all of the fields in a ResourceHeader except for the length. The
  1138. // length bytes are returned as a slice so they can be filled in after the rest
  1139. // of the Resource has been packed.
  1140. func (h *ResourceHeader) pack(oldMsg []byte, compression map[string]int) (msg []byte, length []byte, err error) {
  1141. msg = oldMsg
  1142. if msg, err = h.Name.pack(msg, compression); err != nil {
  1143. return oldMsg, nil, &nestedError{"Name", err}
  1144. }
  1145. msg = packType(msg, h.Type)
  1146. msg = packClass(msg, h.Class)
  1147. msg = packUint32(msg, h.TTL)
  1148. lenBegin := len(msg)
  1149. msg = packUint16(msg, h.Length)
  1150. return msg, msg[lenBegin : lenBegin+uint16Len], nil
  1151. }
  1152. func (h *ResourceHeader) unpack(msg []byte, off int) (int, error) {
  1153. newOff := off
  1154. var err error
  1155. if newOff, err = h.Name.unpack(msg, newOff); err != nil {
  1156. return off, &nestedError{"Name", err}
  1157. }
  1158. if h.Type, newOff, err = unpackType(msg, newOff); err != nil {
  1159. return off, &nestedError{"Type", err}
  1160. }
  1161. if h.Class, newOff, err = unpackClass(msg, newOff); err != nil {
  1162. return off, &nestedError{"Class", err}
  1163. }
  1164. if h.TTL, newOff, err = unpackUint32(msg, newOff); err != nil {
  1165. return off, &nestedError{"TTL", err}
  1166. }
  1167. if h.Length, newOff, err = unpackUint16(msg, newOff); err != nil {
  1168. return off, &nestedError{"Length", err}
  1169. }
  1170. return newOff, nil
  1171. }
  1172. func (h *ResourceHeader) fixLen(msg []byte, length []byte, preLen int) error {
  1173. conLen := len(msg) - preLen
  1174. if conLen > int(^uint16(0)) {
  1175. return errResTooLong
  1176. }
  1177. // Fill in the length now that we know how long the content is.
  1178. packUint16(length[:0], uint16(conLen))
  1179. h.Length = uint16(conLen)
  1180. return nil
  1181. }
  1182. func skipResource(msg []byte, off int) (int, error) {
  1183. newOff, err := skipName(msg, off)
  1184. if err != nil {
  1185. return off, &nestedError{"Name", err}
  1186. }
  1187. if newOff, err = skipType(msg, newOff); err != nil {
  1188. return off, &nestedError{"Type", err}
  1189. }
  1190. if newOff, err = skipClass(msg, newOff); err != nil {
  1191. return off, &nestedError{"Class", err}
  1192. }
  1193. if newOff, err = skipUint32(msg, newOff); err != nil {
  1194. return off, &nestedError{"TTL", err}
  1195. }
  1196. length, newOff, err := unpackUint16(msg, newOff)
  1197. if err != nil {
  1198. return off, &nestedError{"Length", err}
  1199. }
  1200. if newOff += int(length); newOff > len(msg) {
  1201. return off, errResourceLen
  1202. }
  1203. return newOff, nil
  1204. }
  1205. func packUint16(msg []byte, field uint16) []byte {
  1206. return append(msg, byte(field>>8), byte(field))
  1207. }
  1208. func unpackUint16(msg []byte, off int) (uint16, int, error) {
  1209. if off+uint16Len > len(msg) {
  1210. return 0, off, errBaseLen
  1211. }
  1212. return uint16(msg[off])<<8 | uint16(msg[off+1]), off + uint16Len, nil
  1213. }
  1214. func skipUint16(msg []byte, off int) (int, error) {
  1215. if off+uint16Len > len(msg) {
  1216. return off, errBaseLen
  1217. }
  1218. return off + uint16Len, nil
  1219. }
  1220. func packType(msg []byte, field Type) []byte {
  1221. return packUint16(msg, uint16(field))
  1222. }
  1223. func unpackType(msg []byte, off int) (Type, int, error) {
  1224. t, o, err := unpackUint16(msg, off)
  1225. return Type(t), o, err
  1226. }
  1227. func skipType(msg []byte, off int) (int, error) {
  1228. return skipUint16(msg, off)
  1229. }
  1230. func packClass(msg []byte, field Class) []byte {
  1231. return packUint16(msg, uint16(field))
  1232. }
  1233. func unpackClass(msg []byte, off int) (Class, int, error) {
  1234. c, o, err := unpackUint16(msg, off)
  1235. return Class(c), o, err
  1236. }
  1237. func skipClass(msg []byte, off int) (int, error) {
  1238. return skipUint16(msg, off)
  1239. }
  1240. func packUint32(msg []byte, field uint32) []byte {
  1241. return append(
  1242. msg,
  1243. byte(field>>24),
  1244. byte(field>>16),
  1245. byte(field>>8),
  1246. byte(field),
  1247. )
  1248. }
  1249. func unpackUint32(msg []byte, off int) (uint32, int, error) {
  1250. if off+uint32Len > len(msg) {
  1251. return 0, off, errBaseLen
  1252. }
  1253. v := uint32(msg[off])<<24 | uint32(msg[off+1])<<16 | uint32(msg[off+2])<<8 | uint32(msg[off+3])
  1254. return v, off + uint32Len, nil
  1255. }
  1256. func skipUint32(msg []byte, off int) (int, error) {
  1257. if off+uint32Len > len(msg) {
  1258. return off, errBaseLen
  1259. }
  1260. return off + uint32Len, nil
  1261. }
  1262. func packText(msg []byte, field string) []byte {
  1263. for len(field) > 0 {
  1264. l := len(field)
  1265. if l > 255 {
  1266. l = 255
  1267. }
  1268. msg = append(msg, byte(l))
  1269. msg = append(msg, field[:l]...)
  1270. field = field[l:]
  1271. }
  1272. return msg
  1273. }
  1274. func unpackText(msg []byte, off int) (string, int, error) {
  1275. if off >= len(msg) {
  1276. return "", off, errBaseLen
  1277. }
  1278. beginOff := off + 1
  1279. endOff := beginOff + int(msg[off])
  1280. if endOff > len(msg) {
  1281. return "", off, errCalcLen
  1282. }
  1283. return string(msg[beginOff:endOff]), endOff, nil
  1284. }
  1285. func skipText(msg []byte, off int) (int, error) {
  1286. if off >= len(msg) {
  1287. return off, errBaseLen
  1288. }
  1289. endOff := off + 1 + int(msg[off])
  1290. if endOff > len(msg) {
  1291. return off, errCalcLen
  1292. }
  1293. return endOff, nil
  1294. }
  1295. func packBytes(msg []byte, field []byte) []byte {
  1296. return append(msg, field...)
  1297. }
  1298. func unpackBytes(msg []byte, off int, field []byte) (int, error) {
  1299. newOff := off + len(field)
  1300. if newOff > len(msg) {
  1301. return off, errBaseLen
  1302. }
  1303. copy(field, msg[off:newOff])
  1304. return newOff, nil
  1305. }
  1306. func skipBytes(msg []byte, off int, field []byte) (int, error) {
  1307. newOff := off + len(field)
  1308. if newOff > len(msg) {
  1309. return off, errBaseLen
  1310. }
  1311. return newOff, nil
  1312. }
  1313. const nameLen = 255
  1314. // A Name is a non-encoded domain name. It is used instead of strings to avoid
  1315. // allocations.
  1316. type Name struct {
  1317. Data [nameLen]byte
  1318. Length uint8
  1319. }
  1320. // NewName creates a new Name from a string.
  1321. func NewName(name string) (Name, error) {
  1322. if len([]byte(name)) > nameLen {
  1323. return Name{}, errCalcLen
  1324. }
  1325. n := Name{Length: uint8(len(name))}
  1326. copy(n.Data[:], []byte(name))
  1327. return n, nil
  1328. }
  1329. func (n Name) String() string {
  1330. return string(n.Data[:n.Length])
  1331. }
  1332. // pack packs a domain name.
  1333. //
  1334. // Domain names are a sequence of counted strings split at the dots. They end
  1335. // with a zero-length string. Compression can be used to reuse domain suffixes.
  1336. //
  1337. // The compression map will be updated with new domain suffixes. If compression
  1338. // is nil, compression will not be used.
  1339. func (n *Name) pack(msg []byte, compression map[string]int) ([]byte, error) {
  1340. oldMsg := msg
  1341. // Add a trailing dot to canonicalize name.
  1342. if n.Length == 0 || n.Data[n.Length-1] != '.' {
  1343. return oldMsg, errNonCanonicalName
  1344. }
  1345. // Allow root domain.
  1346. if n.Data[0] == '.' && n.Length == 1 {
  1347. return append(msg, 0), nil
  1348. }
  1349. // Emit sequence of counted strings, chopping at dots.
  1350. for i, begin := 0, 0; i < int(n.Length); i++ {
  1351. // Check for the end of the segment.
  1352. if n.Data[i] == '.' {
  1353. // The two most significant bits have special meaning.
  1354. // It isn't allowed for segments to be long enough to
  1355. // need them.
  1356. if i-begin >= 1<<6 {
  1357. return oldMsg, errSegTooLong
  1358. }
  1359. // Segments must have a non-zero length.
  1360. if i-begin == 0 {
  1361. return oldMsg, errZeroSegLen
  1362. }
  1363. msg = append(msg, byte(i-begin))
  1364. for j := begin; j < i; j++ {
  1365. msg = append(msg, n.Data[j])
  1366. }
  1367. begin = i + 1
  1368. continue
  1369. }
  1370. // We can only compress domain suffixes starting with a new
  1371. // segment. A pointer is two bytes with the two most significant
  1372. // bits set to 1 to indicate that it is a pointer.
  1373. if (i == 0 || n.Data[i-1] == '.') && compression != nil {
  1374. if ptr, ok := compression[string(n.Data[i:])]; ok {
  1375. // Hit. Emit a pointer instead of the rest of
  1376. // the domain.
  1377. return append(msg, byte(ptr>>8|0xC0), byte(ptr)), nil
  1378. }
  1379. // Miss. Add the suffix to the compression table if the
  1380. // offset can be stored in the available 14 bytes.
  1381. if len(msg) <= int(^uint16(0)>>2) {
  1382. compression[string(n.Data[i:])] = len(msg)
  1383. }
  1384. }
  1385. }
  1386. return append(msg, 0), nil
  1387. }
  1388. // unpack unpacks a domain name.
  1389. func (n *Name) unpack(msg []byte, off int) (int, error) {
  1390. // currOff is the current working offset.
  1391. currOff := off
  1392. // newOff is the offset where the next record will start. Pointers lead
  1393. // to data that belongs to other names and thus doesn't count towards to
  1394. // the usage of this name.
  1395. newOff := off
  1396. // ptr is the number of pointers followed.
  1397. var ptr int
  1398. // Name is a slice representation of the name data.
  1399. name := n.Data[:0]
  1400. Loop:
  1401. for {
  1402. if currOff >= len(msg) {
  1403. return off, errBaseLen
  1404. }
  1405. c := int(msg[currOff])
  1406. currOff++
  1407. switch c & 0xC0 {
  1408. case 0x00: // String segment
  1409. if c == 0x00 {
  1410. // A zero length signals the end of the name.
  1411. break Loop
  1412. }
  1413. endOff := currOff + c
  1414. if endOff > len(msg) {
  1415. return off, errCalcLen
  1416. }
  1417. name = append(name, msg[currOff:endOff]...)
  1418. name = append(name, '.')
  1419. currOff = endOff
  1420. case 0xC0: // Pointer
  1421. if currOff >= len(msg) {
  1422. return off, errInvalidPtr
  1423. }
  1424. c1 := msg[currOff]
  1425. currOff++
  1426. if ptr == 0 {
  1427. newOff = currOff
  1428. }
  1429. // Don't follow too many pointers, maybe there's a loop.
  1430. if ptr++; ptr > 10 {
  1431. return off, errTooManyPtr
  1432. }
  1433. currOff = (c^0xC0)<<8 | int(c1)
  1434. default:
  1435. // Prefixes 0x80 and 0x40 are reserved.
  1436. return off, errReserved
  1437. }
  1438. }
  1439. if len(name) == 0 {
  1440. name = append(name, '.')
  1441. }
  1442. if len(name) > len(n.Data) {
  1443. return off, errCalcLen
  1444. }
  1445. n.Length = uint8(len(name))
  1446. if ptr == 0 {
  1447. newOff = currOff
  1448. }
  1449. return newOff, nil
  1450. }
  1451. func skipName(msg []byte, off int) (int, error) {
  1452. // newOff is the offset where the next record will start. Pointers lead
  1453. // to data that belongs to other names and thus doesn't count towards to
  1454. // the usage of this name.
  1455. newOff := off
  1456. Loop:
  1457. for {
  1458. if newOff >= len(msg) {
  1459. return off, errBaseLen
  1460. }
  1461. c := int(msg[newOff])
  1462. newOff++
  1463. switch c & 0xC0 {
  1464. case 0x00:
  1465. if c == 0x00 {
  1466. // A zero length signals the end of the name.
  1467. break Loop
  1468. }
  1469. // literal string
  1470. newOff += c
  1471. if newOff > len(msg) {
  1472. return off, errCalcLen
  1473. }
  1474. case 0xC0:
  1475. // Pointer to somewhere else in msg.
  1476. // Pointers are two bytes.
  1477. newOff++
  1478. // Don't follow the pointer as the data here has ended.
  1479. break Loop
  1480. default:
  1481. // Prefixes 0x80 and 0x40 are reserved.
  1482. return off, errReserved
  1483. }
  1484. }
  1485. return newOff, nil
  1486. }
  1487. // A Question is a DNS query.
  1488. type Question struct {
  1489. Name Name
  1490. Type Type
  1491. Class Class
  1492. }
  1493. func (q *Question) pack(msg []byte, compression map[string]int) ([]byte, error) {
  1494. msg, err := q.Name.pack(msg, compression)
  1495. if err != nil {
  1496. return msg, &nestedError{"Name", err}
  1497. }
  1498. msg = packType(msg, q.Type)
  1499. return packClass(msg, q.Class), nil
  1500. }
  1501. func unpackResourceBody(msg []byte, off int, hdr ResourceHeader) (ResourceBody, int, error) {
  1502. var (
  1503. r ResourceBody
  1504. err error
  1505. name string
  1506. )
  1507. switch hdr.Type {
  1508. case TypeA:
  1509. var rb AResource
  1510. rb, err = unpackAResource(msg, off)
  1511. r = &rb
  1512. name = "A"
  1513. case TypeNS:
  1514. var rb NSResource
  1515. rb, err = unpackNSResource(msg, off)
  1516. r = &rb
  1517. name = "NS"
  1518. case TypeCNAME:
  1519. var rb CNAMEResource
  1520. rb, err = unpackCNAMEResource(msg, off)
  1521. r = &rb
  1522. name = "CNAME"
  1523. case TypeSOA:
  1524. var rb SOAResource
  1525. rb, err = unpackSOAResource(msg, off)
  1526. r = &rb
  1527. name = "SOA"
  1528. case TypePTR:
  1529. var rb PTRResource
  1530. rb, err = unpackPTRResource(msg, off)
  1531. r = &rb
  1532. name = "PTR"
  1533. case TypeMX:
  1534. var rb MXResource
  1535. rb, err = unpackMXResource(msg, off)
  1536. r = &rb
  1537. name = "MX"
  1538. case TypeTXT:
  1539. var rb TXTResource
  1540. rb, err = unpackTXTResource(msg, off, hdr.Length)
  1541. r = &rb
  1542. name = "TXT"
  1543. case TypeAAAA:
  1544. var rb AAAAResource
  1545. rb, err = unpackAAAAResource(msg, off)
  1546. r = &rb
  1547. name = "AAAA"
  1548. case TypeSRV:
  1549. var rb SRVResource
  1550. rb, err = unpackSRVResource(msg, off)
  1551. r = &rb
  1552. name = "SRV"
  1553. }
  1554. if err != nil {
  1555. return nil, off, &nestedError{name + " record", err}
  1556. }
  1557. if r == nil {
  1558. return nil, off, errors.New("invalid resource type: " + string(hdr.Type+'0'))
  1559. }
  1560. return r, off + int(hdr.Length), nil
  1561. }
  1562. // A CNAMEResource is a CNAME Resource record.
  1563. type CNAMEResource struct {
  1564. CNAME Name
  1565. }
  1566. func (r *CNAMEResource) realType() Type {
  1567. return TypeCNAME
  1568. }
  1569. func (r *CNAMEResource) pack(msg []byte, compression map[string]int) ([]byte, error) {
  1570. return r.CNAME.pack(msg, compression)
  1571. }
  1572. func unpackCNAMEResource(msg []byte, off int) (CNAMEResource, error) {
  1573. var cname Name
  1574. if _, err := cname.unpack(msg, off); err != nil {
  1575. return CNAMEResource{}, err
  1576. }
  1577. return CNAMEResource{cname}, nil
  1578. }
  1579. // An MXResource is an MX Resource record.
  1580. type MXResource struct {
  1581. Pref uint16
  1582. MX Name
  1583. }
  1584. func (r *MXResource) realType() Type {
  1585. return TypeMX
  1586. }
  1587. func (r *MXResource) pack(msg []byte, compression map[string]int) ([]byte, error) {
  1588. oldMsg := msg
  1589. msg = packUint16(msg, r.Pref)
  1590. msg, err := r.MX.pack(msg, compression)
  1591. if err != nil {
  1592. return oldMsg, &nestedError{"MXResource.MX", err}
  1593. }
  1594. return msg, nil
  1595. }
  1596. func unpackMXResource(msg []byte, off int) (MXResource, error) {
  1597. pref, off, err := unpackUint16(msg, off)
  1598. if err != nil {
  1599. return MXResource{}, &nestedError{"Pref", err}
  1600. }
  1601. var mx Name
  1602. if _, err := mx.unpack(msg, off); err != nil {
  1603. return MXResource{}, &nestedError{"MX", err}
  1604. }
  1605. return MXResource{pref, mx}, nil
  1606. }
  1607. // An NSResource is an NS Resource record.
  1608. type NSResource struct {
  1609. NS Name
  1610. }
  1611. func (r *NSResource) realType() Type {
  1612. return TypeNS
  1613. }
  1614. func (r *NSResource) pack(msg []byte, compression map[string]int) ([]byte, error) {
  1615. return r.NS.pack(msg, compression)
  1616. }
  1617. func unpackNSResource(msg []byte, off int) (NSResource, error) {
  1618. var ns Name
  1619. if _, err := ns.unpack(msg, off); err != nil {
  1620. return NSResource{}, err
  1621. }
  1622. return NSResource{ns}, nil
  1623. }
  1624. // A PTRResource is a PTR Resource record.
  1625. type PTRResource struct {
  1626. PTR Name
  1627. }
  1628. func (r *PTRResource) realType() Type {
  1629. return TypePTR
  1630. }
  1631. func (r *PTRResource) pack(msg []byte, compression map[string]int) ([]byte, error) {
  1632. return r.PTR.pack(msg, compression)
  1633. }
  1634. func unpackPTRResource(msg []byte, off int) (PTRResource, error) {
  1635. var ptr Name
  1636. if _, err := ptr.unpack(msg, off); err != nil {
  1637. return PTRResource{}, err
  1638. }
  1639. return PTRResource{ptr}, nil
  1640. }
  1641. // An SOAResource is an SOA Resource record.
  1642. type SOAResource struct {
  1643. NS Name
  1644. MBox Name
  1645. Serial uint32
  1646. Refresh uint32
  1647. Retry uint32
  1648. Expire uint32
  1649. // MinTTL the is the default TTL of Resources records which did not
  1650. // contain a TTL value and the TTL of negative responses. (RFC 2308
  1651. // Section 4)
  1652. MinTTL uint32
  1653. }
  1654. func (r *SOAResource) realType() Type {
  1655. return TypeSOA
  1656. }
  1657. func (r *SOAResource) pack(msg []byte, compression map[string]int) ([]byte, error) {
  1658. oldMsg := msg
  1659. msg, err := r.NS.pack(msg, compression)
  1660. if err != nil {
  1661. return oldMsg, &nestedError{"SOAResource.NS", err}
  1662. }
  1663. msg, err = r.MBox.pack(msg, compression)
  1664. if err != nil {
  1665. return oldMsg, &nestedError{"SOAResource.MBox", err}
  1666. }
  1667. msg = packUint32(msg, r.Serial)
  1668. msg = packUint32(msg, r.Refresh)
  1669. msg = packUint32(msg, r.Retry)
  1670. msg = packUint32(msg, r.Expire)
  1671. return packUint32(msg, r.MinTTL), nil
  1672. }
  1673. func unpackSOAResource(msg []byte, off int) (SOAResource, error) {
  1674. var ns Name
  1675. off, err := ns.unpack(msg, off)
  1676. if err != nil {
  1677. return SOAResource{}, &nestedError{"NS", err}
  1678. }
  1679. var mbox Name
  1680. if off, err = mbox.unpack(msg, off); err != nil {
  1681. return SOAResource{}, &nestedError{"MBox", err}
  1682. }
  1683. serial, off, err := unpackUint32(msg, off)
  1684. if err != nil {
  1685. return SOAResource{}, &nestedError{"Serial", err}
  1686. }
  1687. refresh, off, err := unpackUint32(msg, off)
  1688. if err != nil {
  1689. return SOAResource{}, &nestedError{"Refresh", err}
  1690. }
  1691. retry, off, err := unpackUint32(msg, off)
  1692. if err != nil {
  1693. return SOAResource{}, &nestedError{"Retry", err}
  1694. }
  1695. expire, off, err := unpackUint32(msg, off)
  1696. if err != nil {
  1697. return SOAResource{}, &nestedError{"Expire", err}
  1698. }
  1699. minTTL, _, err := unpackUint32(msg, off)
  1700. if err != nil {
  1701. return SOAResource{}, &nestedError{"MinTTL", err}
  1702. }
  1703. return SOAResource{ns, mbox, serial, refresh, retry, expire, minTTL}, nil
  1704. }
  1705. // A TXTResource is a TXT Resource record.
  1706. type TXTResource struct {
  1707. Txt string // Not a domain name.
  1708. }
  1709. func (r *TXTResource) realType() Type {
  1710. return TypeTXT
  1711. }
  1712. func (r *TXTResource) pack(msg []byte, compression map[string]int) ([]byte, error) {
  1713. return packText(msg, r.Txt), nil
  1714. }
  1715. func unpackTXTResource(msg []byte, off int, length uint16) (TXTResource, error) {
  1716. var txt string
  1717. for n := uint16(0); n < length; {
  1718. var t string
  1719. var err error
  1720. if t, off, err = unpackText(msg, off); err != nil {
  1721. return TXTResource{}, &nestedError{"text", err}
  1722. }
  1723. // Check if we got too many bytes.
  1724. if length-n < uint16(len(t))+1 {
  1725. return TXTResource{}, errCalcLen
  1726. }
  1727. n += uint16(len(t)) + 1
  1728. txt += t
  1729. }
  1730. return TXTResource{txt}, nil
  1731. }
  1732. // An SRVResource is an SRV Resource record.
  1733. type SRVResource struct {
  1734. Priority uint16
  1735. Weight uint16
  1736. Port uint16
  1737. Target Name // Not compressed as per RFC 2782.
  1738. }
  1739. func (r *SRVResource) realType() Type {
  1740. return TypeSRV
  1741. }
  1742. func (r *SRVResource) pack(msg []byte, compression map[string]int) ([]byte, error) {
  1743. oldMsg := msg
  1744. msg = packUint16(msg, r.Priority)
  1745. msg = packUint16(msg, r.Weight)
  1746. msg = packUint16(msg, r.Port)
  1747. msg, err := r.Target.pack(msg, nil)
  1748. if err != nil {
  1749. return oldMsg, &nestedError{"SRVResource.Target", err}
  1750. }
  1751. return msg, nil
  1752. }
  1753. func unpackSRVResource(msg []byte, off int) (SRVResource, error) {
  1754. priority, off, err := unpackUint16(msg, off)
  1755. if err != nil {
  1756. return SRVResource{}, &nestedError{"Priority", err}
  1757. }
  1758. weight, off, err := unpackUint16(msg, off)
  1759. if err != nil {
  1760. return SRVResource{}, &nestedError{"Weight", err}
  1761. }
  1762. port, off, err := unpackUint16(msg, off)
  1763. if err != nil {
  1764. return SRVResource{}, &nestedError{"Port", err}
  1765. }
  1766. var target Name
  1767. if _, err := target.unpack(msg, off); err != nil {
  1768. return SRVResource{}, &nestedError{"Target", err}
  1769. }
  1770. return SRVResource{priority, weight, port, target}, nil
  1771. }
  1772. // An AResource is an A Resource record.
  1773. type AResource struct {
  1774. A [4]byte
  1775. }
  1776. func (r *AResource) realType() Type {
  1777. return TypeA
  1778. }
  1779. func (r *AResource) pack(msg []byte, compression map[string]int) ([]byte, error) {
  1780. return packBytes(msg, r.A[:]), nil
  1781. }
  1782. func unpackAResource(msg []byte, off int) (AResource, error) {
  1783. var a [4]byte
  1784. if _, err := unpackBytes(msg, off, a[:]); err != nil {
  1785. return AResource{}, err
  1786. }
  1787. return AResource{a}, nil
  1788. }
  1789. // An AAAAResource is an AAAA Resource record.
  1790. type AAAAResource struct {
  1791. AAAA [16]byte
  1792. }
  1793. func (r *AAAAResource) realType() Type {
  1794. return TypeAAAA
  1795. }
  1796. func (r *AAAAResource) pack(msg []byte, compression map[string]int) ([]byte, error) {
  1797. return packBytes(msg, r.AAAA[:]), nil
  1798. }
  1799. func unpackAAAAResource(msg []byte, off int) (AAAAResource, error) {
  1800. var aaaa [16]byte
  1801. if _, err := unpackBytes(msg, off, aaaa[:]); err != nil {
  1802. return AAAAResource{}, err
  1803. }
  1804. return AAAAResource{aaaa}, nil
  1805. }