message.go 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601
  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, length, 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, length, 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, length, 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, length, 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, length, 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, length, 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, length, 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, length, 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, length, 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, length, 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, length, 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, length, 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, length, 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, length, 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, length, 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, length, 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, length, 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, length, 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, length, 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, length, 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, length, 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, length, 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. // The bytes where length was packed are returned as a slice so they can be
  1471. // updated after the rest of the Resource has been packed.
  1472. func (h *ResourceHeader) pack(oldMsg []byte, compression map[string]int, compressionOff int) (msg []byte, length []byte, err error) {
  1473. msg = oldMsg
  1474. if msg, err = h.Name.pack(msg, compression, compressionOff); err != nil {
  1475. return oldMsg, nil, &nestedError{"Name", err}
  1476. }
  1477. msg = packType(msg, h.Type)
  1478. msg = packClass(msg, h.Class)
  1479. msg = packUint32(msg, h.TTL)
  1480. lenBegin := len(msg)
  1481. msg = packUint16(msg, h.Length)
  1482. return msg, msg[lenBegin : lenBegin+uint16Len], nil
  1483. }
  1484. func (h *ResourceHeader) unpack(msg []byte, off int) (int, error) {
  1485. newOff := off
  1486. var err error
  1487. if newOff, err = h.Name.unpack(msg, newOff); err != nil {
  1488. return off, &nestedError{"Name", err}
  1489. }
  1490. if h.Type, newOff, err = unpackType(msg, newOff); err != nil {
  1491. return off, &nestedError{"Type", err}
  1492. }
  1493. if h.Class, newOff, err = unpackClass(msg, newOff); err != nil {
  1494. return off, &nestedError{"Class", err}
  1495. }
  1496. if h.TTL, newOff, err = unpackUint32(msg, newOff); err != nil {
  1497. return off, &nestedError{"TTL", err}
  1498. }
  1499. if h.Length, newOff, err = unpackUint16(msg, newOff); err != nil {
  1500. return off, &nestedError{"Length", err}
  1501. }
  1502. return newOff, nil
  1503. }
  1504. func (h *ResourceHeader) fixLen(msg []byte, length []byte, preLen int) error {
  1505. conLen := len(msg) - preLen
  1506. if conLen > int(^uint16(0)) {
  1507. return errResTooLong
  1508. }
  1509. // Fill in the length now that we know how long the content is.
  1510. packUint16(length[:0], uint16(conLen))
  1511. h.Length = uint16(conLen)
  1512. return nil
  1513. }
  1514. // EDNS(0) wire costants.
  1515. const (
  1516. edns0Version = 0
  1517. edns0DNSSECOK = 0x00008000
  1518. ednsVersionMask = 0x00ff0000
  1519. edns0DNSSECOKMask = 0x00ff8000
  1520. )
  1521. // SetEDNS0 configures h for EDNS(0).
  1522. //
  1523. // The provided extRCode must be an extedned RCode.
  1524. func (h *ResourceHeader) SetEDNS0(udpPayloadLen int, extRCode RCode, dnssecOK bool) error {
  1525. h.Name = Name{Data: [nameLen]byte{'.'}, Length: 1} // RFC 6891 section 6.1.2
  1526. h.Type = TypeOPT
  1527. h.Class = Class(udpPayloadLen)
  1528. h.TTL = uint32(extRCode) >> 4 << 24
  1529. if dnssecOK {
  1530. h.TTL |= edns0DNSSECOK
  1531. }
  1532. return nil
  1533. }
  1534. // DNSSECAllowed reports whether the DNSSEC OK bit is set.
  1535. func (h *ResourceHeader) DNSSECAllowed() bool {
  1536. return h.TTL&edns0DNSSECOKMask == edns0DNSSECOK // RFC 6891 section 6.1.3
  1537. }
  1538. // ExtendedRCode returns an extended RCode.
  1539. //
  1540. // The provided rcode must be the RCode in DNS message header.
  1541. func (h *ResourceHeader) ExtendedRCode(rcode RCode) RCode {
  1542. if h.TTL&ednsVersionMask == edns0Version { // RFC 6891 section 6.1.3
  1543. return RCode(h.TTL>>24<<4) | rcode
  1544. }
  1545. return rcode
  1546. }
  1547. func skipResource(msg []byte, off int) (int, error) {
  1548. newOff, err := skipName(msg, off)
  1549. if err != nil {
  1550. return off, &nestedError{"Name", err}
  1551. }
  1552. if newOff, err = skipType(msg, newOff); err != nil {
  1553. return off, &nestedError{"Type", err}
  1554. }
  1555. if newOff, err = skipClass(msg, newOff); err != nil {
  1556. return off, &nestedError{"Class", err}
  1557. }
  1558. if newOff, err = skipUint32(msg, newOff); err != nil {
  1559. return off, &nestedError{"TTL", err}
  1560. }
  1561. length, newOff, err := unpackUint16(msg, newOff)
  1562. if err != nil {
  1563. return off, &nestedError{"Length", err}
  1564. }
  1565. if newOff += int(length); newOff > len(msg) {
  1566. return off, errResourceLen
  1567. }
  1568. return newOff, nil
  1569. }
  1570. // packUint16 appends the wire format of field to msg.
  1571. func packUint16(msg []byte, field uint16) []byte {
  1572. return append(msg, byte(field>>8), byte(field))
  1573. }
  1574. func unpackUint16(msg []byte, off int) (uint16, int, error) {
  1575. if off+uint16Len > len(msg) {
  1576. return 0, off, errBaseLen
  1577. }
  1578. return uint16(msg[off])<<8 | uint16(msg[off+1]), off + uint16Len, nil
  1579. }
  1580. func skipUint16(msg []byte, off int) (int, error) {
  1581. if off+uint16Len > len(msg) {
  1582. return off, errBaseLen
  1583. }
  1584. return off + uint16Len, nil
  1585. }
  1586. // packType appends the wire format of field to msg.
  1587. func packType(msg []byte, field Type) []byte {
  1588. return packUint16(msg, uint16(field))
  1589. }
  1590. func unpackType(msg []byte, off int) (Type, int, error) {
  1591. t, o, err := unpackUint16(msg, off)
  1592. return Type(t), o, err
  1593. }
  1594. func skipType(msg []byte, off int) (int, error) {
  1595. return skipUint16(msg, off)
  1596. }
  1597. // packClass appends the wire format of field to msg.
  1598. func packClass(msg []byte, field Class) []byte {
  1599. return packUint16(msg, uint16(field))
  1600. }
  1601. func unpackClass(msg []byte, off int) (Class, int, error) {
  1602. c, o, err := unpackUint16(msg, off)
  1603. return Class(c), o, err
  1604. }
  1605. func skipClass(msg []byte, off int) (int, error) {
  1606. return skipUint16(msg, off)
  1607. }
  1608. // packUint32 appends the wire format of field to msg.
  1609. func packUint32(msg []byte, field uint32) []byte {
  1610. return append(
  1611. msg,
  1612. byte(field>>24),
  1613. byte(field>>16),
  1614. byte(field>>8),
  1615. byte(field),
  1616. )
  1617. }
  1618. func unpackUint32(msg []byte, off int) (uint32, int, error) {
  1619. if off+uint32Len > len(msg) {
  1620. return 0, off, errBaseLen
  1621. }
  1622. v := uint32(msg[off])<<24 | uint32(msg[off+1])<<16 | uint32(msg[off+2])<<8 | uint32(msg[off+3])
  1623. return v, off + uint32Len, nil
  1624. }
  1625. func skipUint32(msg []byte, off int) (int, error) {
  1626. if off+uint32Len > len(msg) {
  1627. return off, errBaseLen
  1628. }
  1629. return off + uint32Len, nil
  1630. }
  1631. // packText appends the wire format of field to msg.
  1632. func packText(msg []byte, field string) ([]byte, error) {
  1633. l := len(field)
  1634. if l > 255 {
  1635. return nil, errStringTooLong
  1636. }
  1637. msg = append(msg, byte(l))
  1638. msg = append(msg, field...)
  1639. return msg, nil
  1640. }
  1641. func unpackText(msg []byte, off int) (string, int, error) {
  1642. if off >= len(msg) {
  1643. return "", off, errBaseLen
  1644. }
  1645. beginOff := off + 1
  1646. endOff := beginOff + int(msg[off])
  1647. if endOff > len(msg) {
  1648. return "", off, errCalcLen
  1649. }
  1650. return string(msg[beginOff:endOff]), endOff, nil
  1651. }
  1652. func skipText(msg []byte, off int) (int, error) {
  1653. if off >= len(msg) {
  1654. return off, errBaseLen
  1655. }
  1656. endOff := off + 1 + int(msg[off])
  1657. if endOff > len(msg) {
  1658. return off, errCalcLen
  1659. }
  1660. return endOff, nil
  1661. }
  1662. // packBytes appends the wire format of field to msg.
  1663. func packBytes(msg []byte, field []byte) []byte {
  1664. return append(msg, field...)
  1665. }
  1666. func unpackBytes(msg []byte, off int, field []byte) (int, error) {
  1667. newOff := off + len(field)
  1668. if newOff > len(msg) {
  1669. return off, errBaseLen
  1670. }
  1671. copy(field, msg[off:newOff])
  1672. return newOff, nil
  1673. }
  1674. func skipBytes(msg []byte, off int, field []byte) (int, error) {
  1675. newOff := off + len(field)
  1676. if newOff > len(msg) {
  1677. return off, errBaseLen
  1678. }
  1679. return newOff, nil
  1680. }
  1681. const nameLen = 255
  1682. // A Name is a non-encoded domain name. It is used instead of strings to avoid
  1683. // allocations.
  1684. type Name struct {
  1685. Data [nameLen]byte
  1686. Length uint8
  1687. }
  1688. // NewName creates a new Name from a string.
  1689. func NewName(name string) (Name, error) {
  1690. if len([]byte(name)) > nameLen {
  1691. return Name{}, errCalcLen
  1692. }
  1693. n := Name{Length: uint8(len(name))}
  1694. copy(n.Data[:], []byte(name))
  1695. return n, nil
  1696. }
  1697. // MustNewName creates a new Name from a string and panics on error.
  1698. func MustNewName(name string) Name {
  1699. n, err := NewName(name)
  1700. if err != nil {
  1701. panic("creating name: " + err.Error())
  1702. }
  1703. return n
  1704. }
  1705. // String implements fmt.Stringer.String.
  1706. func (n Name) String() string {
  1707. return string(n.Data[:n.Length])
  1708. }
  1709. // GoString implements fmt.GoStringer.GoString.
  1710. func (n *Name) GoString() string {
  1711. return `dnsmessage.MustNewName("` + printString(n.Data[:n.Length]) + `")`
  1712. }
  1713. // pack appends the wire format of the Name to msg.
  1714. //
  1715. // Domain names are a sequence of counted strings split at the dots. They end
  1716. // with a zero-length string. Compression can be used to reuse domain suffixes.
  1717. //
  1718. // The compression map will be updated with new domain suffixes. If compression
  1719. // is nil, compression will not be used.
  1720. func (n *Name) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) {
  1721. oldMsg := msg
  1722. // Add a trailing dot to canonicalize name.
  1723. if n.Length == 0 || n.Data[n.Length-1] != '.' {
  1724. return oldMsg, errNonCanonicalName
  1725. }
  1726. // Allow root domain.
  1727. if n.Data[0] == '.' && n.Length == 1 {
  1728. return append(msg, 0), nil
  1729. }
  1730. // Emit sequence of counted strings, chopping at dots.
  1731. for i, begin := 0, 0; i < int(n.Length); i++ {
  1732. // Check for the end of the segment.
  1733. if n.Data[i] == '.' {
  1734. // The two most significant bits have special meaning.
  1735. // It isn't allowed for segments to be long enough to
  1736. // need them.
  1737. if i-begin >= 1<<6 {
  1738. return oldMsg, errSegTooLong
  1739. }
  1740. // Segments must have a non-zero length.
  1741. if i-begin == 0 {
  1742. return oldMsg, errZeroSegLen
  1743. }
  1744. msg = append(msg, byte(i-begin))
  1745. for j := begin; j < i; j++ {
  1746. msg = append(msg, n.Data[j])
  1747. }
  1748. begin = i + 1
  1749. continue
  1750. }
  1751. // We can only compress domain suffixes starting with a new
  1752. // segment. A pointer is two bytes with the two most significant
  1753. // bits set to 1 to indicate that it is a pointer.
  1754. if (i == 0 || n.Data[i-1] == '.') && compression != nil {
  1755. if ptr, ok := compression[string(n.Data[i:])]; ok {
  1756. // Hit. Emit a pointer instead of the rest of
  1757. // the domain.
  1758. return append(msg, byte(ptr>>8|0xC0), byte(ptr)), nil
  1759. }
  1760. // Miss. Add the suffix to the compression table if the
  1761. // offset can be stored in the available 14 bytes.
  1762. if len(msg) <= int(^uint16(0)>>2) {
  1763. compression[string(n.Data[i:])] = len(msg) - compressionOff
  1764. }
  1765. }
  1766. }
  1767. return append(msg, 0), nil
  1768. }
  1769. // unpack unpacks a domain name.
  1770. func (n *Name) unpack(msg []byte, off int) (int, error) {
  1771. return n.unpackCompressed(msg, off, true /* allowCompression */)
  1772. }
  1773. func (n *Name) unpackCompressed(msg []byte, off int, allowCompression bool) (int, error) {
  1774. // currOff is the current working offset.
  1775. currOff := off
  1776. // newOff is the offset where the next record will start. Pointers lead
  1777. // to data that belongs to other names and thus doesn't count towards to
  1778. // the usage of this name.
  1779. newOff := off
  1780. // ptr is the number of pointers followed.
  1781. var ptr int
  1782. // Name is a slice representation of the name data.
  1783. name := n.Data[:0]
  1784. Loop:
  1785. for {
  1786. if currOff >= len(msg) {
  1787. return off, errBaseLen
  1788. }
  1789. c := int(msg[currOff])
  1790. currOff++
  1791. switch c & 0xC0 {
  1792. case 0x00: // String segment
  1793. if c == 0x00 {
  1794. // A zero length signals the end of the name.
  1795. break Loop
  1796. }
  1797. endOff := currOff + c
  1798. if endOff > len(msg) {
  1799. return off, errCalcLen
  1800. }
  1801. name = append(name, msg[currOff:endOff]...)
  1802. name = append(name, '.')
  1803. currOff = endOff
  1804. case 0xC0: // Pointer
  1805. if !allowCompression {
  1806. return off, errCompressedSRV
  1807. }
  1808. if currOff >= len(msg) {
  1809. return off, errInvalidPtr
  1810. }
  1811. c1 := msg[currOff]
  1812. currOff++
  1813. if ptr == 0 {
  1814. newOff = currOff
  1815. }
  1816. // Don't follow too many pointers, maybe there's a loop.
  1817. if ptr++; ptr > 10 {
  1818. return off, errTooManyPtr
  1819. }
  1820. currOff = (c^0xC0)<<8 | int(c1)
  1821. default:
  1822. // Prefixes 0x80 and 0x40 are reserved.
  1823. return off, errReserved
  1824. }
  1825. }
  1826. if len(name) == 0 {
  1827. name = append(name, '.')
  1828. }
  1829. if len(name) > len(n.Data) {
  1830. return off, errCalcLen
  1831. }
  1832. n.Length = uint8(len(name))
  1833. if ptr == 0 {
  1834. newOff = currOff
  1835. }
  1836. return newOff, nil
  1837. }
  1838. func skipName(msg []byte, off int) (int, error) {
  1839. // newOff is the offset where the next record will start. Pointers lead
  1840. // to data that belongs to other names and thus doesn't count towards to
  1841. // the usage of this name.
  1842. newOff := off
  1843. Loop:
  1844. for {
  1845. if newOff >= len(msg) {
  1846. return off, errBaseLen
  1847. }
  1848. c := int(msg[newOff])
  1849. newOff++
  1850. switch c & 0xC0 {
  1851. case 0x00:
  1852. if c == 0x00 {
  1853. // A zero length signals the end of the name.
  1854. break Loop
  1855. }
  1856. // literal string
  1857. newOff += c
  1858. if newOff > len(msg) {
  1859. return off, errCalcLen
  1860. }
  1861. case 0xC0:
  1862. // Pointer to somewhere else in msg.
  1863. // Pointers are two bytes.
  1864. newOff++
  1865. // Don't follow the pointer as the data here has ended.
  1866. break Loop
  1867. default:
  1868. // Prefixes 0x80 and 0x40 are reserved.
  1869. return off, errReserved
  1870. }
  1871. }
  1872. return newOff, nil
  1873. }
  1874. // A Question is a DNS query.
  1875. type Question struct {
  1876. Name Name
  1877. Type Type
  1878. Class Class
  1879. }
  1880. // pack appends the wire format of the Question to msg.
  1881. func (q *Question) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) {
  1882. msg, err := q.Name.pack(msg, compression, compressionOff)
  1883. if err != nil {
  1884. return msg, &nestedError{"Name", err}
  1885. }
  1886. msg = packType(msg, q.Type)
  1887. return packClass(msg, q.Class), nil
  1888. }
  1889. // GoString implements fmt.GoStringer.GoString.
  1890. func (q *Question) GoString() string {
  1891. return "dnsmessage.Question{" +
  1892. "Name: " + q.Name.GoString() + ", " +
  1893. "Type: " + q.Type.GoString() + ", " +
  1894. "Class: " + q.Class.GoString() + "}"
  1895. }
  1896. func unpackResourceBody(msg []byte, off int, hdr ResourceHeader) (ResourceBody, int, error) {
  1897. var (
  1898. r ResourceBody
  1899. err error
  1900. name string
  1901. )
  1902. switch hdr.Type {
  1903. case TypeA:
  1904. var rb AResource
  1905. rb, err = unpackAResource(msg, off)
  1906. r = &rb
  1907. name = "A"
  1908. case TypeNS:
  1909. var rb NSResource
  1910. rb, err = unpackNSResource(msg, off)
  1911. r = &rb
  1912. name = "NS"
  1913. case TypeCNAME:
  1914. var rb CNAMEResource
  1915. rb, err = unpackCNAMEResource(msg, off)
  1916. r = &rb
  1917. name = "CNAME"
  1918. case TypeSOA:
  1919. var rb SOAResource
  1920. rb, err = unpackSOAResource(msg, off)
  1921. r = &rb
  1922. name = "SOA"
  1923. case TypePTR:
  1924. var rb PTRResource
  1925. rb, err = unpackPTRResource(msg, off)
  1926. r = &rb
  1927. name = "PTR"
  1928. case TypeMX:
  1929. var rb MXResource
  1930. rb, err = unpackMXResource(msg, off)
  1931. r = &rb
  1932. name = "MX"
  1933. case TypeTXT:
  1934. var rb TXTResource
  1935. rb, err = unpackTXTResource(msg, off, hdr.Length)
  1936. r = &rb
  1937. name = "TXT"
  1938. case TypeAAAA:
  1939. var rb AAAAResource
  1940. rb, err = unpackAAAAResource(msg, off)
  1941. r = &rb
  1942. name = "AAAA"
  1943. case TypeSRV:
  1944. var rb SRVResource
  1945. rb, err = unpackSRVResource(msg, off)
  1946. r = &rb
  1947. name = "SRV"
  1948. case TypeOPT:
  1949. var rb OPTResource
  1950. rb, err = unpackOPTResource(msg, off, hdr.Length)
  1951. r = &rb
  1952. name = "OPT"
  1953. }
  1954. if err != nil {
  1955. return nil, off, &nestedError{name + " record", err}
  1956. }
  1957. if r == nil {
  1958. return nil, off, errors.New("invalid resource type: " + string(hdr.Type+'0'))
  1959. }
  1960. return r, off + int(hdr.Length), nil
  1961. }
  1962. // A CNAMEResource is a CNAME Resource record.
  1963. type CNAMEResource struct {
  1964. CNAME Name
  1965. }
  1966. func (r *CNAMEResource) realType() Type {
  1967. return TypeCNAME
  1968. }
  1969. // pack appends the wire format of the CNAMEResource to msg.
  1970. func (r *CNAMEResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) {
  1971. return r.CNAME.pack(msg, compression, compressionOff)
  1972. }
  1973. // GoString implements fmt.GoStringer.GoString.
  1974. func (r *CNAMEResource) GoString() string {
  1975. return "dnsmessage.CNAMEResource{CNAME: " + r.CNAME.GoString() + "}"
  1976. }
  1977. func unpackCNAMEResource(msg []byte, off int) (CNAMEResource, error) {
  1978. var cname Name
  1979. if _, err := cname.unpack(msg, off); err != nil {
  1980. return CNAMEResource{}, err
  1981. }
  1982. return CNAMEResource{cname}, nil
  1983. }
  1984. // An MXResource is an MX Resource record.
  1985. type MXResource struct {
  1986. Pref uint16
  1987. MX Name
  1988. }
  1989. func (r *MXResource) realType() Type {
  1990. return TypeMX
  1991. }
  1992. // pack appends the wire format of the MXResource to msg.
  1993. func (r *MXResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) {
  1994. oldMsg := msg
  1995. msg = packUint16(msg, r.Pref)
  1996. msg, err := r.MX.pack(msg, compression, compressionOff)
  1997. if err != nil {
  1998. return oldMsg, &nestedError{"MXResource.MX", err}
  1999. }
  2000. return msg, nil
  2001. }
  2002. // GoString implements fmt.GoStringer.GoString.
  2003. func (r *MXResource) GoString() string {
  2004. return "dnsmessage.MXResource{" +
  2005. "Pref: " + printUint16(r.Pref) + ", " +
  2006. "MX: " + r.MX.GoString() + "}"
  2007. }
  2008. func unpackMXResource(msg []byte, off int) (MXResource, error) {
  2009. pref, off, err := unpackUint16(msg, off)
  2010. if err != nil {
  2011. return MXResource{}, &nestedError{"Pref", err}
  2012. }
  2013. var mx Name
  2014. if _, err := mx.unpack(msg, off); err != nil {
  2015. return MXResource{}, &nestedError{"MX", err}
  2016. }
  2017. return MXResource{pref, mx}, nil
  2018. }
  2019. // An NSResource is an NS Resource record.
  2020. type NSResource struct {
  2021. NS Name
  2022. }
  2023. func (r *NSResource) realType() Type {
  2024. return TypeNS
  2025. }
  2026. // pack appends the wire format of the NSResource to msg.
  2027. func (r *NSResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) {
  2028. return r.NS.pack(msg, compression, compressionOff)
  2029. }
  2030. // GoString implements fmt.GoStringer.GoString.
  2031. func (r *NSResource) GoString() string {
  2032. return "dnsmessage.NSResource{NS: " + r.NS.GoString() + "}"
  2033. }
  2034. func unpackNSResource(msg []byte, off int) (NSResource, error) {
  2035. var ns Name
  2036. if _, err := ns.unpack(msg, off); err != nil {
  2037. return NSResource{}, err
  2038. }
  2039. return NSResource{ns}, nil
  2040. }
  2041. // A PTRResource is a PTR Resource record.
  2042. type PTRResource struct {
  2043. PTR Name
  2044. }
  2045. func (r *PTRResource) realType() Type {
  2046. return TypePTR
  2047. }
  2048. // pack appends the wire format of the PTRResource to msg.
  2049. func (r *PTRResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) {
  2050. return r.PTR.pack(msg, compression, compressionOff)
  2051. }
  2052. // GoString implements fmt.GoStringer.GoString.
  2053. func (r *PTRResource) GoString() string {
  2054. return "dnsmessage.PTRResource{PTR: " + r.PTR.GoString() + "}"
  2055. }
  2056. func unpackPTRResource(msg []byte, off int) (PTRResource, error) {
  2057. var ptr Name
  2058. if _, err := ptr.unpack(msg, off); err != nil {
  2059. return PTRResource{}, err
  2060. }
  2061. return PTRResource{ptr}, nil
  2062. }
  2063. // An SOAResource is an SOA Resource record.
  2064. type SOAResource struct {
  2065. NS Name
  2066. MBox Name
  2067. Serial uint32
  2068. Refresh uint32
  2069. Retry uint32
  2070. Expire uint32
  2071. // MinTTL the is the default TTL of Resources records which did not
  2072. // contain a TTL value and the TTL of negative responses. (RFC 2308
  2073. // Section 4)
  2074. MinTTL uint32
  2075. }
  2076. func (r *SOAResource) realType() Type {
  2077. return TypeSOA
  2078. }
  2079. // pack appends the wire format of the SOAResource to msg.
  2080. func (r *SOAResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) {
  2081. oldMsg := msg
  2082. msg, err := r.NS.pack(msg, compression, compressionOff)
  2083. if err != nil {
  2084. return oldMsg, &nestedError{"SOAResource.NS", err}
  2085. }
  2086. msg, err = r.MBox.pack(msg, compression, compressionOff)
  2087. if err != nil {
  2088. return oldMsg, &nestedError{"SOAResource.MBox", err}
  2089. }
  2090. msg = packUint32(msg, r.Serial)
  2091. msg = packUint32(msg, r.Refresh)
  2092. msg = packUint32(msg, r.Retry)
  2093. msg = packUint32(msg, r.Expire)
  2094. return packUint32(msg, r.MinTTL), nil
  2095. }
  2096. // GoString implements fmt.GoStringer.GoString.
  2097. func (r *SOAResource) GoString() string {
  2098. return "dnsmessage.SOAResource{" +
  2099. "NS: " + r.NS.GoString() + ", " +
  2100. "MBox: " + r.MBox.GoString() + ", " +
  2101. "Serial: " + printUint32(r.Serial) + ", " +
  2102. "Refresh: " + printUint32(r.Refresh) + ", " +
  2103. "Retry: " + printUint32(r.Retry) + ", " +
  2104. "Expire: " + printUint32(r.Expire) + ", " +
  2105. "MinTTL: " + printUint32(r.MinTTL) + "}"
  2106. }
  2107. func unpackSOAResource(msg []byte, off int) (SOAResource, error) {
  2108. var ns Name
  2109. off, err := ns.unpack(msg, off)
  2110. if err != nil {
  2111. return SOAResource{}, &nestedError{"NS", err}
  2112. }
  2113. var mbox Name
  2114. if off, err = mbox.unpack(msg, off); err != nil {
  2115. return SOAResource{}, &nestedError{"MBox", err}
  2116. }
  2117. serial, off, err := unpackUint32(msg, off)
  2118. if err != nil {
  2119. return SOAResource{}, &nestedError{"Serial", err}
  2120. }
  2121. refresh, off, err := unpackUint32(msg, off)
  2122. if err != nil {
  2123. return SOAResource{}, &nestedError{"Refresh", err}
  2124. }
  2125. retry, off, err := unpackUint32(msg, off)
  2126. if err != nil {
  2127. return SOAResource{}, &nestedError{"Retry", err}
  2128. }
  2129. expire, off, err := unpackUint32(msg, off)
  2130. if err != nil {
  2131. return SOAResource{}, &nestedError{"Expire", err}
  2132. }
  2133. minTTL, _, err := unpackUint32(msg, off)
  2134. if err != nil {
  2135. return SOAResource{}, &nestedError{"MinTTL", err}
  2136. }
  2137. return SOAResource{ns, mbox, serial, refresh, retry, expire, minTTL}, nil
  2138. }
  2139. // A TXTResource is a TXT Resource record.
  2140. type TXTResource struct {
  2141. TXT []string
  2142. }
  2143. func (r *TXTResource) realType() Type {
  2144. return TypeTXT
  2145. }
  2146. // pack appends the wire format of the TXTResource to msg.
  2147. func (r *TXTResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) {
  2148. oldMsg := msg
  2149. for _, s := range r.TXT {
  2150. var err error
  2151. msg, err = packText(msg, s)
  2152. if err != nil {
  2153. return oldMsg, err
  2154. }
  2155. }
  2156. return msg, nil
  2157. }
  2158. // GoString implements fmt.GoStringer.GoString.
  2159. func (r *TXTResource) GoString() string {
  2160. s := "dnsmessage.TXTResource{TXT: []string{"
  2161. if len(r.TXT) == 0 {
  2162. return s + "}}"
  2163. }
  2164. s += `"` + printString([]byte(r.TXT[0]))
  2165. for _, t := range r.TXT[1:] {
  2166. s += `", "` + printString([]byte(t))
  2167. }
  2168. return s + `"}}`
  2169. }
  2170. func unpackTXTResource(msg []byte, off int, length uint16) (TXTResource, error) {
  2171. txts := make([]string, 0, 1)
  2172. for n := uint16(0); n < length; {
  2173. var t string
  2174. var err error
  2175. if t, off, err = unpackText(msg, off); err != nil {
  2176. return TXTResource{}, &nestedError{"text", err}
  2177. }
  2178. // Check if we got too many bytes.
  2179. if length-n < uint16(len(t))+1 {
  2180. return TXTResource{}, errCalcLen
  2181. }
  2182. n += uint16(len(t)) + 1
  2183. txts = append(txts, t)
  2184. }
  2185. return TXTResource{txts}, nil
  2186. }
  2187. // An SRVResource is an SRV Resource record.
  2188. type SRVResource struct {
  2189. Priority uint16
  2190. Weight uint16
  2191. Port uint16
  2192. Target Name // Not compressed as per RFC 2782.
  2193. }
  2194. func (r *SRVResource) realType() Type {
  2195. return TypeSRV
  2196. }
  2197. // pack appends the wire format of the SRVResource to msg.
  2198. func (r *SRVResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) {
  2199. oldMsg := msg
  2200. msg = packUint16(msg, r.Priority)
  2201. msg = packUint16(msg, r.Weight)
  2202. msg = packUint16(msg, r.Port)
  2203. msg, err := r.Target.pack(msg, nil, compressionOff)
  2204. if err != nil {
  2205. return oldMsg, &nestedError{"SRVResource.Target", err}
  2206. }
  2207. return msg, nil
  2208. }
  2209. // GoString implements fmt.GoStringer.GoString.
  2210. func (r *SRVResource) GoString() string {
  2211. return "dnsmessage.SRVResource{" +
  2212. "Priority: " + printUint16(r.Priority) + ", " +
  2213. "Weight: " + printUint16(r.Weight) + ", " +
  2214. "Port: " + printUint16(r.Port) + ", " +
  2215. "Target: " + r.Target.GoString() + "}"
  2216. }
  2217. func unpackSRVResource(msg []byte, off int) (SRVResource, error) {
  2218. priority, off, err := unpackUint16(msg, off)
  2219. if err != nil {
  2220. return SRVResource{}, &nestedError{"Priority", err}
  2221. }
  2222. weight, off, err := unpackUint16(msg, off)
  2223. if err != nil {
  2224. return SRVResource{}, &nestedError{"Weight", err}
  2225. }
  2226. port, off, err := unpackUint16(msg, off)
  2227. if err != nil {
  2228. return SRVResource{}, &nestedError{"Port", err}
  2229. }
  2230. var target Name
  2231. if _, err := target.unpackCompressed(msg, off, false /* allowCompression */); err != nil {
  2232. return SRVResource{}, &nestedError{"Target", err}
  2233. }
  2234. return SRVResource{priority, weight, port, target}, nil
  2235. }
  2236. // An AResource is an A Resource record.
  2237. type AResource struct {
  2238. A [4]byte
  2239. }
  2240. func (r *AResource) realType() Type {
  2241. return TypeA
  2242. }
  2243. // pack appends the wire format of the AResource to msg.
  2244. func (r *AResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) {
  2245. return packBytes(msg, r.A[:]), nil
  2246. }
  2247. // GoString implements fmt.GoStringer.GoString.
  2248. func (r *AResource) GoString() string {
  2249. return "dnsmessage.AResource{" +
  2250. "A: [4]byte{" + printByteSlice(r.A[:]) + "}}"
  2251. }
  2252. func unpackAResource(msg []byte, off int) (AResource, error) {
  2253. var a [4]byte
  2254. if _, err := unpackBytes(msg, off, a[:]); err != nil {
  2255. return AResource{}, err
  2256. }
  2257. return AResource{a}, nil
  2258. }
  2259. // An AAAAResource is an AAAA Resource record.
  2260. type AAAAResource struct {
  2261. AAAA [16]byte
  2262. }
  2263. func (r *AAAAResource) realType() Type {
  2264. return TypeAAAA
  2265. }
  2266. // GoString implements fmt.GoStringer.GoString.
  2267. func (r *AAAAResource) GoString() string {
  2268. return "dnsmessage.AAAAResource{" +
  2269. "AAAA: [16]byte{" + printByteSlice(r.AAAA[:]) + "}}"
  2270. }
  2271. // pack appends the wire format of the AAAAResource to msg.
  2272. func (r *AAAAResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) {
  2273. return packBytes(msg, r.AAAA[:]), nil
  2274. }
  2275. func unpackAAAAResource(msg []byte, off int) (AAAAResource, error) {
  2276. var aaaa [16]byte
  2277. if _, err := unpackBytes(msg, off, aaaa[:]); err != nil {
  2278. return AAAAResource{}, err
  2279. }
  2280. return AAAAResource{aaaa}, nil
  2281. }
  2282. // An OPTResource is an OPT pseudo Resource record.
  2283. //
  2284. // The pseudo resource record is part of the extension mechanisms for DNS
  2285. // as defined in RFC 6891.
  2286. type OPTResource struct {
  2287. Options []Option
  2288. }
  2289. // An Option represents a DNS message option within OPTResource.
  2290. //
  2291. // The message option is part of the extension mechanisms for DNS as
  2292. // defined in RFC 6891.
  2293. type Option struct {
  2294. Code uint16 // option code
  2295. Data []byte
  2296. }
  2297. // GoString implements fmt.GoStringer.GoString.
  2298. func (o *Option) GoString() string {
  2299. return "dnsmessage.Option{" +
  2300. "Code: " + printUint16(o.Code) + ", " +
  2301. "Data: []byte{" + printByteSlice(o.Data) + "}}"
  2302. }
  2303. func (r *OPTResource) realType() Type {
  2304. return TypeOPT
  2305. }
  2306. func (r *OPTResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) {
  2307. for _, opt := range r.Options {
  2308. msg = packUint16(msg, opt.Code)
  2309. l := uint16(len(opt.Data))
  2310. msg = packUint16(msg, l)
  2311. msg = packBytes(msg, opt.Data)
  2312. }
  2313. return msg, nil
  2314. }
  2315. // GoString implements fmt.GoStringer.GoString.
  2316. func (r *OPTResource) GoString() string {
  2317. s := "dnsmessage.OPTResource{Options: []dnsmessage.Option{"
  2318. if len(r.Options) == 0 {
  2319. return s + "}}"
  2320. }
  2321. s += r.Options[0].GoString()
  2322. for _, o := range r.Options[1:] {
  2323. s += ", " + o.GoString()
  2324. }
  2325. return s + "}}"
  2326. }
  2327. func unpackOPTResource(msg []byte, off int, length uint16) (OPTResource, error) {
  2328. var opts []Option
  2329. for oldOff := off; off < oldOff+int(length); {
  2330. var err error
  2331. var o Option
  2332. o.Code, off, err = unpackUint16(msg, off)
  2333. if err != nil {
  2334. return OPTResource{}, &nestedError{"Code", err}
  2335. }
  2336. var l uint16
  2337. l, off, err = unpackUint16(msg, off)
  2338. if err != nil {
  2339. return OPTResource{}, &nestedError{"Data", err}
  2340. }
  2341. o.Data = make([]byte, l)
  2342. if copy(o.Data, msg[off:]) != int(l) {
  2343. return OPTResource{}, &nestedError{"Data", errCalcLen}
  2344. }
  2345. off += int(l)
  2346. opts = append(opts, o)
  2347. }
  2348. return OPTResource{opts}, nil
  2349. }