message.go 68 KB

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