message.go 65 KB

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