message.go 53 KB

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