message.go 69 KB

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