message.go 65 KB

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