message.go 57 KB

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