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.
 
 
 

1419 lines
35 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 or skipped.
  59. ErrNotStarted = errors.New("parsing of this type isn't available yet")
  60. // ErrSectionDone indicated that all records in the section have been
  61. // parsed.
  62. ErrSectionDone = errors.New("parsing 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. errResourceLen = errors.New("insufficient data for resource body length")
  69. errSegTooLong = errors.New("segment length too long")
  70. errZeroSegLen = errors.New("zero length segment")
  71. errResTooLong = errors.New("resource length too long")
  72. errTooManyQuestions = errors.New("too many Questions to pack (>65535)")
  73. errTooManyAnswers = errors.New("too many Answers to pack (>65535)")
  74. errTooManyAuthorities = errors.New("too many Authorities to pack (>65535)")
  75. errTooManyAdditionals = errors.New("too many Additionals to pack (>65535)")
  76. )
  77. type nestedError struct {
  78. // s is the current level's error message.
  79. s string
  80. // err is the nested error.
  81. err error
  82. }
  83. // nestedError implements error.Error.
  84. func (e *nestedError) Error() string {
  85. return e.s + ": " + e.err.Error()
  86. }
  87. // Header is a representation of a DNS message header.
  88. type Header struct {
  89. ID uint16
  90. Response bool
  91. OpCode OpCode
  92. Authoritative bool
  93. Truncated bool
  94. RecursionDesired bool
  95. RecursionAvailable bool
  96. RCode RCode
  97. }
  98. func (m *Header) pack() (id uint16, bits uint16) {
  99. id = m.ID
  100. bits = uint16(m.OpCode)<<11 | uint16(m.RCode)
  101. if m.RecursionAvailable {
  102. bits |= headerBitRA
  103. }
  104. if m.RecursionDesired {
  105. bits |= headerBitRD
  106. }
  107. if m.Truncated {
  108. bits |= headerBitTC
  109. }
  110. if m.Authoritative {
  111. bits |= headerBitAA
  112. }
  113. if m.Response {
  114. bits |= headerBitQR
  115. }
  116. return
  117. }
  118. // Message is a representation of a DNS message.
  119. type Message struct {
  120. Header
  121. Questions []Question
  122. Answers []Resource
  123. Authorities []Resource
  124. Additionals []Resource
  125. }
  126. type section uint8
  127. const (
  128. sectionHeader section = iota
  129. sectionQuestions
  130. sectionAnswers
  131. sectionAuthorities
  132. sectionAdditionals
  133. sectionDone
  134. headerBitQR = 1 << 15 // query/response (response=1)
  135. headerBitAA = 1 << 10 // authoritative
  136. headerBitTC = 1 << 9 // truncated
  137. headerBitRD = 1 << 8 // recursion desired
  138. headerBitRA = 1 << 7 // recursion available
  139. )
  140. var sectionNames = map[section]string{
  141. sectionHeader: "header",
  142. sectionQuestions: "Question",
  143. sectionAnswers: "Answer",
  144. sectionAuthorities: "Authority",
  145. sectionAdditionals: "Additional",
  146. }
  147. // header is the wire format for a DNS message header.
  148. type header struct {
  149. id uint16
  150. bits uint16
  151. questions uint16
  152. answers uint16
  153. authorities uint16
  154. additionals uint16
  155. }
  156. func (h *header) count(sec section) uint16 {
  157. switch sec {
  158. case sectionQuestions:
  159. return h.questions
  160. case sectionAnswers:
  161. return h.answers
  162. case sectionAuthorities:
  163. return h.authorities
  164. case sectionAdditionals:
  165. return h.additionals
  166. }
  167. return 0
  168. }
  169. func (h *header) pack(msg []byte) []byte {
  170. msg = packUint16(msg, h.id)
  171. msg = packUint16(msg, h.bits)
  172. msg = packUint16(msg, h.questions)
  173. msg = packUint16(msg, h.answers)
  174. msg = packUint16(msg, h.authorities)
  175. return packUint16(msg, h.additionals)
  176. }
  177. func (h *header) unpack(msg []byte, off int) (int, error) {
  178. newOff := off
  179. var err error
  180. if h.id, newOff, err = unpackUint16(msg, newOff); err != nil {
  181. return off, &nestedError{"id", err}
  182. }
  183. if h.bits, newOff, err = unpackUint16(msg, newOff); err != nil {
  184. return off, &nestedError{"bits", err}
  185. }
  186. if h.questions, newOff, err = unpackUint16(msg, newOff); err != nil {
  187. return off, &nestedError{"questions", err}
  188. }
  189. if h.answers, newOff, err = unpackUint16(msg, newOff); err != nil {
  190. return off, &nestedError{"answers", err}
  191. }
  192. if h.authorities, newOff, err = unpackUint16(msg, newOff); err != nil {
  193. return off, &nestedError{"authorities", err}
  194. }
  195. if h.additionals, newOff, err = unpackUint16(msg, newOff); err != nil {
  196. return off, &nestedError{"additionals", err}
  197. }
  198. return newOff, nil
  199. }
  200. func (h *header) header() Header {
  201. return Header{
  202. ID: h.id,
  203. Response: (h.bits & headerBitQR) != 0,
  204. OpCode: OpCode(h.bits>>11) & 0xF,
  205. Authoritative: (h.bits & headerBitAA) != 0,
  206. Truncated: (h.bits & headerBitTC) != 0,
  207. RecursionDesired: (h.bits & headerBitRD) != 0,
  208. RecursionAvailable: (h.bits & headerBitRA) != 0,
  209. RCode: RCode(h.bits & 0xF),
  210. }
  211. }
  212. // A Resource is a DNS resource record.
  213. type Resource interface {
  214. // Header return's the Resource's ResourceHeader.
  215. Header() *ResourceHeader
  216. // pack packs a Resource except for its header.
  217. pack(msg []byte, compression map[string]int) ([]byte, error)
  218. // realType returns the actual type of the Resource. This is used to
  219. // fill in the header Type field.
  220. realType() Type
  221. }
  222. func packResource(msg []byte, resource Resource, compression map[string]int) ([]byte, error) {
  223. oldMsg := msg
  224. resource.Header().Type = resource.realType()
  225. msg, length, err := resource.Header().pack(msg, compression)
  226. if err != nil {
  227. return msg, &nestedError{"ResourceHeader", err}
  228. }
  229. preLen := len(msg)
  230. msg, err = resource.pack(msg, compression)
  231. if err != nil {
  232. return msg, &nestedError{"content", err}
  233. }
  234. conLen := len(msg) - preLen
  235. if conLen > int(^uint16(0)) {
  236. return oldMsg, errResTooLong
  237. }
  238. // Fill in the length now that we know how long the content is.
  239. packUint16(length[:0], uint16(conLen))
  240. resource.Header().Length = uint16(conLen)
  241. return msg, nil
  242. }
  243. // A Parser allows incrementally parsing a DNS message.
  244. //
  245. // When parsing is started, the Header is parsed. Next, each Question can be
  246. // either parsed or skipped. Alternatively, all Questions can be skipped at
  247. // once. When all Questions have been parsed, attempting to parse Questions
  248. // will return (nil, nil) and attempting to skip Questions will return
  249. // (true, nil). After all Questions have been either parsed or skipped, all
  250. // Answers, Authorities and Additionals can be either parsed or skipped in the
  251. // same way, and each type of Resource must be fully parsed or skipped before
  252. // proceeding to the next type of Resource.
  253. //
  254. // Note that there is no requirement to fully skip or parse the message.
  255. type Parser struct {
  256. msg []byte
  257. header header
  258. section section
  259. off int
  260. index int
  261. resHeaderValid bool
  262. resHeader ResourceHeader
  263. }
  264. // Start parses the header and enables the parsing of Questions.
  265. func (p *Parser) Start(msg []byte) (Header, error) {
  266. if p.msg != nil {
  267. *p = Parser{}
  268. }
  269. p.msg = msg
  270. var err error
  271. if p.off, err = p.header.unpack(msg, 0); err != nil {
  272. return Header{}, &nestedError{"unpacking header", err}
  273. }
  274. p.section = sectionQuestions
  275. return p.header.header(), nil
  276. }
  277. func (p *Parser) checkAdvance(sec section) error {
  278. if p.section < sec {
  279. return ErrNotStarted
  280. }
  281. if p.section > sec {
  282. return ErrSectionDone
  283. }
  284. p.resHeaderValid = false
  285. if p.index == int(p.header.count(sec)) {
  286. p.index = 0
  287. p.section++
  288. return ErrSectionDone
  289. }
  290. return nil
  291. }
  292. func (p *Parser) resource(sec section) (Resource, error) {
  293. var r Resource
  294. hdr, err := p.resourceHeader(sec)
  295. if err != nil {
  296. return r, err
  297. }
  298. p.resHeaderValid = false
  299. r, p.off, err = unpackResource(p.msg, p.off, hdr)
  300. if err != nil {
  301. return nil, &nestedError{"unpacking " + sectionNames[sec], err}
  302. }
  303. p.index++
  304. return r, nil
  305. }
  306. func (p *Parser) resourceHeader(sec section) (ResourceHeader, error) {
  307. if p.resHeaderValid {
  308. return p.resHeader, nil
  309. }
  310. if err := p.checkAdvance(sec); err != nil {
  311. return ResourceHeader{}, err
  312. }
  313. var hdr ResourceHeader
  314. off, err := hdr.unpack(p.msg, p.off)
  315. if err != nil {
  316. return ResourceHeader{}, err
  317. }
  318. p.resHeaderValid = true
  319. p.resHeader = hdr
  320. p.off = off
  321. return hdr, nil
  322. }
  323. func (p *Parser) skipResource(sec section) error {
  324. if p.resHeaderValid {
  325. newOff := p.off + int(p.resHeader.Length)
  326. if newOff > len(p.msg) {
  327. return errResourceLen
  328. }
  329. p.off = newOff
  330. p.resHeaderValid = false
  331. p.index++
  332. return nil
  333. }
  334. if err := p.checkAdvance(sec); err != nil {
  335. return err
  336. }
  337. var err error
  338. p.off, err = skipResource(p.msg, p.off)
  339. if err != nil {
  340. return &nestedError{"skipping: " + sectionNames[sec], err}
  341. }
  342. p.index++
  343. return nil
  344. }
  345. // Question parses a single Question.
  346. func (p *Parser) Question() (Question, error) {
  347. if err := p.checkAdvance(sectionQuestions); err != nil {
  348. return Question{}, err
  349. }
  350. name, off, err := unpackName(p.msg, p.off)
  351. if err != nil {
  352. return Question{}, &nestedError{"unpacking Question.Name", err}
  353. }
  354. typ, off, err := unpackType(p.msg, off)
  355. if err != nil {
  356. return Question{}, &nestedError{"unpacking Question.Type", err}
  357. }
  358. class, off, err := unpackClass(p.msg, off)
  359. if err != nil {
  360. return Question{}, &nestedError{"unpacking Question.Class", err}
  361. }
  362. p.off = off
  363. p.index++
  364. return Question{name, typ, class}, nil
  365. }
  366. // AllQuestions parses all Questions.
  367. func (p *Parser) AllQuestions() ([]Question, error) {
  368. qs := make([]Question, 0, p.header.questions)
  369. for {
  370. q, err := p.Question()
  371. if err == ErrSectionDone {
  372. return qs, nil
  373. }
  374. if err != nil {
  375. return nil, err
  376. }
  377. qs = append(qs, q)
  378. }
  379. }
  380. // SkipQuestion skips a single Question.
  381. func (p *Parser) SkipQuestion() error {
  382. if err := p.checkAdvance(sectionQuestions); err != nil {
  383. return err
  384. }
  385. off, err := skipName(p.msg, p.off)
  386. if err != nil {
  387. return &nestedError{"skipping Question Name", err}
  388. }
  389. if off, err = skipType(p.msg, off); err != nil {
  390. return &nestedError{"skipping Question Type", err}
  391. }
  392. if off, err = skipClass(p.msg, off); err != nil {
  393. return &nestedError{"skipping Question Class", err}
  394. }
  395. p.off = off
  396. p.index++
  397. return nil
  398. }
  399. // SkipAllQuestions skips all Questions.
  400. func (p *Parser) SkipAllQuestions() error {
  401. for {
  402. if err := p.SkipQuestion(); err == ErrSectionDone {
  403. return nil
  404. } else if err != nil {
  405. return err
  406. }
  407. }
  408. }
  409. // AnswerHeader parses a single Answer ResourceHeader.
  410. func (p *Parser) AnswerHeader() (ResourceHeader, error) {
  411. return p.resourceHeader(sectionAnswers)
  412. }
  413. // Answer parses a single Answer Resource.
  414. func (p *Parser) Answer() (Resource, error) {
  415. return p.resource(sectionAnswers)
  416. }
  417. // AllAnswers parses all Answer Resources.
  418. func (p *Parser) AllAnswers() ([]Resource, error) {
  419. as := make([]Resource, 0, p.header.answers)
  420. for {
  421. a, err := p.Answer()
  422. if err == ErrSectionDone {
  423. return as, nil
  424. }
  425. if err != nil {
  426. return nil, err
  427. }
  428. as = append(as, a)
  429. }
  430. }
  431. // SkipAnswer skips a single Answer Resource.
  432. func (p *Parser) SkipAnswer() error {
  433. return p.skipResource(sectionAnswers)
  434. }
  435. // SkipAllAnswers skips all Answer Resources.
  436. func (p *Parser) SkipAllAnswers() error {
  437. for {
  438. if err := p.SkipAnswer(); err == ErrSectionDone {
  439. return nil
  440. } else if err != nil {
  441. return err
  442. }
  443. }
  444. }
  445. // AuthorityHeader parses a single Authority ResourceHeader.
  446. func (p *Parser) AuthorityHeader() (ResourceHeader, error) {
  447. return p.resourceHeader(sectionAuthorities)
  448. }
  449. // Authority parses a single Authority Resource.
  450. func (p *Parser) Authority() (Resource, error) {
  451. return p.resource(sectionAuthorities)
  452. }
  453. // AllAuthorities parses all Authority Resources.
  454. func (p *Parser) AllAuthorities() ([]Resource, error) {
  455. as := make([]Resource, 0, p.header.authorities)
  456. for {
  457. a, err := p.Authority()
  458. if err == ErrSectionDone {
  459. return as, nil
  460. }
  461. if err != nil {
  462. return nil, err
  463. }
  464. as = append(as, a)
  465. }
  466. }
  467. // SkipAuthority skips a single Authority Resource.
  468. func (p *Parser) SkipAuthority() error {
  469. return p.skipResource(sectionAuthorities)
  470. }
  471. // SkipAllAuthorities skips all Authority Resources.
  472. func (p *Parser) SkipAllAuthorities() error {
  473. for {
  474. if err := p.SkipAuthority(); err == ErrSectionDone {
  475. return nil
  476. } else if err != nil {
  477. return err
  478. }
  479. }
  480. }
  481. // AdditionalHeader parses a single Additional ResourceHeader.
  482. func (p *Parser) AdditionalHeader() (ResourceHeader, error) {
  483. return p.resourceHeader(sectionAdditionals)
  484. }
  485. // Additional parses a single Additional Resource.
  486. func (p *Parser) Additional() (Resource, error) {
  487. return p.resource(sectionAdditionals)
  488. }
  489. // AllAdditionals parses all Additional Resources.
  490. func (p *Parser) AllAdditionals() ([]Resource, error) {
  491. as := make([]Resource, 0, p.header.additionals)
  492. for {
  493. a, err := p.Additional()
  494. if err == ErrSectionDone {
  495. return as, nil
  496. }
  497. if err != nil {
  498. return nil, err
  499. }
  500. as = append(as, a)
  501. }
  502. }
  503. // SkipAdditional skips a single Additional Resource.
  504. func (p *Parser) SkipAdditional() error {
  505. return p.skipResource(sectionAdditionals)
  506. }
  507. // SkipAllAdditionals skips all Additional Resources.
  508. func (p *Parser) SkipAllAdditionals() error {
  509. for {
  510. if err := p.SkipAdditional(); err == ErrSectionDone {
  511. return nil
  512. } else if err != nil {
  513. return err
  514. }
  515. }
  516. }
  517. // Unpack parses a full Message.
  518. func (m *Message) Unpack(msg []byte) error {
  519. var p Parser
  520. var err error
  521. if m.Header, err = p.Start(msg); err != nil {
  522. return err
  523. }
  524. if m.Questions, err = p.AllQuestions(); err != nil {
  525. return err
  526. }
  527. if m.Answers, err = p.AllAnswers(); err != nil {
  528. return err
  529. }
  530. if m.Authorities, err = p.AllAuthorities(); err != nil {
  531. return err
  532. }
  533. if m.Additionals, err = p.AllAdditionals(); err != nil {
  534. return err
  535. }
  536. return nil
  537. }
  538. // Pack packs a full Message.
  539. func (m *Message) Pack() ([]byte, error) {
  540. // Validate the lengths. It is very unlikely that anyone will try to
  541. // pack more than 65535 of any particular type, but it is possible and
  542. // we should fail gracefully.
  543. if len(m.Questions) > int(^uint16(0)) {
  544. return nil, errTooManyQuestions
  545. }
  546. if len(m.Answers) > int(^uint16(0)) {
  547. return nil, errTooManyAnswers
  548. }
  549. if len(m.Authorities) > int(^uint16(0)) {
  550. return nil, errTooManyAuthorities
  551. }
  552. if len(m.Additionals) > int(^uint16(0)) {
  553. return nil, errTooManyAdditionals
  554. }
  555. var h header
  556. h.id, h.bits = m.Header.pack()
  557. h.questions = uint16(len(m.Questions))
  558. h.answers = uint16(len(m.Answers))
  559. h.authorities = uint16(len(m.Authorities))
  560. h.additionals = uint16(len(m.Additionals))
  561. // The starting capacity doesn't matter too much, but most DNS responses
  562. // Will be <= 512 bytes as it is the limit for DNS over UDP.
  563. msg := make([]byte, 0, 512)
  564. msg = h.pack(msg)
  565. // RFC 1035 allows (but does not require) compression for packing. RFC
  566. // 1035 requires unpacking implementations to support compression, so
  567. // unconditionally enabling it is fine.
  568. //
  569. // DNS lookups are typically done over UDP, and RFC 1035 states that UDP
  570. // DNS packets can be a maximum of 512 bytes long. Without compression,
  571. // many DNS response packets are over this limit, so enabling
  572. // compression will help ensure compliance.
  573. compression := map[string]int{}
  574. for _, q := range m.Questions {
  575. var err error
  576. msg, err = q.pack(msg, compression)
  577. if err != nil {
  578. return nil, &nestedError{"packing Question", err}
  579. }
  580. }
  581. for _, a := range m.Answers {
  582. var err error
  583. msg, err = packResource(msg, a, compression)
  584. if err != nil {
  585. return nil, &nestedError{"packing Answer", err}
  586. }
  587. }
  588. for _, a := range m.Authorities {
  589. var err error
  590. msg, err = packResource(msg, a, compression)
  591. if err != nil {
  592. return nil, &nestedError{"packing Authority", err}
  593. }
  594. }
  595. for _, a := range m.Additionals {
  596. var err error
  597. msg, err = packResource(msg, a, compression)
  598. if err != nil {
  599. return nil, &nestedError{"packing Additional", err}
  600. }
  601. }
  602. return msg, nil
  603. }
  604. // An ResourceHeader is the header of a DNS resource record. There are
  605. // many types of DNS resource records, but they all share the same header.
  606. type ResourceHeader struct {
  607. // Name is the domain name for which this resource record pertains.
  608. Name string
  609. // Type is the type of DNS resource record.
  610. //
  611. // This field will be set automatically during packing.
  612. Type Type
  613. // Class is the class of network to which this DNS resource record
  614. // pertains.
  615. Class Class
  616. // TTL is the length of time (measured in seconds) which this resource
  617. // record is valid for (time to live). All Resources in a set should
  618. // have the same TTL (RFC 2181 Section 5.2).
  619. TTL uint32
  620. // Length is the length of data in the resource record after the header.
  621. //
  622. // This field will be set automatically during packing.
  623. Length uint16
  624. }
  625. // Header implements Resource.Header.
  626. func (h *ResourceHeader) Header() *ResourceHeader {
  627. return h
  628. }
  629. // pack packs all of the fields in a ResourceHeader except for the length. The
  630. // length bytes are returned as a slice so they can be filled in after the rest
  631. // of the Resource has been packed.
  632. func (h *ResourceHeader) pack(oldMsg []byte, compression map[string]int) (msg []byte, length []byte, err error) {
  633. msg = oldMsg
  634. if msg, err = packName(msg, h.Name, compression); err != nil {
  635. return oldMsg, nil, &nestedError{"Name", err}
  636. }
  637. msg = packType(msg, h.Type)
  638. msg = packClass(msg, h.Class)
  639. msg = packUint32(msg, h.TTL)
  640. lenBegin := len(msg)
  641. msg = packUint16(msg, h.Length)
  642. return msg, msg[lenBegin:], nil
  643. }
  644. func (h *ResourceHeader) unpack(msg []byte, off int) (int, error) {
  645. newOff := off
  646. var err error
  647. if h.Name, newOff, err = unpackName(msg, newOff); err != nil {
  648. return off, &nestedError{"Name", err}
  649. }
  650. if h.Type, newOff, err = unpackType(msg, newOff); err != nil {
  651. return off, &nestedError{"Type", err}
  652. }
  653. if h.Class, newOff, err = unpackClass(msg, newOff); err != nil {
  654. return off, &nestedError{"Class", err}
  655. }
  656. if h.TTL, newOff, err = unpackUint32(msg, newOff); err != nil {
  657. return off, &nestedError{"TTL", err}
  658. }
  659. if h.Length, newOff, err = unpackUint16(msg, newOff); err != nil {
  660. return off, &nestedError{"Length", err}
  661. }
  662. return newOff, nil
  663. }
  664. func skipResource(msg []byte, off int) (int, error) {
  665. newOff, err := skipName(msg, off)
  666. if err != nil {
  667. return off, &nestedError{"Name", err}
  668. }
  669. if newOff, err = skipType(msg, newOff); err != nil {
  670. return off, &nestedError{"Type", err}
  671. }
  672. if newOff, err = skipClass(msg, newOff); err != nil {
  673. return off, &nestedError{"Class", err}
  674. }
  675. if newOff, err = skipUint32(msg, newOff); err != nil {
  676. return off, &nestedError{"TTL", err}
  677. }
  678. length, newOff, err := unpackUint16(msg, newOff)
  679. if err != nil {
  680. return off, &nestedError{"Length", err}
  681. }
  682. if newOff += int(length); newOff > len(msg) {
  683. return off, errResourceLen
  684. }
  685. return newOff, nil
  686. }
  687. func packUint16(msg []byte, field uint16) []byte {
  688. return append(msg, byte(field>>8), byte(field))
  689. }
  690. func unpackUint16(msg []byte, off int) (uint16, int, error) {
  691. if off+2 > len(msg) {
  692. return 0, off, errBaseLen
  693. }
  694. return uint16(msg[off])<<8 | uint16(msg[off+1]), off + 2, nil
  695. }
  696. func skipUint16(msg []byte, off int) (int, error) {
  697. if off+2 > len(msg) {
  698. return off, errBaseLen
  699. }
  700. return off + 2, nil
  701. }
  702. func packType(msg []byte, field Type) []byte {
  703. return packUint16(msg, uint16(field))
  704. }
  705. func unpackType(msg []byte, off int) (Type, int, error) {
  706. t, o, err := unpackUint16(msg, off)
  707. return Type(t), o, err
  708. }
  709. func skipType(msg []byte, off int) (int, error) {
  710. return skipUint16(msg, off)
  711. }
  712. func packClass(msg []byte, field Class) []byte {
  713. return packUint16(msg, uint16(field))
  714. }
  715. func unpackClass(msg []byte, off int) (Class, int, error) {
  716. c, o, err := unpackUint16(msg, off)
  717. return Class(c), o, err
  718. }
  719. func skipClass(msg []byte, off int) (int, error) {
  720. return skipUint16(msg, off)
  721. }
  722. func packUint32(msg []byte, field uint32) []byte {
  723. return append(
  724. msg,
  725. byte(field>>24),
  726. byte(field>>16),
  727. byte(field>>8),
  728. byte(field),
  729. )
  730. }
  731. func unpackUint32(msg []byte, off int) (uint32, int, error) {
  732. if off+4 > len(msg) {
  733. return 0, off, errBaseLen
  734. }
  735. v := uint32(msg[off])<<24 | uint32(msg[off+1])<<16 | uint32(msg[off+2])<<8 | uint32(msg[off+3])
  736. return v, off + 4, nil
  737. }
  738. func skipUint32(msg []byte, off int) (int, error) {
  739. if off+4 > len(msg) {
  740. return off, errBaseLen
  741. }
  742. return off + 4, nil
  743. }
  744. func packText(msg []byte, field string) []byte {
  745. for len(field) > 0 {
  746. l := len(field)
  747. if l > 255 {
  748. l = 255
  749. }
  750. msg = append(msg, byte(l))
  751. msg = append(msg, field[:l]...)
  752. field = field[l:]
  753. }
  754. return msg
  755. }
  756. func unpackText(msg []byte, off int) (string, int, error) {
  757. if off >= len(msg) {
  758. return "", off, errBaseLen
  759. }
  760. beginOff := off + 1
  761. endOff := beginOff + int(msg[off])
  762. if endOff > len(msg) {
  763. return "", off, errCalcLen
  764. }
  765. return string(msg[beginOff:endOff]), endOff, nil
  766. }
  767. func skipText(msg []byte, off int) (int, error) {
  768. if off >= len(msg) {
  769. return off, errBaseLen
  770. }
  771. endOff := off + 1 + int(msg[off])
  772. if endOff > len(msg) {
  773. return off, errCalcLen
  774. }
  775. return endOff, nil
  776. }
  777. func packBytes(msg []byte, field []byte) []byte {
  778. return append(msg, field...)
  779. }
  780. func unpackBytes(msg []byte, off int, field []byte) (int, error) {
  781. newOff := off + len(field)
  782. if newOff > len(msg) {
  783. return off, errBaseLen
  784. }
  785. copy(field, msg[off:newOff])
  786. return newOff, nil
  787. }
  788. func skipBytes(msg []byte, off int, field []byte) (int, error) {
  789. newOff := off + len(field)
  790. if newOff > len(msg) {
  791. return off, errBaseLen
  792. }
  793. return newOff, nil
  794. }
  795. // packName packs a domain name.
  796. //
  797. // Domain names are a sequence of counted strings split at the dots. They end
  798. // with a zero-length string. Compression can be used to reuse domain suffixes.
  799. //
  800. // The compression map will be updated with new domain suffixes. If compression
  801. // is nil, compression will not be used.
  802. func packName(msg []byte, name string, compression map[string]int) ([]byte, error) {
  803. oldMsg := msg
  804. // Add a trailing dot to canonicalize name.
  805. if n := len(name); n == 0 || name[n-1] != '.' {
  806. name += "."
  807. }
  808. // Allow root domain.
  809. if name == "." {
  810. return append(msg, 0), nil
  811. }
  812. // Emit sequence of counted strings, chopping at dots.
  813. for i, begin := 0, 0; i < len(name); i++ {
  814. // Check for the end of the segment.
  815. if name[i] == '.' {
  816. // The two most significant bits have special meaning.
  817. // It isn't allowed for segments to be long enough to
  818. // need them.
  819. if i-begin >= 1<<6 {
  820. return oldMsg, errSegTooLong
  821. }
  822. // Segments must have a non-zero length.
  823. if i-begin == 0 {
  824. return oldMsg, errZeroSegLen
  825. }
  826. msg = append(msg, byte(i-begin))
  827. for j := begin; j < i; j++ {
  828. msg = append(msg, name[j])
  829. }
  830. begin = i + 1
  831. continue
  832. }
  833. // We can only compress domain suffixes starting with a new
  834. // segment. A pointer is two bytes with the two most significant
  835. // bits set to 1 to indicate that it is a pointer.
  836. if (i == 0 || name[i-1] == '.') && compression != nil {
  837. if ptr, ok := compression[name[i:]]; ok {
  838. // Hit. Emit a pointer instead of the rest of
  839. // the domain.
  840. return append(msg, byte(ptr>>8|0xC0), byte(ptr)), nil
  841. }
  842. // Miss. Add the suffix to the compression table if the
  843. // offset can be stored in the available 14 bytes.
  844. if len(msg) <= int(^uint16(0)>>2) {
  845. compression[name[i:]] = len(msg)
  846. }
  847. }
  848. }
  849. return append(msg, 0), nil
  850. }
  851. // unpackName unpacks a domain name.
  852. func unpackName(msg []byte, off int) (string, int, error) {
  853. // currOff is the current working offset.
  854. currOff := off
  855. // newOff is the offset where the next record will start. Pointers lead
  856. // to data that belongs to other names and thus doesn't count towards to
  857. // the usage of this name.
  858. newOff := off
  859. // name is the domain name being unpacked.
  860. name := make([]byte, 0, 255)
  861. // ptr is the number of pointers followed.
  862. var ptr int
  863. Loop:
  864. for {
  865. if currOff >= len(msg) {
  866. return "", off, errBaseLen
  867. }
  868. c := int(msg[currOff])
  869. currOff++
  870. switch c & 0xC0 {
  871. case 0x00: // String segment
  872. if c == 0x00 {
  873. // A zero length signals the end of the name.
  874. break Loop
  875. }
  876. endOff := currOff + c
  877. if endOff > len(msg) {
  878. return "", off, errCalcLen
  879. }
  880. name = append(name, msg[currOff:endOff]...)
  881. name = append(name, '.')
  882. currOff = endOff
  883. case 0xC0: // Pointer
  884. if currOff >= len(msg) {
  885. return "", off, errInvalidPtr
  886. }
  887. c1 := msg[currOff]
  888. currOff++
  889. if ptr == 0 {
  890. newOff = currOff
  891. }
  892. // Don't follow too many pointers, maybe there's a loop.
  893. if ptr++; ptr > 10 {
  894. return "", off, errTooManyPtr
  895. }
  896. currOff = (c^0xC0)<<8 | int(c1)
  897. default:
  898. // Prefixes 0x80 and 0x40 are reserved.
  899. return "", off, errReserved
  900. }
  901. }
  902. if len(name) == 0 {
  903. name = append(name, '.')
  904. }
  905. if ptr == 0 {
  906. newOff = currOff
  907. }
  908. return string(name), newOff, nil
  909. }
  910. func skipName(msg []byte, off int) (int, error) {
  911. // newOff is the offset where the next record will start. Pointers lead
  912. // to data that belongs to other names and thus doesn't count towards to
  913. // the usage of this name.
  914. newOff := off
  915. Loop:
  916. for {
  917. if newOff >= len(msg) {
  918. return off, errBaseLen
  919. }
  920. c := int(msg[newOff])
  921. newOff++
  922. switch c & 0xC0 {
  923. case 0x00:
  924. if c == 0x00 {
  925. // A zero length signals the end of the name.
  926. break Loop
  927. }
  928. // literal string
  929. newOff += c
  930. if newOff > len(msg) {
  931. return off, errCalcLen
  932. }
  933. case 0xC0:
  934. // Pointer to somewhere else in msg.
  935. // Pointers are two bytes.
  936. newOff++
  937. // Don't follow the pointer as the data here has ended.
  938. break Loop
  939. default:
  940. // Prefixes 0x80 and 0x40 are reserved.
  941. return off, errReserved
  942. }
  943. }
  944. return newOff, nil
  945. }
  946. // A Question is a DNS query.
  947. type Question struct {
  948. Name string
  949. Type Type
  950. Class Class
  951. }
  952. func (q *Question) pack(msg []byte, compression map[string]int) ([]byte, error) {
  953. msg, err := packName(msg, q.Name, compression)
  954. if err != nil {
  955. return msg, &nestedError{"Name", err}
  956. }
  957. msg = packType(msg, q.Type)
  958. return packClass(msg, q.Class), nil
  959. }
  960. func unpackResource(msg []byte, off int, hdr ResourceHeader) (Resource, int, error) {
  961. var (
  962. r Resource
  963. err error
  964. name string
  965. )
  966. switch hdr.Type {
  967. case TypeA:
  968. r, err = unpackAResource(hdr, msg, off)
  969. name = "A"
  970. case TypeNS:
  971. r, err = unpackNSResource(hdr, msg, off)
  972. name = "NS"
  973. case TypeCNAME:
  974. r, err = unpackCNAMEResource(hdr, msg, off)
  975. name = "CNAME"
  976. case TypeSOA:
  977. r, err = unpackSOAResource(hdr, msg, off)
  978. name = "SOA"
  979. case TypePTR:
  980. r, err = unpackPTRResource(hdr, msg, off)
  981. name = "PTR"
  982. case TypeMX:
  983. r, err = unpackMXResource(hdr, msg, off)
  984. name = "MX"
  985. case TypeTXT:
  986. r, err = unpackTXTResource(hdr, msg, off)
  987. name = "TXT"
  988. case TypeAAAA:
  989. r, err = unpackAAAAResource(hdr, msg, off)
  990. name = "AAAA"
  991. case TypeSRV:
  992. r, err = unpackSRVResource(hdr, msg, off)
  993. name = "SRV"
  994. }
  995. if err != nil {
  996. return nil, off, &nestedError{name + " record", err}
  997. }
  998. if r != nil {
  999. return r, off + int(hdr.Length), nil
  1000. }
  1001. return nil, off, errors.New("invalid resource type: " + string(hdr.Type+'0'))
  1002. }
  1003. // A CNAMEResource is a CNAME Resource record.
  1004. type CNAMEResource struct {
  1005. ResourceHeader
  1006. CNAME string
  1007. }
  1008. func (r *CNAMEResource) realType() Type {
  1009. return TypeCNAME
  1010. }
  1011. func (r *CNAMEResource) pack(msg []byte, compression map[string]int) ([]byte, error) {
  1012. return packName(msg, r.CNAME, compression)
  1013. }
  1014. func unpackCNAMEResource(hdr ResourceHeader, msg []byte, off int) (*CNAMEResource, error) {
  1015. cname, _, err := unpackName(msg, off)
  1016. if err != nil {
  1017. return nil, err
  1018. }
  1019. return &CNAMEResource{hdr, cname}, nil
  1020. }
  1021. // An MXResource is an MX Resource record.
  1022. type MXResource struct {
  1023. ResourceHeader
  1024. Pref uint16
  1025. MX string
  1026. }
  1027. func (r *MXResource) realType() Type {
  1028. return TypeMX
  1029. }
  1030. func (r *MXResource) pack(msg []byte, compression map[string]int) ([]byte, error) {
  1031. oldMsg := msg
  1032. msg = packUint16(msg, r.Pref)
  1033. msg, err := packName(msg, r.MX, compression)
  1034. if err != nil {
  1035. return oldMsg, &nestedError{"MXResource.MX", err}
  1036. }
  1037. return msg, nil
  1038. }
  1039. func unpackMXResource(hdr ResourceHeader, msg []byte, off int) (*MXResource, error) {
  1040. pref, off, err := unpackUint16(msg, off)
  1041. if err != nil {
  1042. return nil, &nestedError{"Pref", err}
  1043. }
  1044. mx, _, err := unpackName(msg, off)
  1045. if err != nil {
  1046. return nil, &nestedError{"MX", err}
  1047. }
  1048. return &MXResource{hdr, pref, mx}, nil
  1049. }
  1050. // An NSResource is an NS Resource record.
  1051. type NSResource struct {
  1052. ResourceHeader
  1053. NS string
  1054. }
  1055. func (r *NSResource) realType() Type {
  1056. return TypeNS
  1057. }
  1058. func (r *NSResource) pack(msg []byte, compression map[string]int) ([]byte, error) {
  1059. return packName(msg, r.NS, compression)
  1060. }
  1061. func unpackNSResource(hdr ResourceHeader, msg []byte, off int) (*NSResource, error) {
  1062. ns, _, err := unpackName(msg, off)
  1063. if err != nil {
  1064. return nil, err
  1065. }
  1066. return &NSResource{hdr, ns}, nil
  1067. }
  1068. // A PTRResource is a PTR Resource record.
  1069. type PTRResource struct {
  1070. ResourceHeader
  1071. PTR string
  1072. }
  1073. func (r *PTRResource) realType() Type {
  1074. return TypePTR
  1075. }
  1076. func (r *PTRResource) pack(msg []byte, compression map[string]int) ([]byte, error) {
  1077. return packName(msg, r.PTR, compression)
  1078. }
  1079. func unpackPTRResource(hdr ResourceHeader, msg []byte, off int) (*PTRResource, error) {
  1080. ptr, _, err := unpackName(msg, off)
  1081. if err != nil {
  1082. return nil, err
  1083. }
  1084. return &PTRResource{hdr, ptr}, nil
  1085. }
  1086. // An SOAResource is an SOA Resource record.
  1087. type SOAResource struct {
  1088. ResourceHeader
  1089. NS string
  1090. MBox string
  1091. Serial uint32
  1092. Refresh uint32
  1093. Retry uint32
  1094. Expire uint32
  1095. // MinTTL the is the default TTL of Resources records which did not
  1096. // contain a TTL value and the TTL of negative responses. (RFC 2308
  1097. // Section 4)
  1098. MinTTL uint32
  1099. }
  1100. func (r *SOAResource) realType() Type {
  1101. return TypeSOA
  1102. }
  1103. func (r *SOAResource) pack(msg []byte, compression map[string]int) ([]byte, error) {
  1104. oldMsg := msg
  1105. msg, err := packName(msg, r.NS, compression)
  1106. if err != nil {
  1107. return oldMsg, &nestedError{"SOAResource.NS", err}
  1108. }
  1109. msg, err = packName(msg, r.MBox, compression)
  1110. if err != nil {
  1111. return oldMsg, &nestedError{"SOAResource.MBox", err}
  1112. }
  1113. msg = packUint32(msg, r.Serial)
  1114. msg = packUint32(msg, r.Refresh)
  1115. msg = packUint32(msg, r.Retry)
  1116. msg = packUint32(msg, r.Expire)
  1117. return packUint32(msg, r.MinTTL), nil
  1118. }
  1119. func unpackSOAResource(hdr ResourceHeader, msg []byte, off int) (*SOAResource, error) {
  1120. ns, off, err := unpackName(msg, off)
  1121. if err != nil {
  1122. return nil, &nestedError{"NS", err}
  1123. }
  1124. mbox, off, err := unpackName(msg, off)
  1125. if err != nil {
  1126. return nil, &nestedError{"MBox", err}
  1127. }
  1128. serial, off, err := unpackUint32(msg, off)
  1129. if err != nil {
  1130. return nil, &nestedError{"Serial", err}
  1131. }
  1132. refresh, off, err := unpackUint32(msg, off)
  1133. if err != nil {
  1134. return nil, &nestedError{"Refresh", err}
  1135. }
  1136. retry, off, err := unpackUint32(msg, off)
  1137. if err != nil {
  1138. return nil, &nestedError{"Retry", err}
  1139. }
  1140. expire, off, err := unpackUint32(msg, off)
  1141. if err != nil {
  1142. return nil, &nestedError{"Expire", err}
  1143. }
  1144. minTTL, _, err := unpackUint32(msg, off)
  1145. if err != nil {
  1146. return nil, &nestedError{"MinTTL", err}
  1147. }
  1148. return &SOAResource{hdr, ns, mbox, serial, refresh, retry, expire, minTTL}, nil
  1149. }
  1150. // A TXTResource is a TXT Resource record.
  1151. type TXTResource struct {
  1152. ResourceHeader
  1153. Txt string // Not a domain name.
  1154. }
  1155. func (r *TXTResource) realType() Type {
  1156. return TypeTXT
  1157. }
  1158. func (r *TXTResource) pack(msg []byte, compression map[string]int) ([]byte, error) {
  1159. return packText(msg, r.Txt), nil
  1160. }
  1161. func unpackTXTResource(hdr ResourceHeader, msg []byte, off int) (*TXTResource, error) {
  1162. var txt string
  1163. for n := uint16(0); n < hdr.Length; {
  1164. var t string
  1165. var err error
  1166. if t, off, err = unpackText(msg, off); err != nil {
  1167. return nil, &nestedError{"text", err}
  1168. }
  1169. // Check if we got too many bytes.
  1170. if hdr.Length-n < uint16(len(t))+1 {
  1171. return nil, errCalcLen
  1172. }
  1173. n += uint16(len(t)) + 1
  1174. txt += t
  1175. }
  1176. return &TXTResource{hdr, txt}, nil
  1177. }
  1178. // An SRVResource is an SRV Resource record.
  1179. type SRVResource struct {
  1180. ResourceHeader
  1181. Priority uint16
  1182. Weight uint16
  1183. Port uint16
  1184. Target string // Not compressed as per RFC 2782.
  1185. }
  1186. func (r *SRVResource) realType() Type {
  1187. return TypeSRV
  1188. }
  1189. func (r *SRVResource) pack(msg []byte, compression map[string]int) ([]byte, error) {
  1190. oldMsg := msg
  1191. msg = packUint16(msg, r.Priority)
  1192. msg = packUint16(msg, r.Weight)
  1193. msg = packUint16(msg, r.Port)
  1194. msg, err := packName(msg, r.Target, nil)
  1195. if err != nil {
  1196. return oldMsg, &nestedError{"SRVResource.Target", err}
  1197. }
  1198. return msg, nil
  1199. }
  1200. func unpackSRVResource(hdr ResourceHeader, msg []byte, off int) (*SRVResource, error) {
  1201. priority, off, err := unpackUint16(msg, off)
  1202. if err != nil {
  1203. return nil, &nestedError{"Priority", err}
  1204. }
  1205. weight, off, err := unpackUint16(msg, off)
  1206. if err != nil {
  1207. return nil, &nestedError{"Weight", err}
  1208. }
  1209. port, off, err := unpackUint16(msg, off)
  1210. if err != nil {
  1211. return nil, &nestedError{"Port", err}
  1212. }
  1213. target, _, err := unpackName(msg, off)
  1214. if err != nil {
  1215. return nil, &nestedError{"Target", err}
  1216. }
  1217. return &SRVResource{hdr, priority, weight, port, target}, nil
  1218. }
  1219. // An AResource is an A Resource record.
  1220. type AResource struct {
  1221. ResourceHeader
  1222. A [4]byte
  1223. }
  1224. func (r *AResource) realType() Type {
  1225. return TypeA
  1226. }
  1227. func (r *AResource) pack(msg []byte, compression map[string]int) ([]byte, error) {
  1228. return packBytes(msg, r.A[:]), nil
  1229. }
  1230. func unpackAResource(hdr ResourceHeader, msg []byte, off int) (*AResource, error) {
  1231. var a [4]byte
  1232. if _, err := unpackBytes(msg, off, a[:]); err != nil {
  1233. return nil, err
  1234. }
  1235. return &AResource{hdr, a}, nil
  1236. }
  1237. // An AAAAResource is an AAAA Resource record.
  1238. type AAAAResource struct {
  1239. ResourceHeader
  1240. AAAA [16]byte
  1241. }
  1242. func (r *AAAAResource) realType() Type {
  1243. return TypeAAAA
  1244. }
  1245. func (r *AAAAResource) pack(msg []byte, compression map[string]int) ([]byte, error) {
  1246. return packBytes(msg, r.AAAA[:]), nil
  1247. }
  1248. func unpackAAAAResource(hdr ResourceHeader, msg []byte, off int) (*AAAAResource, error) {
  1249. var aaaa [16]byte
  1250. if _, err := unpackBytes(msg, off, aaaa[:]); err != nil {
  1251. return nil, err
  1252. }
  1253. return &AAAAResource{hdr, aaaa}, nil
  1254. }