msg.go 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945
  1. // DNS packet assembly, see RFC 1035. Converting from - Unpack() -
  2. // and to - Pack() - wire format.
  3. // All the packers and unpackers take a (msg []byte, off int)
  4. // and return (off1 int, ok bool). If they return ok==false, they
  5. // also return off1==len(msg), so that the next unpacker will
  6. // also fail. This lets us avoid checks of ok until the end of a
  7. // packing sequence.
  8. package dns
  9. import (
  10. "encoding/base32"
  11. "encoding/base64"
  12. "encoding/hex"
  13. "math/big"
  14. "math/rand"
  15. "net"
  16. "reflect"
  17. "strconv"
  18. "time"
  19. )
  20. const maxCompressionOffset = 2 << 13 // We have 14 bits for the compression pointer
  21. var (
  22. // ErrAlg indicates an error with the (DNSSEC) algorithm.
  23. ErrAlg error = &Error{err: "bad algorithm"}
  24. // ErrAuth indicates an error in the TSIG authentication.
  25. ErrAuth error = &Error{err: "bad authentication"}
  26. // ErrBuf indicates that the buffer used it too small for the message.
  27. ErrBuf error = &Error{err: "buffer size too small"}
  28. // ErrConnEmpty indicates a connection is being uses before it is initialized.
  29. ErrConnEmpty error = &Error{err: "conn has no connection"}
  30. // ErrExtendedRcode ...
  31. ErrExtendedRcode error = &Error{err: "bad extended rcode"}
  32. // ErrFqdn indicates that a domain name does not have a closing dot.
  33. ErrFqdn error = &Error{err: "domain must be fully qualified"}
  34. // ErrId indicates there is a mismatch with the message's ID.
  35. ErrId error = &Error{err: "id mismatch"}
  36. // ErrKeyAlg indicates that the algorithm in the key is not valid.
  37. ErrKeyAlg error = &Error{err: "bad key algorithm"}
  38. ErrKey error = &Error{err: "bad key"}
  39. ErrKeySize error = &Error{err: "bad key size"}
  40. ErrNoSig error = &Error{err: "no signature found"}
  41. ErrPrivKey error = &Error{err: "bad private key"}
  42. ErrRcode error = &Error{err: "bad rcode"}
  43. ErrRdata error = &Error{err: "bad rdata"}
  44. ErrRRset error = &Error{err: "bad rrset"}
  45. ErrSecret error = &Error{err: "no secrets defined"}
  46. ErrShortRead error = &Error{err: "short read"}
  47. // ErrSig indicates that a signature can not be cryptographically validated.
  48. ErrSig error = &Error{err: "bad signature"}
  49. // ErrSOA indicates that no SOA RR was seen when doing zone transfers.
  50. ErrSoa error = &Error{err: "no SOA"}
  51. // ErrTime indicates a timing error in TSIG authentication.
  52. ErrTime error = &Error{err: "bad time"}
  53. // ErrTruncated indicates that we failed to unpack a truncated message.
  54. // We unpacked as much as we had so Msg can still be used, if desired.
  55. ErrTruncated error = &Error{err: "failed to unpack truncated message"}
  56. )
  57. // Id, by default, returns a 16 bits random number to be used as a
  58. // message id. The random provided should be good enough. This being a
  59. // variable the function can be reassigned to a custom function.
  60. // For instance, to make it return a static value:
  61. //
  62. // dns.Id = func() uint16 { return 3 }
  63. var Id func() uint16 = id
  64. // MsgHdr is a a manually-unpacked version of (id, bits).
  65. type MsgHdr struct {
  66. Id uint16
  67. Response bool
  68. Opcode int
  69. Authoritative bool
  70. Truncated bool
  71. RecursionDesired bool
  72. RecursionAvailable bool
  73. Zero bool
  74. AuthenticatedData bool
  75. CheckingDisabled bool
  76. Rcode int
  77. }
  78. // Msg contains the layout of a DNS message.
  79. type Msg struct {
  80. MsgHdr
  81. Compress bool `json:"-"` // If true, the message will be compressed when converted to wire format. This not part of the official DNS packet format.
  82. Question []Question // Holds the RR(s) of the question section.
  83. Answer []RR // Holds the RR(s) of the answer section.
  84. Ns []RR // Holds the RR(s) of the authority section.
  85. Extra []RR // Holds the RR(s) of the additional section.
  86. }
  87. // StringToType is the reverse of TypeToString, needed for string parsing.
  88. var StringToType = reverseInt16(TypeToString)
  89. // StringToClass is the reverse of ClassToString, needed for string parsing.
  90. var StringToClass = reverseInt16(ClassToString)
  91. // Map of opcodes strings.
  92. var StringToOpcode = reverseInt(OpcodeToString)
  93. // Map of rcodes strings.
  94. var StringToRcode = reverseInt(RcodeToString)
  95. // ClassToString is a maps Classes to strings for each CLASS wire type.
  96. var ClassToString = map[uint16]string{
  97. ClassINET: "IN",
  98. ClassCSNET: "CS",
  99. ClassCHAOS: "CH",
  100. ClassHESIOD: "HS",
  101. ClassNONE: "NONE",
  102. ClassANY: "ANY",
  103. }
  104. // OpcodeToString maps Opcodes to strings.
  105. var OpcodeToString = map[int]string{
  106. OpcodeQuery: "QUERY",
  107. OpcodeIQuery: "IQUERY",
  108. OpcodeStatus: "STATUS",
  109. OpcodeNotify: "NOTIFY",
  110. OpcodeUpdate: "UPDATE",
  111. }
  112. // RcodeToString maps Rcodes to strings.
  113. var RcodeToString = map[int]string{
  114. RcodeSuccess: "NOERROR",
  115. RcodeFormatError: "FORMERR",
  116. RcodeServerFailure: "SERVFAIL",
  117. RcodeNameError: "NXDOMAIN",
  118. RcodeNotImplemented: "NOTIMPL",
  119. RcodeRefused: "REFUSED",
  120. RcodeYXDomain: "YXDOMAIN", // From RFC 2136
  121. RcodeYXRrset: "YXRRSET",
  122. RcodeNXRrset: "NXRRSET",
  123. RcodeNotAuth: "NOTAUTH",
  124. RcodeNotZone: "NOTZONE",
  125. RcodeBadSig: "BADSIG", // Also known as RcodeBadVers, see RFC 6891
  126. // RcodeBadVers: "BADVERS",
  127. RcodeBadKey: "BADKEY",
  128. RcodeBadTime: "BADTIME",
  129. RcodeBadMode: "BADMODE",
  130. RcodeBadName: "BADNAME",
  131. RcodeBadAlg: "BADALG",
  132. RcodeBadTrunc: "BADTRUNC",
  133. }
  134. // Rather than write the usual handful of routines to pack and
  135. // unpack every message that can appear on the wire, we use
  136. // reflection to write a generic pack/unpack for structs and then
  137. // use it. Thus, if in the future we need to define new message
  138. // structs, no new pack/unpack/printing code needs to be written.
  139. // Domain names are a sequence of counted strings
  140. // split at the dots. They end with a zero-length string.
  141. // PackDomainName packs a domain name s into msg[off:].
  142. // If compression is wanted compress must be true and the compression
  143. // map needs to hold a mapping between domain names and offsets
  144. // pointing into msg.
  145. func PackDomainName(s string, msg []byte, off int, compression map[string]int, compress bool) (off1 int, err error) {
  146. off1, _, err = packDomainName(s, msg, off, compression, compress)
  147. return
  148. }
  149. func packDomainName(s string, msg []byte, off int, compression map[string]int, compress bool) (off1 int, labels int, err error) {
  150. // special case if msg == nil
  151. lenmsg := 256
  152. if msg != nil {
  153. lenmsg = len(msg)
  154. }
  155. ls := len(s)
  156. if ls == 0 { // Ok, for instance when dealing with update RR without any rdata.
  157. return off, 0, nil
  158. }
  159. // If not fully qualified, error out, but only if msg == nil #ugly
  160. switch {
  161. case msg == nil:
  162. if s[ls-1] != '.' {
  163. s += "."
  164. ls++
  165. }
  166. case msg != nil:
  167. if s[ls-1] != '.' {
  168. return lenmsg, 0, ErrFqdn
  169. }
  170. }
  171. // Each dot ends a segment of the name.
  172. // We trade each dot byte for a length byte.
  173. // Except for escaped dots (\.), which are normal dots.
  174. // There is also a trailing zero.
  175. // Compression
  176. nameoffset := -1
  177. pointer := -1
  178. // Emit sequence of counted strings, chopping at dots.
  179. begin := 0
  180. bs := []byte(s)
  181. roBs, bsFresh, escapedDot := s, true, false
  182. for i := 0; i < ls; i++ {
  183. if bs[i] == '\\' {
  184. for j := i; j < ls-1; j++ {
  185. bs[j] = bs[j+1]
  186. }
  187. ls--
  188. if off+1 > lenmsg {
  189. return lenmsg, labels, ErrBuf
  190. }
  191. // check for \DDD
  192. if i+2 < ls && isDigit(bs[i]) && isDigit(bs[i+1]) && isDigit(bs[i+2]) {
  193. bs[i] = dddToByte(bs[i:])
  194. for j := i + 1; j < ls-2; j++ {
  195. bs[j] = bs[j+2]
  196. }
  197. ls -= 2
  198. } else if bs[i] == 't' {
  199. bs[i] = '\t'
  200. } else if bs[i] == 'r' {
  201. bs[i] = '\r'
  202. } else if bs[i] == 'n' {
  203. bs[i] = '\n'
  204. }
  205. escapedDot = bs[i] == '.'
  206. bsFresh = false
  207. continue
  208. }
  209. if bs[i] == '.' {
  210. if i > 0 && bs[i-1] == '.' && !escapedDot {
  211. // two dots back to back is not legal
  212. return lenmsg, labels, ErrRdata
  213. }
  214. if i-begin >= 1<<6 { // top two bits of length must be clear
  215. return lenmsg, labels, ErrRdata
  216. }
  217. // off can already (we're in a loop) be bigger than len(msg)
  218. // this happens when a name isn't fully qualified
  219. if off+1 > lenmsg {
  220. return lenmsg, labels, ErrBuf
  221. }
  222. if msg != nil {
  223. msg[off] = byte(i - begin)
  224. }
  225. offset := off
  226. off++
  227. for j := begin; j < i; j++ {
  228. if off+1 > lenmsg {
  229. return lenmsg, labels, ErrBuf
  230. }
  231. if msg != nil {
  232. msg[off] = bs[j]
  233. }
  234. off++
  235. }
  236. if compress && !bsFresh {
  237. roBs = string(bs)
  238. bsFresh = true
  239. }
  240. // Don't try to compress '.'
  241. if compress && roBs[begin:] != "." {
  242. if p, ok := compression[roBs[begin:]]; !ok {
  243. // Only offsets smaller than this can be used.
  244. if offset < maxCompressionOffset {
  245. compression[roBs[begin:]] = offset
  246. }
  247. } else {
  248. // The first hit is the longest matching dname
  249. // keep the pointer offset we get back and store
  250. // the offset of the current name, because that's
  251. // where we need to insert the pointer later
  252. // If compress is true, we're allowed to compress this dname
  253. if pointer == -1 && compress {
  254. pointer = p // Where to point to
  255. nameoffset = offset // Where to point from
  256. break
  257. }
  258. }
  259. }
  260. labels++
  261. begin = i + 1
  262. }
  263. escapedDot = false
  264. }
  265. // Root label is special
  266. if len(bs) == 1 && bs[0] == '.' {
  267. return off, labels, nil
  268. }
  269. // If we did compression and we find something add the pointer here
  270. if pointer != -1 {
  271. // We have two bytes (14 bits) to put the pointer in
  272. // if msg == nil, we will never do compression
  273. msg[nameoffset], msg[nameoffset+1] = packUint16(uint16(pointer ^ 0xC000))
  274. off = nameoffset + 1
  275. goto End
  276. }
  277. if msg != nil {
  278. msg[off] = 0
  279. }
  280. End:
  281. off++
  282. return off, labels, nil
  283. }
  284. // Unpack a domain name.
  285. // In addition to the simple sequences of counted strings above,
  286. // domain names are allowed to refer to strings elsewhere in the
  287. // packet, to avoid repeating common suffixes when returning
  288. // many entries in a single domain. The pointers are marked
  289. // by a length byte with the top two bits set. Ignoring those
  290. // two bits, that byte and the next give a 14 bit offset from msg[0]
  291. // where we should pick up the trail.
  292. // Note that if we jump elsewhere in the packet,
  293. // we return off1 == the offset after the first pointer we found,
  294. // which is where the next record will start.
  295. // In theory, the pointers are only allowed to jump backward.
  296. // We let them jump anywhere and stop jumping after a while.
  297. // UnpackDomainName unpacks a domain name into a string.
  298. func UnpackDomainName(msg []byte, off int) (string, int, error) {
  299. s := make([]byte, 0, 64)
  300. off1 := 0
  301. lenmsg := len(msg)
  302. ptr := 0 // number of pointers followed
  303. Loop:
  304. for {
  305. if off >= lenmsg {
  306. return "", lenmsg, ErrBuf
  307. }
  308. c := int(msg[off])
  309. off++
  310. switch c & 0xC0 {
  311. case 0x00:
  312. if c == 0x00 {
  313. // end of name
  314. break Loop
  315. }
  316. // literal string
  317. if off+c > lenmsg {
  318. return "", lenmsg, ErrBuf
  319. }
  320. for j := off; j < off+c; j++ {
  321. switch b := msg[j]; b {
  322. case '.', '(', ')', ';', ' ', '@':
  323. fallthrough
  324. case '"', '\\':
  325. s = append(s, '\\', b)
  326. case '\t':
  327. s = append(s, '\\', 't')
  328. case '\r':
  329. s = append(s, '\\', 'r')
  330. default:
  331. if b < 32 || b >= 127 { // unprintable use \DDD
  332. var buf [3]byte
  333. bufs := strconv.AppendInt(buf[:0], int64(b), 10)
  334. s = append(s, '\\')
  335. for i := 0; i < 3-len(bufs); i++ {
  336. s = append(s, '0')
  337. }
  338. for _, r := range bufs {
  339. s = append(s, r)
  340. }
  341. } else {
  342. s = append(s, b)
  343. }
  344. }
  345. }
  346. s = append(s, '.')
  347. off += c
  348. case 0xC0:
  349. // pointer to somewhere else in msg.
  350. // remember location after first ptr,
  351. // since that's how many bytes we consumed.
  352. // also, don't follow too many pointers --
  353. // maybe there's a loop.
  354. if off >= lenmsg {
  355. return "", lenmsg, ErrBuf
  356. }
  357. c1 := msg[off]
  358. off++
  359. if ptr == 0 {
  360. off1 = off
  361. }
  362. if ptr++; ptr > 10 {
  363. return "", lenmsg, &Error{err: "too many compression pointers"}
  364. }
  365. off = (c^0xC0)<<8 | int(c1)
  366. default:
  367. // 0x80 and 0x40 are reserved
  368. return "", lenmsg, ErrRdata
  369. }
  370. }
  371. if ptr == 0 {
  372. off1 = off
  373. }
  374. if len(s) == 0 {
  375. s = []byte(".")
  376. }
  377. return string(s), off1, nil
  378. }
  379. func packTxt(txt []string, msg []byte, offset int, tmp []byte) (int, error) {
  380. var err error
  381. if len(txt) == 0 {
  382. if offset >= len(msg) {
  383. return offset, ErrBuf
  384. }
  385. msg[offset] = 0
  386. return offset, nil
  387. }
  388. for i := range txt {
  389. if len(txt[i]) > len(tmp) {
  390. return offset, ErrBuf
  391. }
  392. offset, err = packTxtString(txt[i], msg, offset, tmp)
  393. if err != nil {
  394. return offset, err
  395. }
  396. }
  397. return offset, err
  398. }
  399. func packTxtString(s string, msg []byte, offset int, tmp []byte) (int, error) {
  400. lenByteOffset := offset
  401. if offset >= len(msg) {
  402. return offset, ErrBuf
  403. }
  404. offset++
  405. bs := tmp[:len(s)]
  406. copy(bs, s)
  407. for i := 0; i < len(bs); i++ {
  408. if len(msg) <= offset {
  409. return offset, ErrBuf
  410. }
  411. if bs[i] == '\\' {
  412. i++
  413. if i == len(bs) {
  414. break
  415. }
  416. // check for \DDD
  417. if i+2 < len(bs) && isDigit(bs[i]) && isDigit(bs[i+1]) && isDigit(bs[i+2]) {
  418. msg[offset] = dddToByte(bs[i:])
  419. i += 2
  420. } else if bs[i] == 't' {
  421. msg[offset] = '\t'
  422. } else if bs[i] == 'r' {
  423. msg[offset] = '\r'
  424. } else if bs[i] == 'n' {
  425. msg[offset] = '\n'
  426. } else {
  427. msg[offset] = bs[i]
  428. }
  429. } else {
  430. msg[offset] = bs[i]
  431. }
  432. offset++
  433. }
  434. l := offset - lenByteOffset - 1
  435. if l > 255 {
  436. return offset, &Error{err: "string exceeded 255 bytes in txt"}
  437. }
  438. msg[lenByteOffset] = byte(l)
  439. return offset, nil
  440. }
  441. func packOctetString(s string, msg []byte, offset int, tmp []byte) (int, error) {
  442. if offset >= len(msg) {
  443. return offset, ErrBuf
  444. }
  445. bs := tmp[:len(s)]
  446. copy(bs, s)
  447. for i := 0; i < len(bs); i++ {
  448. if len(msg) <= offset {
  449. return offset, ErrBuf
  450. }
  451. if bs[i] == '\\' {
  452. i++
  453. if i == len(bs) {
  454. break
  455. }
  456. // check for \DDD
  457. if i+2 < len(bs) && isDigit(bs[i]) && isDigit(bs[i+1]) && isDigit(bs[i+2]) {
  458. msg[offset] = dddToByte(bs[i:])
  459. i += 2
  460. } else {
  461. msg[offset] = bs[i]
  462. }
  463. } else {
  464. msg[offset] = bs[i]
  465. }
  466. offset++
  467. }
  468. return offset, nil
  469. }
  470. func unpackTxt(msg []byte, off0 int) (ss []string, off int, err error) {
  471. off = off0
  472. var s string
  473. for off < len(msg) && err == nil {
  474. s, off, err = unpackTxtString(msg, off)
  475. if err == nil {
  476. ss = append(ss, s)
  477. }
  478. }
  479. return
  480. }
  481. func unpackTxtString(msg []byte, offset int) (string, int, error) {
  482. if offset+1 > len(msg) {
  483. return "", offset, &Error{err: "overflow unpacking txt"}
  484. }
  485. l := int(msg[offset])
  486. if offset+l+1 > len(msg) {
  487. return "", offset, &Error{err: "overflow unpacking txt"}
  488. }
  489. s := make([]byte, 0, l)
  490. for _, b := range msg[offset+1 : offset+1+l] {
  491. switch b {
  492. case '"', '\\':
  493. s = append(s, '\\', b)
  494. case '\t':
  495. s = append(s, `\t`...)
  496. case '\r':
  497. s = append(s, `\r`...)
  498. case '\n':
  499. s = append(s, `\n`...)
  500. default:
  501. if b < 32 || b > 127 { // unprintable
  502. var buf [3]byte
  503. bufs := strconv.AppendInt(buf[:0], int64(b), 10)
  504. s = append(s, '\\')
  505. for i := 0; i < 3-len(bufs); i++ {
  506. s = append(s, '0')
  507. }
  508. for _, r := range bufs {
  509. s = append(s, r)
  510. }
  511. } else {
  512. s = append(s, b)
  513. }
  514. }
  515. }
  516. offset += 1 + l
  517. return string(s), offset, nil
  518. }
  519. // Pack a reflect.StructValue into msg. Struct members can only be uint8, uint16, uint32, string,
  520. // slices and other (often anonymous) structs.
  521. func packStructValue(val reflect.Value, msg []byte, off int, compression map[string]int, compress bool) (off1 int, err error) {
  522. var txtTmp []byte
  523. lenmsg := len(msg)
  524. numfield := val.NumField()
  525. for i := 0; i < numfield; i++ {
  526. typefield := val.Type().Field(i)
  527. if typefield.Tag == `dns:"-"` {
  528. continue
  529. }
  530. switch fv := val.Field(i); fv.Kind() {
  531. default:
  532. return lenmsg, &Error{err: "bad kind packing"}
  533. case reflect.Interface:
  534. // PrivateRR is the only RR implementation that has interface field.
  535. // therefore it's expected that this interface would be PrivateRdata
  536. switch data := fv.Interface().(type) {
  537. case PrivateRdata:
  538. n, err := data.Pack(msg[off:])
  539. if err != nil {
  540. return lenmsg, err
  541. }
  542. off += n
  543. default:
  544. return lenmsg, &Error{err: "bad kind interface packing"}
  545. }
  546. case reflect.Slice:
  547. switch typefield.Tag {
  548. default:
  549. return lenmsg, &Error{"bad tag packing slice: " + typefield.Tag.Get("dns")}
  550. case `dns:"domain-name"`:
  551. for j := 0; j < val.Field(i).Len(); j++ {
  552. element := val.Field(i).Index(j).String()
  553. off, err = PackDomainName(element, msg, off, compression, false && compress)
  554. if err != nil {
  555. return lenmsg, err
  556. }
  557. }
  558. case `dns:"txt"`:
  559. if txtTmp == nil {
  560. txtTmp = make([]byte, 256*4+1)
  561. }
  562. off, err = packTxt(fv.Interface().([]string), msg, off, txtTmp)
  563. if err != nil {
  564. return lenmsg, err
  565. }
  566. case `dns:"opt"`: // edns
  567. for j := 0; j < val.Field(i).Len(); j++ {
  568. element := val.Field(i).Index(j).Interface()
  569. b, e := element.(EDNS0).pack()
  570. if e != nil {
  571. return lenmsg, &Error{err: "overflow packing opt"}
  572. }
  573. // Option code
  574. msg[off], msg[off+1] = packUint16(element.(EDNS0).Option())
  575. // Length
  576. msg[off+2], msg[off+3] = packUint16(uint16(len(b)))
  577. off += 4
  578. if off+len(b) > lenmsg {
  579. copy(msg[off:], b)
  580. off = lenmsg
  581. continue
  582. }
  583. // Actual data
  584. copy(msg[off:off+len(b)], b)
  585. off += len(b)
  586. }
  587. case `dns:"a"`:
  588. if val.Type().String() == "dns.IPSECKEY" {
  589. // Field(2) is GatewayType, must be 1
  590. if val.Field(2).Uint() != 1 {
  591. continue
  592. }
  593. }
  594. // It must be a slice of 4, even if it is 16, we encode
  595. // only the first 4
  596. if off+net.IPv4len > lenmsg {
  597. return lenmsg, &Error{err: "overflow packing a"}
  598. }
  599. switch fv.Len() {
  600. case net.IPv6len:
  601. msg[off] = byte(fv.Index(12).Uint())
  602. msg[off+1] = byte(fv.Index(13).Uint())
  603. msg[off+2] = byte(fv.Index(14).Uint())
  604. msg[off+3] = byte(fv.Index(15).Uint())
  605. off += net.IPv4len
  606. case net.IPv4len:
  607. msg[off] = byte(fv.Index(0).Uint())
  608. msg[off+1] = byte(fv.Index(1).Uint())
  609. msg[off+2] = byte(fv.Index(2).Uint())
  610. msg[off+3] = byte(fv.Index(3).Uint())
  611. off += net.IPv4len
  612. case 0:
  613. // Allowed, for dynamic updates
  614. default:
  615. return lenmsg, &Error{err: "overflow packing a"}
  616. }
  617. case `dns:"aaaa"`:
  618. if val.Type().String() == "dns.IPSECKEY" {
  619. // Field(2) is GatewayType, must be 2
  620. if val.Field(2).Uint() != 2 {
  621. continue
  622. }
  623. }
  624. if fv.Len() == 0 {
  625. break
  626. }
  627. if fv.Len() > net.IPv6len || off+fv.Len() > lenmsg {
  628. return lenmsg, &Error{err: "overflow packing aaaa"}
  629. }
  630. for j := 0; j < net.IPv6len; j++ {
  631. msg[off] = byte(fv.Index(j).Uint())
  632. off++
  633. }
  634. case `dns:"wks"`:
  635. // TODO(miek): this is wrong should be lenrd
  636. if off == lenmsg {
  637. break // dyn. updates
  638. }
  639. if val.Field(i).Len() == 0 {
  640. break
  641. }
  642. off1 := off
  643. for j := 0; j < val.Field(i).Len(); j++ {
  644. serv := int(fv.Index(j).Uint())
  645. if off+serv/8+1 > len(msg) {
  646. return len(msg), &Error{err: "overflow packing wks"}
  647. }
  648. msg[off+serv/8] |= byte(1 << (7 - uint(serv%8)))
  649. if off+serv/8+1 > off1 {
  650. off1 = off + serv/8 + 1
  651. }
  652. }
  653. off = off1
  654. case `dns:"nsec"`: // NSEC/NSEC3
  655. // This is the uint16 type bitmap
  656. if val.Field(i).Len() == 0 {
  657. // Do absolutely nothing
  658. break
  659. }
  660. var lastwindow, lastlength uint16
  661. for j := 0; j < val.Field(i).Len(); j++ {
  662. t := uint16(fv.Index(j).Uint())
  663. window := t / 256
  664. length := (t-window*256)/8 + 1
  665. if window > lastwindow && lastlength != 0 {
  666. // New window, jump to the new offset
  667. off += int(lastlength) + 2
  668. lastlength = 0
  669. }
  670. if window < lastwindow || length < lastlength {
  671. return len(msg), &Error{err: "nsec bits out of order"}
  672. }
  673. if off+2+int(length) > len(msg) {
  674. return len(msg), &Error{err: "overflow packing nsec"}
  675. }
  676. // Setting the window #
  677. msg[off] = byte(window)
  678. // Setting the octets length
  679. msg[off+1] = byte(length)
  680. // Setting the bit value for the type in the right octet
  681. msg[off+1+int(length)] |= byte(1 << (7 - (t % 8)))
  682. lastwindow, lastlength = window, length
  683. }
  684. off += int(lastlength) + 2
  685. }
  686. case reflect.Struct:
  687. off, err = packStructValue(fv, msg, off, compression, compress)
  688. if err != nil {
  689. return lenmsg, err
  690. }
  691. case reflect.Uint8:
  692. if off+1 > lenmsg {
  693. return lenmsg, &Error{err: "overflow packing uint8"}
  694. }
  695. msg[off] = byte(fv.Uint())
  696. off++
  697. case reflect.Uint16:
  698. if off+2 > lenmsg {
  699. return lenmsg, &Error{err: "overflow packing uint16"}
  700. }
  701. i := fv.Uint()
  702. msg[off] = byte(i >> 8)
  703. msg[off+1] = byte(i)
  704. off += 2
  705. case reflect.Uint32:
  706. if off+4 > lenmsg {
  707. return lenmsg, &Error{err: "overflow packing uint32"}
  708. }
  709. i := fv.Uint()
  710. msg[off] = byte(i >> 24)
  711. msg[off+1] = byte(i >> 16)
  712. msg[off+2] = byte(i >> 8)
  713. msg[off+3] = byte(i)
  714. off += 4
  715. case reflect.Uint64:
  716. switch typefield.Tag {
  717. default:
  718. if off+8 > lenmsg {
  719. return lenmsg, &Error{err: "overflow packing uint64"}
  720. }
  721. i := fv.Uint()
  722. msg[off] = byte(i >> 56)
  723. msg[off+1] = byte(i >> 48)
  724. msg[off+2] = byte(i >> 40)
  725. msg[off+3] = byte(i >> 32)
  726. msg[off+4] = byte(i >> 24)
  727. msg[off+5] = byte(i >> 16)
  728. msg[off+6] = byte(i >> 8)
  729. msg[off+7] = byte(i)
  730. off += 8
  731. case `dns:"uint48"`:
  732. // Used in TSIG, where it stops at 48 bits, so we discard the upper 16
  733. if off+6 > lenmsg {
  734. return lenmsg, &Error{err: "overflow packing uint64 as uint48"}
  735. }
  736. i := fv.Uint()
  737. msg[off] = byte(i >> 40)
  738. msg[off+1] = byte(i >> 32)
  739. msg[off+2] = byte(i >> 24)
  740. msg[off+3] = byte(i >> 16)
  741. msg[off+4] = byte(i >> 8)
  742. msg[off+5] = byte(i)
  743. off += 6
  744. }
  745. case reflect.String:
  746. // There are multiple string encodings.
  747. // The tag distinguishes ordinary strings from domain names.
  748. s := fv.String()
  749. switch typefield.Tag {
  750. default:
  751. return lenmsg, &Error{"bad tag packing string: " + typefield.Tag.Get("dns")}
  752. case `dns:"base64"`:
  753. b64, e := fromBase64([]byte(s))
  754. if e != nil {
  755. return lenmsg, e
  756. }
  757. copy(msg[off:off+len(b64)], b64)
  758. off += len(b64)
  759. case `dns:"domain-name"`:
  760. if val.Type().String() == "dns.IPSECKEY" {
  761. // Field(2) is GatewayType, 1 and 2 or used for addresses
  762. x := val.Field(2).Uint()
  763. if x == 1 || x == 2 {
  764. continue
  765. }
  766. }
  767. if off, err = PackDomainName(s, msg, off, compression, false && compress); err != nil {
  768. return lenmsg, err
  769. }
  770. case `dns:"cdomain-name"`:
  771. if off, err = PackDomainName(s, msg, off, compression, true && compress); err != nil {
  772. return lenmsg, err
  773. }
  774. case `dns:"size-base32"`:
  775. // This is purely for NSEC3 atm, the previous byte must
  776. // holds the length of the encoded string. As NSEC3
  777. // is only defined to SHA1, the hashlength is 20 (160 bits)
  778. msg[off-1] = 20
  779. fallthrough
  780. case `dns:"base32"`:
  781. b32, e := fromBase32([]byte(s))
  782. if e != nil {
  783. return lenmsg, e
  784. }
  785. copy(msg[off:off+len(b32)], b32)
  786. off += len(b32)
  787. case `dns:"size-hex"`:
  788. fallthrough
  789. case `dns:"hex"`:
  790. // There is no length encoded here
  791. h, e := hex.DecodeString(s)
  792. if e != nil {
  793. return lenmsg, e
  794. }
  795. if off+hex.DecodedLen(len(s)) > lenmsg {
  796. return lenmsg, &Error{err: "overflow packing hex"}
  797. }
  798. copy(msg[off:off+hex.DecodedLen(len(s))], h)
  799. off += hex.DecodedLen(len(s))
  800. case `dns:"size"`:
  801. // the size is already encoded in the RR, we can safely use the
  802. // length of string. String is RAW (not encoded in hex, nor base64)
  803. copy(msg[off:off+len(s)], s)
  804. off += len(s)
  805. case `dns:"octet"`:
  806. bytesTmp := make([]byte, 256)
  807. off, err = packOctetString(fv.String(), msg, off, bytesTmp)
  808. if err != nil {
  809. return lenmsg, err
  810. }
  811. case `dns:"txt"`:
  812. fallthrough
  813. case "":
  814. if txtTmp == nil {
  815. txtTmp = make([]byte, 256*4+1)
  816. }
  817. off, err = packTxtString(fv.String(), msg, off, txtTmp)
  818. if err != nil {
  819. return lenmsg, err
  820. }
  821. }
  822. }
  823. }
  824. return off, nil
  825. }
  826. func structValue(any interface{}) reflect.Value {
  827. return reflect.ValueOf(any).Elem()
  828. }
  829. // PackStruct packs any structure to wire format.
  830. func PackStruct(any interface{}, msg []byte, off int) (off1 int, err error) {
  831. off, err = packStructValue(structValue(any), msg, off, nil, false)
  832. return off, err
  833. }
  834. func packStructCompress(any interface{}, msg []byte, off int, compression map[string]int, compress bool) (off1 int, err error) {
  835. off, err = packStructValue(structValue(any), msg, off, compression, compress)
  836. return off, err
  837. }
  838. // Unpack a reflect.StructValue from msg.
  839. // Same restrictions as packStructValue.
  840. func unpackStructValue(val reflect.Value, msg []byte, off int) (off1 int, err error) {
  841. lenmsg := len(msg)
  842. for i := 0; i < val.NumField(); i++ {
  843. if off > lenmsg {
  844. return lenmsg, &Error{"bad offset unpacking"}
  845. }
  846. switch fv := val.Field(i); fv.Kind() {
  847. default:
  848. return lenmsg, &Error{err: "bad kind unpacking"}
  849. case reflect.Interface:
  850. // PrivateRR is the only RR implementation that has interface field.
  851. // therefore it's expected that this interface would be PrivateRdata
  852. switch data := fv.Interface().(type) {
  853. case PrivateRdata:
  854. n, err := data.Unpack(msg[off:])
  855. if err != nil {
  856. return lenmsg, err
  857. }
  858. off += n
  859. default:
  860. return lenmsg, &Error{err: "bad kind interface unpacking"}
  861. }
  862. case reflect.Slice:
  863. switch val.Type().Field(i).Tag {
  864. default:
  865. return lenmsg, &Error{"bad tag unpacking slice: " + val.Type().Field(i).Tag.Get("dns")}
  866. case `dns:"domain-name"`:
  867. // HIP record slice of name (or none)
  868. var servers []string
  869. var s string
  870. for off < lenmsg {
  871. s, off, err = UnpackDomainName(msg, off)
  872. if err != nil {
  873. return lenmsg, err
  874. }
  875. servers = append(servers, s)
  876. }
  877. fv.Set(reflect.ValueOf(servers))
  878. case `dns:"txt"`:
  879. if off == lenmsg {
  880. break
  881. }
  882. var txt []string
  883. txt, off, err = unpackTxt(msg, off)
  884. if err != nil {
  885. return lenmsg, err
  886. }
  887. fv.Set(reflect.ValueOf(txt))
  888. case `dns:"opt"`: // edns0
  889. if off == lenmsg {
  890. // This is an EDNS0 (OPT Record) with no rdata
  891. // We can safely return here.
  892. break
  893. }
  894. var edns []EDNS0
  895. Option:
  896. code := uint16(0)
  897. if off+4 > lenmsg {
  898. return lenmsg, &Error{err: "overflow unpacking opt"}
  899. }
  900. code, off = unpackUint16(msg, off)
  901. optlen, off1 := unpackUint16(msg, off)
  902. if off1+int(optlen) > lenmsg {
  903. return lenmsg, &Error{err: "overflow unpacking opt"}
  904. }
  905. switch code {
  906. case EDNS0NSID:
  907. e := new(EDNS0_NSID)
  908. if err := e.unpack(msg[off1 : off1+int(optlen)]); err != nil {
  909. return lenmsg, err
  910. }
  911. edns = append(edns, e)
  912. off = off1 + int(optlen)
  913. case EDNS0SUBNET, EDNS0SUBNETDRAFT:
  914. e := new(EDNS0_SUBNET)
  915. if err := e.unpack(msg[off1 : off1+int(optlen)]); err != nil {
  916. return lenmsg, err
  917. }
  918. edns = append(edns, e)
  919. off = off1 + int(optlen)
  920. if code == EDNS0SUBNETDRAFT {
  921. e.DraftOption = true
  922. }
  923. case EDNS0UL:
  924. e := new(EDNS0_UL)
  925. if err := e.unpack(msg[off1 : off1+int(optlen)]); err != nil {
  926. return lenmsg, err
  927. }
  928. edns = append(edns, e)
  929. off = off1 + int(optlen)
  930. case EDNS0LLQ:
  931. e := new(EDNS0_LLQ)
  932. if err := e.unpack(msg[off1 : off1+int(optlen)]); err != nil {
  933. return lenmsg, err
  934. }
  935. edns = append(edns, e)
  936. off = off1 + int(optlen)
  937. case EDNS0DAU:
  938. e := new(EDNS0_DAU)
  939. if err := e.unpack(msg[off1 : off1+int(optlen)]); err != nil {
  940. return lenmsg, err
  941. }
  942. edns = append(edns, e)
  943. off = off1 + int(optlen)
  944. case EDNS0DHU:
  945. e := new(EDNS0_DHU)
  946. if err := e.unpack(msg[off1 : off1+int(optlen)]); err != nil {
  947. return lenmsg, err
  948. }
  949. edns = append(edns, e)
  950. off = off1 + int(optlen)
  951. case EDNS0N3U:
  952. e := new(EDNS0_N3U)
  953. if err := e.unpack(msg[off1 : off1+int(optlen)]); err != nil {
  954. return lenmsg, err
  955. }
  956. edns = append(edns, e)
  957. off = off1 + int(optlen)
  958. default:
  959. e := new(EDNS0_LOCAL)
  960. e.Code = code
  961. if err := e.unpack(msg[off1 : off1+int(optlen)]); err != nil {
  962. return lenmsg, err
  963. }
  964. edns = append(edns, e)
  965. off = off1 + int(optlen)
  966. }
  967. if off < lenmsg {
  968. goto Option
  969. }
  970. fv.Set(reflect.ValueOf(edns))
  971. case `dns:"a"`:
  972. if val.Type().String() == "dns.IPSECKEY" {
  973. // Field(2) is GatewayType, must be 1
  974. if val.Field(2).Uint() != 1 {
  975. continue
  976. }
  977. }
  978. if off == lenmsg {
  979. break // dyn. update
  980. }
  981. if off+net.IPv4len > lenmsg {
  982. return lenmsg, &Error{err: "overflow unpacking a"}
  983. }
  984. fv.Set(reflect.ValueOf(net.IPv4(msg[off], msg[off+1], msg[off+2], msg[off+3])))
  985. off += net.IPv4len
  986. case `dns:"aaaa"`:
  987. if val.Type().String() == "dns.IPSECKEY" {
  988. // Field(2) is GatewayType, must be 2
  989. if val.Field(2).Uint() != 2 {
  990. continue
  991. }
  992. }
  993. if off == lenmsg {
  994. break
  995. }
  996. if off+net.IPv6len > lenmsg {
  997. return lenmsg, &Error{err: "overflow unpacking aaaa"}
  998. }
  999. fv.Set(reflect.ValueOf(net.IP{msg[off], msg[off+1], msg[off+2], msg[off+3], msg[off+4],
  1000. msg[off+5], msg[off+6], msg[off+7], msg[off+8], msg[off+9], msg[off+10],
  1001. msg[off+11], msg[off+12], msg[off+13], msg[off+14], msg[off+15]}))
  1002. off += net.IPv6len
  1003. case `dns:"wks"`:
  1004. // Rest of the record is the bitmap
  1005. var serv []uint16
  1006. j := 0
  1007. for off < lenmsg {
  1008. if off+1 > lenmsg {
  1009. return lenmsg, &Error{err: "overflow unpacking wks"}
  1010. }
  1011. b := msg[off]
  1012. // Check the bits one by one, and set the type
  1013. if b&0x80 == 0x80 {
  1014. serv = append(serv, uint16(j*8+0))
  1015. }
  1016. if b&0x40 == 0x40 {
  1017. serv = append(serv, uint16(j*8+1))
  1018. }
  1019. if b&0x20 == 0x20 {
  1020. serv = append(serv, uint16(j*8+2))
  1021. }
  1022. if b&0x10 == 0x10 {
  1023. serv = append(serv, uint16(j*8+3))
  1024. }
  1025. if b&0x8 == 0x8 {
  1026. serv = append(serv, uint16(j*8+4))
  1027. }
  1028. if b&0x4 == 0x4 {
  1029. serv = append(serv, uint16(j*8+5))
  1030. }
  1031. if b&0x2 == 0x2 {
  1032. serv = append(serv, uint16(j*8+6))
  1033. }
  1034. if b&0x1 == 0x1 {
  1035. serv = append(serv, uint16(j*8+7))
  1036. }
  1037. j++
  1038. off++
  1039. }
  1040. fv.Set(reflect.ValueOf(serv))
  1041. case `dns:"nsec"`: // NSEC/NSEC3
  1042. if off == len(msg) {
  1043. break
  1044. }
  1045. // Rest of the record is the type bitmap
  1046. var nsec []uint16
  1047. length := 0
  1048. window := 0
  1049. lastwindow := -1
  1050. for off < len(msg) {
  1051. if off+2 > len(msg) {
  1052. return len(msg), &Error{err: "overflow unpacking nsecx"}
  1053. }
  1054. window = int(msg[off])
  1055. length = int(msg[off+1])
  1056. off += 2
  1057. if window <= lastwindow {
  1058. // RFC 4034: Blocks are present in the NSEC RR RDATA in
  1059. // increasing numerical order.
  1060. return len(msg), &Error{err: "out of order NSEC block"}
  1061. }
  1062. if length == 0 {
  1063. // RFC 4034: Blocks with no types present MUST NOT be included.
  1064. return len(msg), &Error{err: "empty NSEC block"}
  1065. }
  1066. if length > 32 {
  1067. return len(msg), &Error{err: "NSEC block too long"}
  1068. }
  1069. if off+length > len(msg) {
  1070. return len(msg), &Error{err: "overflowing NSEC block"}
  1071. }
  1072. // Walk the bytes in the window and extract the type bits
  1073. for j := 0; j < length; j++ {
  1074. b := msg[off+j]
  1075. // Check the bits one by one, and set the type
  1076. if b&0x80 == 0x80 {
  1077. nsec = append(nsec, uint16(window*256+j*8+0))
  1078. }
  1079. if b&0x40 == 0x40 {
  1080. nsec = append(nsec, uint16(window*256+j*8+1))
  1081. }
  1082. if b&0x20 == 0x20 {
  1083. nsec = append(nsec, uint16(window*256+j*8+2))
  1084. }
  1085. if b&0x10 == 0x10 {
  1086. nsec = append(nsec, uint16(window*256+j*8+3))
  1087. }
  1088. if b&0x8 == 0x8 {
  1089. nsec = append(nsec, uint16(window*256+j*8+4))
  1090. }
  1091. if b&0x4 == 0x4 {
  1092. nsec = append(nsec, uint16(window*256+j*8+5))
  1093. }
  1094. if b&0x2 == 0x2 {
  1095. nsec = append(nsec, uint16(window*256+j*8+6))
  1096. }
  1097. if b&0x1 == 0x1 {
  1098. nsec = append(nsec, uint16(window*256+j*8+7))
  1099. }
  1100. }
  1101. off += length
  1102. lastwindow = window
  1103. }
  1104. fv.Set(reflect.ValueOf(nsec))
  1105. }
  1106. case reflect.Struct:
  1107. off, err = unpackStructValue(fv, msg, off)
  1108. if err != nil {
  1109. return lenmsg, err
  1110. }
  1111. if val.Type().Field(i).Name == "Hdr" {
  1112. lenrd := off + int(val.FieldByName("Hdr").FieldByName("Rdlength").Uint())
  1113. if lenrd > lenmsg {
  1114. return lenmsg, &Error{err: "overflowing header size"}
  1115. }
  1116. msg = msg[:lenrd]
  1117. lenmsg = len(msg)
  1118. }
  1119. case reflect.Uint8:
  1120. if off == lenmsg {
  1121. break
  1122. }
  1123. if off+1 > lenmsg {
  1124. return lenmsg, &Error{err: "overflow unpacking uint8"}
  1125. }
  1126. fv.SetUint(uint64(uint8(msg[off])))
  1127. off++
  1128. case reflect.Uint16:
  1129. if off == lenmsg {
  1130. break
  1131. }
  1132. var i uint16
  1133. if off+2 > lenmsg {
  1134. return lenmsg, &Error{err: "overflow unpacking uint16"}
  1135. }
  1136. i, off = unpackUint16(msg, off)
  1137. fv.SetUint(uint64(i))
  1138. case reflect.Uint32:
  1139. if off == lenmsg {
  1140. break
  1141. }
  1142. if off+4 > lenmsg {
  1143. return lenmsg, &Error{err: "overflow unpacking uint32"}
  1144. }
  1145. fv.SetUint(uint64(uint32(msg[off])<<24 | uint32(msg[off+1])<<16 | uint32(msg[off+2])<<8 | uint32(msg[off+3])))
  1146. off += 4
  1147. case reflect.Uint64:
  1148. if off == lenmsg {
  1149. break
  1150. }
  1151. switch val.Type().Field(i).Tag {
  1152. default:
  1153. if off+8 > lenmsg {
  1154. return lenmsg, &Error{err: "overflow unpacking uint64"}
  1155. }
  1156. fv.SetUint(uint64(uint64(msg[off])<<56 | uint64(msg[off+1])<<48 | uint64(msg[off+2])<<40 |
  1157. uint64(msg[off+3])<<32 | uint64(msg[off+4])<<24 | uint64(msg[off+5])<<16 | uint64(msg[off+6])<<8 | uint64(msg[off+7])))
  1158. off += 8
  1159. case `dns:"uint48"`:
  1160. // Used in TSIG where the last 48 bits are occupied, so for now, assume a uint48 (6 bytes)
  1161. if off+6 > lenmsg {
  1162. return lenmsg, &Error{err: "overflow unpacking uint64 as uint48"}
  1163. }
  1164. fv.SetUint(uint64(uint64(msg[off])<<40 | uint64(msg[off+1])<<32 | uint64(msg[off+2])<<24 | uint64(msg[off+3])<<16 |
  1165. uint64(msg[off+4])<<8 | uint64(msg[off+5])))
  1166. off += 6
  1167. }
  1168. case reflect.String:
  1169. var s string
  1170. if off == lenmsg {
  1171. break
  1172. }
  1173. switch val.Type().Field(i).Tag {
  1174. default:
  1175. return lenmsg, &Error{"bad tag unpacking string: " + val.Type().Field(i).Tag.Get("dns")}
  1176. case `dns:"octet"`:
  1177. s = string(msg[off:])
  1178. off = lenmsg
  1179. case `dns:"hex"`:
  1180. hexend := lenmsg
  1181. if val.FieldByName("Hdr").FieldByName("Rrtype").Uint() == uint64(TypeHIP) {
  1182. hexend = off + int(val.FieldByName("HitLength").Uint())
  1183. }
  1184. if hexend > lenmsg {
  1185. return lenmsg, &Error{err: "overflow unpacking HIP hex"}
  1186. }
  1187. s = hex.EncodeToString(msg[off:hexend])
  1188. off = hexend
  1189. case `dns:"base64"`:
  1190. // Rest of the RR is base64 encoded value
  1191. b64end := lenmsg
  1192. if val.FieldByName("Hdr").FieldByName("Rrtype").Uint() == uint64(TypeHIP) {
  1193. b64end = off + int(val.FieldByName("PublicKeyLength").Uint())
  1194. }
  1195. if b64end > lenmsg {
  1196. return lenmsg, &Error{err: "overflow unpacking HIP base64"}
  1197. }
  1198. s = toBase64(msg[off:b64end])
  1199. off = b64end
  1200. case `dns:"cdomain-name"`:
  1201. fallthrough
  1202. case `dns:"domain-name"`:
  1203. if val.Type().String() == "dns.IPSECKEY" {
  1204. // Field(2) is GatewayType, 1 and 2 or used for addresses
  1205. x := val.Field(2).Uint()
  1206. if x == 1 || x == 2 {
  1207. continue
  1208. }
  1209. }
  1210. if off == lenmsg && int(val.FieldByName("Hdr").FieldByName("Rdlength").Uint()) == 0 {
  1211. // zero rdata is ok for dyn updates, but only if rdlength is 0
  1212. break
  1213. }
  1214. s, off, err = UnpackDomainName(msg, off)
  1215. if err != nil {
  1216. return lenmsg, err
  1217. }
  1218. case `dns:"size-base32"`:
  1219. var size int
  1220. switch val.Type().Name() {
  1221. case "NSEC3":
  1222. switch val.Type().Field(i).Name {
  1223. case "NextDomain":
  1224. name := val.FieldByName("HashLength")
  1225. size = int(name.Uint())
  1226. }
  1227. }
  1228. if off+size > lenmsg {
  1229. return lenmsg, &Error{err: "overflow unpacking base32"}
  1230. }
  1231. s = toBase32(msg[off : off+size])
  1232. off += size
  1233. case `dns:"size-hex"`:
  1234. // a "size" string, but it must be encoded in hex in the string
  1235. var size int
  1236. switch val.Type().Name() {
  1237. case "NSEC3":
  1238. switch val.Type().Field(i).Name {
  1239. case "Salt":
  1240. name := val.FieldByName("SaltLength")
  1241. size = int(name.Uint())
  1242. case "NextDomain":
  1243. name := val.FieldByName("HashLength")
  1244. size = int(name.Uint())
  1245. }
  1246. case "TSIG":
  1247. switch val.Type().Field(i).Name {
  1248. case "MAC":
  1249. name := val.FieldByName("MACSize")
  1250. size = int(name.Uint())
  1251. case "OtherData":
  1252. name := val.FieldByName("OtherLen")
  1253. size = int(name.Uint())
  1254. }
  1255. }
  1256. if off+size > lenmsg {
  1257. return lenmsg, &Error{err: "overflow unpacking hex"}
  1258. }
  1259. s = hex.EncodeToString(msg[off : off+size])
  1260. off += size
  1261. case `dns:"txt"`:
  1262. fallthrough
  1263. case "":
  1264. s, off, err = unpackTxtString(msg, off)
  1265. }
  1266. fv.SetString(s)
  1267. }
  1268. }
  1269. return off, nil
  1270. }
  1271. // Helpers for dealing with escaped bytes
  1272. func isDigit(b byte) bool { return b >= '0' && b <= '9' }
  1273. func dddToByte(s []byte) byte {
  1274. return byte((s[0]-'0')*100 + (s[1]-'0')*10 + (s[2] - '0'))
  1275. }
  1276. // UnpackStruct unpacks a binary message from offset off to the interface
  1277. // value given.
  1278. func UnpackStruct(any interface{}, msg []byte, off int) (int, error) {
  1279. return unpackStructValue(structValue(any), msg, off)
  1280. }
  1281. // Helper function for packing and unpacking
  1282. func intToBytes(i *big.Int, length int) []byte {
  1283. buf := i.Bytes()
  1284. if len(buf) < length {
  1285. b := make([]byte, length)
  1286. copy(b[length-len(buf):], buf)
  1287. return b
  1288. }
  1289. return buf
  1290. }
  1291. func unpackUint16(msg []byte, off int) (uint16, int) {
  1292. return uint16(msg[off])<<8 | uint16(msg[off+1]), off + 2
  1293. }
  1294. func packUint16(i uint16) (byte, byte) {
  1295. return byte(i >> 8), byte(i)
  1296. }
  1297. func toBase32(b []byte) string {
  1298. return base32.HexEncoding.EncodeToString(b)
  1299. }
  1300. func fromBase32(s []byte) (buf []byte, err error) {
  1301. buflen := base32.HexEncoding.DecodedLen(len(s))
  1302. buf = make([]byte, buflen)
  1303. n, err := base32.HexEncoding.Decode(buf, s)
  1304. buf = buf[:n]
  1305. return
  1306. }
  1307. func toBase64(b []byte) string {
  1308. return base64.StdEncoding.EncodeToString(b)
  1309. }
  1310. func fromBase64(s []byte) (buf []byte, err error) {
  1311. buflen := base64.StdEncoding.DecodedLen(len(s))
  1312. buf = make([]byte, buflen)
  1313. n, err := base64.StdEncoding.Decode(buf, s)
  1314. buf = buf[:n]
  1315. return
  1316. }
  1317. // PackRR packs a resource record rr into msg[off:].
  1318. // See PackDomainName for documentation about the compression.
  1319. func PackRR(rr RR, msg []byte, off int, compression map[string]int, compress bool) (off1 int, err error) {
  1320. if rr == nil {
  1321. return len(msg), &Error{err: "nil rr"}
  1322. }
  1323. off1, err = packStructCompress(rr, msg, off, compression, compress)
  1324. if err != nil {
  1325. return len(msg), err
  1326. }
  1327. if rawSetRdlength(msg, off, off1) {
  1328. return off1, nil
  1329. }
  1330. return off, ErrRdata
  1331. }
  1332. // UnpackRR unpacks msg[off:] into an RR.
  1333. func UnpackRR(msg []byte, off int) (rr RR, off1 int, err error) {
  1334. // unpack just the header, to find the rr type and length
  1335. var h RR_Header
  1336. off0 := off
  1337. if off, err = UnpackStruct(&h, msg, off); err != nil {
  1338. return nil, len(msg), err
  1339. }
  1340. end := off + int(h.Rdlength)
  1341. // make an rr of that type and re-unpack.
  1342. mk, known := TypeToRR[h.Rrtype]
  1343. if !known {
  1344. rr = new(RFC3597)
  1345. } else {
  1346. rr = mk()
  1347. }
  1348. off, err = UnpackStruct(rr, msg, off0)
  1349. if off != end {
  1350. return &h, end, &Error{err: "bad rdlength"}
  1351. }
  1352. return rr, off, err
  1353. }
  1354. // unpackRRslice unpacks msg[off:] into an []RR.
  1355. // If we cannot unpack the whole array, then it will return nil
  1356. func unpackRRslice(l int, msg []byte, off int) (dst1 []RR, off1 int, err error) {
  1357. var r RR
  1358. // Optimistically make dst be the length that was sent
  1359. dst := make([]RR, 0, l)
  1360. for i := 0; i < l; i++ {
  1361. off1 := off
  1362. r, off, err = UnpackRR(msg, off)
  1363. if err != nil {
  1364. off = len(msg)
  1365. break
  1366. }
  1367. // If offset does not increase anymore, l is a lie
  1368. if off1 == off {
  1369. l = i
  1370. break
  1371. }
  1372. dst = append(dst, r)
  1373. }
  1374. if err != nil && off == len(msg) {
  1375. dst = nil
  1376. }
  1377. return dst, off, err
  1378. }
  1379. // Reverse a map
  1380. func reverseInt8(m map[uint8]string) map[string]uint8 {
  1381. n := make(map[string]uint8)
  1382. for u, s := range m {
  1383. n[s] = u
  1384. }
  1385. return n
  1386. }
  1387. func reverseInt16(m map[uint16]string) map[string]uint16 {
  1388. n := make(map[string]uint16)
  1389. for u, s := range m {
  1390. n[s] = u
  1391. }
  1392. return n
  1393. }
  1394. func reverseInt(m map[int]string) map[string]int {
  1395. n := make(map[string]int)
  1396. for u, s := range m {
  1397. n[s] = u
  1398. }
  1399. return n
  1400. }
  1401. // Convert a MsgHdr to a string, with dig-like headers:
  1402. //
  1403. //;; opcode: QUERY, status: NOERROR, id: 48404
  1404. //
  1405. //;; flags: qr aa rd ra;
  1406. func (h *MsgHdr) String() string {
  1407. if h == nil {
  1408. return "<nil> MsgHdr"
  1409. }
  1410. s := ";; opcode: " + OpcodeToString[h.Opcode]
  1411. s += ", status: " + RcodeToString[h.Rcode]
  1412. s += ", id: " + strconv.Itoa(int(h.Id)) + "\n"
  1413. s += ";; flags:"
  1414. if h.Response {
  1415. s += " qr"
  1416. }
  1417. if h.Authoritative {
  1418. s += " aa"
  1419. }
  1420. if h.Truncated {
  1421. s += " tc"
  1422. }
  1423. if h.RecursionDesired {
  1424. s += " rd"
  1425. }
  1426. if h.RecursionAvailable {
  1427. s += " ra"
  1428. }
  1429. if h.Zero { // Hmm
  1430. s += " z"
  1431. }
  1432. if h.AuthenticatedData {
  1433. s += " ad"
  1434. }
  1435. if h.CheckingDisabled {
  1436. s += " cd"
  1437. }
  1438. s += ";"
  1439. return s
  1440. }
  1441. // Pack packs a Msg: it is converted to to wire format.
  1442. // If the dns.Compress is true the message will be in compressed wire format.
  1443. func (dns *Msg) Pack() (msg []byte, err error) {
  1444. return dns.PackBuffer(nil)
  1445. }
  1446. // PackBuffer packs a Msg, using the given buffer buf. If buf is too small
  1447. // a new buffer is allocated.
  1448. func (dns *Msg) PackBuffer(buf []byte) (msg []byte, err error) {
  1449. var dh Header
  1450. var compression map[string]int
  1451. if dns.Compress {
  1452. compression = make(map[string]int) // Compression pointer mappings
  1453. }
  1454. if dns.Rcode < 0 || dns.Rcode > 0xFFF {
  1455. return nil, ErrRcode
  1456. }
  1457. if dns.Rcode > 0xF {
  1458. // Regular RCODE field is 4 bits
  1459. opt := dns.IsEdns0()
  1460. if opt == nil {
  1461. return nil, ErrExtendedRcode
  1462. }
  1463. opt.SetExtendedRcode(uint8(dns.Rcode >> 4))
  1464. dns.Rcode &= 0xF
  1465. }
  1466. // Convert convenient Msg into wire-like Header.
  1467. dh.Id = dns.Id
  1468. dh.Bits = uint16(dns.Opcode)<<11 | uint16(dns.Rcode)
  1469. if dns.Response {
  1470. dh.Bits |= _QR
  1471. }
  1472. if dns.Authoritative {
  1473. dh.Bits |= _AA
  1474. }
  1475. if dns.Truncated {
  1476. dh.Bits |= _TC
  1477. }
  1478. if dns.RecursionDesired {
  1479. dh.Bits |= _RD
  1480. }
  1481. if dns.RecursionAvailable {
  1482. dh.Bits |= _RA
  1483. }
  1484. if dns.Zero {
  1485. dh.Bits |= _Z
  1486. }
  1487. if dns.AuthenticatedData {
  1488. dh.Bits |= _AD
  1489. }
  1490. if dns.CheckingDisabled {
  1491. dh.Bits |= _CD
  1492. }
  1493. // Prepare variable sized arrays.
  1494. question := dns.Question
  1495. answer := dns.Answer
  1496. ns := dns.Ns
  1497. extra := dns.Extra
  1498. dh.Qdcount = uint16(len(question))
  1499. dh.Ancount = uint16(len(answer))
  1500. dh.Nscount = uint16(len(ns))
  1501. dh.Arcount = uint16(len(extra))
  1502. // We need the uncompressed length here, because we first pack it and then compress it.
  1503. msg = buf
  1504. compress := dns.Compress
  1505. dns.Compress = false
  1506. if packLen := dns.Len() + 1; len(msg) < packLen {
  1507. msg = make([]byte, packLen)
  1508. }
  1509. dns.Compress = compress
  1510. // Pack it in: header and then the pieces.
  1511. off := 0
  1512. off, err = packStructCompress(&dh, msg, off, compression, dns.Compress)
  1513. if err != nil {
  1514. return nil, err
  1515. }
  1516. for i := 0; i < len(question); i++ {
  1517. off, err = packStructCompress(&question[i], msg, off, compression, dns.Compress)
  1518. if err != nil {
  1519. return nil, err
  1520. }
  1521. }
  1522. for i := 0; i < len(answer); i++ {
  1523. off, err = PackRR(answer[i], msg, off, compression, dns.Compress)
  1524. if err != nil {
  1525. return nil, err
  1526. }
  1527. }
  1528. for i := 0; i < len(ns); i++ {
  1529. off, err = PackRR(ns[i], msg, off, compression, dns.Compress)
  1530. if err != nil {
  1531. return nil, err
  1532. }
  1533. }
  1534. for i := 0; i < len(extra); i++ {
  1535. off, err = PackRR(extra[i], msg, off, compression, dns.Compress)
  1536. if err != nil {
  1537. return nil, err
  1538. }
  1539. }
  1540. return msg[:off], nil
  1541. }
  1542. // Unpack unpacks a binary message to a Msg structure.
  1543. func (dns *Msg) Unpack(msg []byte) (err error) {
  1544. // Header.
  1545. var dh Header
  1546. off := 0
  1547. if off, err = UnpackStruct(&dh, msg, off); err != nil {
  1548. return err
  1549. }
  1550. dns.Id = dh.Id
  1551. dns.Response = (dh.Bits & _QR) != 0
  1552. dns.Opcode = int(dh.Bits>>11) & 0xF
  1553. dns.Authoritative = (dh.Bits & _AA) != 0
  1554. dns.Truncated = (dh.Bits & _TC) != 0
  1555. dns.RecursionDesired = (dh.Bits & _RD) != 0
  1556. dns.RecursionAvailable = (dh.Bits & _RA) != 0
  1557. dns.Zero = (dh.Bits & _Z) != 0
  1558. dns.AuthenticatedData = (dh.Bits & _AD) != 0
  1559. dns.CheckingDisabled = (dh.Bits & _CD) != 0
  1560. dns.Rcode = int(dh.Bits & 0xF)
  1561. // Optimistically use the count given to us in the header
  1562. dns.Question = make([]Question, 0, int(dh.Qdcount))
  1563. var q Question
  1564. for i := 0; i < int(dh.Qdcount); i++ {
  1565. off1 := off
  1566. off, err = UnpackStruct(&q, msg, off)
  1567. if err != nil {
  1568. // Even if Truncated is set, we only will set ErrTruncated if we
  1569. // actually got the questions
  1570. return err
  1571. }
  1572. if off1 == off { // Offset does not increase anymore, dh.Qdcount is a lie!
  1573. dh.Qdcount = uint16(i)
  1574. break
  1575. }
  1576. dns.Question = append(dns.Question, q)
  1577. }
  1578. dns.Answer, off, err = unpackRRslice(int(dh.Ancount), msg, off)
  1579. // The header counts might have been wrong so we need to update it
  1580. dh.Ancount = uint16(len(dns.Answer))
  1581. if err == nil {
  1582. dns.Ns, off, err = unpackRRslice(int(dh.Nscount), msg, off)
  1583. }
  1584. // The header counts might have been wrong so we need to update it
  1585. dh.Nscount = uint16(len(dns.Ns))
  1586. if err == nil {
  1587. dns.Extra, off, err = unpackRRslice(int(dh.Arcount), msg, off)
  1588. }
  1589. // The header counts might have been wrong so we need to update it
  1590. dh.Arcount = uint16(len(dns.Extra))
  1591. if off != len(msg) {
  1592. // TODO(miek) make this an error?
  1593. // use PackOpt to let people tell how detailed the error reporting should be?
  1594. // println("dns: extra bytes in dns packet", off, "<", len(msg))
  1595. } else if dns.Truncated {
  1596. // Whether we ran into a an error or not, we want to return that it
  1597. // was truncated
  1598. err = ErrTruncated
  1599. }
  1600. return err
  1601. }
  1602. // Convert a complete message to a string with dig-like output.
  1603. func (dns *Msg) String() string {
  1604. if dns == nil {
  1605. return "<nil> MsgHdr"
  1606. }
  1607. s := dns.MsgHdr.String() + " "
  1608. s += "QUERY: " + strconv.Itoa(len(dns.Question)) + ", "
  1609. s += "ANSWER: " + strconv.Itoa(len(dns.Answer)) + ", "
  1610. s += "AUTHORITY: " + strconv.Itoa(len(dns.Ns)) + ", "
  1611. s += "ADDITIONAL: " + strconv.Itoa(len(dns.Extra)) + "\n"
  1612. if len(dns.Question) > 0 {
  1613. s += "\n;; QUESTION SECTION:\n"
  1614. for i := 0; i < len(dns.Question); i++ {
  1615. s += dns.Question[i].String() + "\n"
  1616. }
  1617. }
  1618. if len(dns.Answer) > 0 {
  1619. s += "\n;; ANSWER SECTION:\n"
  1620. for i := 0; i < len(dns.Answer); i++ {
  1621. if dns.Answer[i] != nil {
  1622. s += dns.Answer[i].String() + "\n"
  1623. }
  1624. }
  1625. }
  1626. if len(dns.Ns) > 0 {
  1627. s += "\n;; AUTHORITY SECTION:\n"
  1628. for i := 0; i < len(dns.Ns); i++ {
  1629. if dns.Ns[i] != nil {
  1630. s += dns.Ns[i].String() + "\n"
  1631. }
  1632. }
  1633. }
  1634. if len(dns.Extra) > 0 {
  1635. s += "\n;; ADDITIONAL SECTION:\n"
  1636. for i := 0; i < len(dns.Extra); i++ {
  1637. if dns.Extra[i] != nil {
  1638. s += dns.Extra[i].String() + "\n"
  1639. }
  1640. }
  1641. }
  1642. return s
  1643. }
  1644. // Len returns the message length when in (un)compressed wire format.
  1645. // If dns.Compress is true compression it is taken into account. Len()
  1646. // is provided to be a faster way to get the size of the resulting packet,
  1647. // than packing it, measuring the size and discarding the buffer.
  1648. func (dns *Msg) Len() int {
  1649. // We always return one more than needed.
  1650. l := 12 // Message header is always 12 bytes
  1651. var compression map[string]int
  1652. if dns.Compress {
  1653. compression = make(map[string]int)
  1654. }
  1655. for i := 0; i < len(dns.Question); i++ {
  1656. l += dns.Question[i].len()
  1657. if dns.Compress {
  1658. compressionLenHelper(compression, dns.Question[i].Name)
  1659. }
  1660. }
  1661. for i := 0; i < len(dns.Answer); i++ {
  1662. l += dns.Answer[i].len()
  1663. if dns.Compress {
  1664. k, ok := compressionLenSearch(compression, dns.Answer[i].Header().Name)
  1665. if ok {
  1666. l += 1 - k
  1667. }
  1668. compressionLenHelper(compression, dns.Answer[i].Header().Name)
  1669. k, ok = compressionLenSearchType(compression, dns.Answer[i])
  1670. if ok {
  1671. l += 1 - k
  1672. }
  1673. compressionLenHelperType(compression, dns.Answer[i])
  1674. }
  1675. }
  1676. for i := 0; i < len(dns.Ns); i++ {
  1677. l += dns.Ns[i].len()
  1678. if dns.Compress {
  1679. k, ok := compressionLenSearch(compression, dns.Ns[i].Header().Name)
  1680. if ok {
  1681. l += 1 - k
  1682. }
  1683. compressionLenHelper(compression, dns.Ns[i].Header().Name)
  1684. k, ok = compressionLenSearchType(compression, dns.Ns[i])
  1685. if ok {
  1686. l += 1 - k
  1687. }
  1688. compressionLenHelperType(compression, dns.Ns[i])
  1689. }
  1690. }
  1691. for i := 0; i < len(dns.Extra); i++ {
  1692. l += dns.Extra[i].len()
  1693. if dns.Compress {
  1694. k, ok := compressionLenSearch(compression, dns.Extra[i].Header().Name)
  1695. if ok {
  1696. l += 1 - k
  1697. }
  1698. compressionLenHelper(compression, dns.Extra[i].Header().Name)
  1699. k, ok = compressionLenSearchType(compression, dns.Extra[i])
  1700. if ok {
  1701. l += 1 - k
  1702. }
  1703. compressionLenHelperType(compression, dns.Extra[i])
  1704. }
  1705. }
  1706. return l
  1707. }
  1708. // Put the parts of the name in the compression map.
  1709. func compressionLenHelper(c map[string]int, s string) {
  1710. pref := ""
  1711. lbs := Split(s)
  1712. for j := len(lbs) - 1; j >= 0; j-- {
  1713. pref = s[lbs[j]:]
  1714. if _, ok := c[pref]; !ok {
  1715. c[pref] = len(pref)
  1716. }
  1717. }
  1718. }
  1719. // Look for each part in the compression map and returns its length,
  1720. // keep on searching so we get the longest match.
  1721. func compressionLenSearch(c map[string]int, s string) (int, bool) {
  1722. off := 0
  1723. end := false
  1724. if s == "" { // don't bork on bogus data
  1725. return 0, false
  1726. }
  1727. for {
  1728. if _, ok := c[s[off:]]; ok {
  1729. return len(s[off:]), true
  1730. }
  1731. if end {
  1732. break
  1733. }
  1734. off, end = NextLabel(s, off)
  1735. }
  1736. return 0, false
  1737. }
  1738. // TODO(miek): should add all types, because the all can be *used* for compression.
  1739. func compressionLenHelperType(c map[string]int, r RR) {
  1740. switch x := r.(type) {
  1741. case *NS:
  1742. compressionLenHelper(c, x.Ns)
  1743. case *MX:
  1744. compressionLenHelper(c, x.Mx)
  1745. case *CNAME:
  1746. compressionLenHelper(c, x.Target)
  1747. case *PTR:
  1748. compressionLenHelper(c, x.Ptr)
  1749. case *SOA:
  1750. compressionLenHelper(c, x.Ns)
  1751. compressionLenHelper(c, x.Mbox)
  1752. case *MB:
  1753. compressionLenHelper(c, x.Mb)
  1754. case *MG:
  1755. compressionLenHelper(c, x.Mg)
  1756. case *MR:
  1757. compressionLenHelper(c, x.Mr)
  1758. case *MF:
  1759. compressionLenHelper(c, x.Mf)
  1760. case *MD:
  1761. compressionLenHelper(c, x.Md)
  1762. case *RT:
  1763. compressionLenHelper(c, x.Host)
  1764. case *MINFO:
  1765. compressionLenHelper(c, x.Rmail)
  1766. compressionLenHelper(c, x.Email)
  1767. case *AFSDB:
  1768. compressionLenHelper(c, x.Hostname)
  1769. }
  1770. }
  1771. // Only search on compressing these types.
  1772. func compressionLenSearchType(c map[string]int, r RR) (int, bool) {
  1773. switch x := r.(type) {
  1774. case *NS:
  1775. return compressionLenSearch(c, x.Ns)
  1776. case *MX:
  1777. return compressionLenSearch(c, x.Mx)
  1778. case *CNAME:
  1779. return compressionLenSearch(c, x.Target)
  1780. case *PTR:
  1781. return compressionLenSearch(c, x.Ptr)
  1782. case *SOA:
  1783. k, ok := compressionLenSearch(c, x.Ns)
  1784. k1, ok1 := compressionLenSearch(c, x.Mbox)
  1785. if !ok && !ok1 {
  1786. return 0, false
  1787. }
  1788. return k + k1, true
  1789. case *MB:
  1790. return compressionLenSearch(c, x.Mb)
  1791. case *MG:
  1792. return compressionLenSearch(c, x.Mg)
  1793. case *MR:
  1794. return compressionLenSearch(c, x.Mr)
  1795. case *MF:
  1796. return compressionLenSearch(c, x.Mf)
  1797. case *MD:
  1798. return compressionLenSearch(c, x.Md)
  1799. case *RT:
  1800. return compressionLenSearch(c, x.Host)
  1801. case *MINFO:
  1802. k, ok := compressionLenSearch(c, x.Rmail)
  1803. k1, ok1 := compressionLenSearch(c, x.Email)
  1804. if !ok && !ok1 {
  1805. return 0, false
  1806. }
  1807. return k + k1, true
  1808. case *AFSDB:
  1809. return compressionLenSearch(c, x.Hostname)
  1810. }
  1811. return 0, false
  1812. }
  1813. // id returns a 16 bits random number to be used as a
  1814. // message id. The random provided should be good enough.
  1815. func id() uint16 {
  1816. return uint16(rand.Int()) ^ uint16(time.Now().Nanosecond())
  1817. }
  1818. // Copy returns a new RR which is a deep-copy of r.
  1819. func Copy(r RR) RR {
  1820. r1 := r.copy()
  1821. return r1
  1822. }
  1823. // Copy returns a new *Msg which is a deep-copy of dns.
  1824. func (dns *Msg) Copy() *Msg {
  1825. return dns.CopyTo(new(Msg))
  1826. }
  1827. // CopyTo copies the contents to the provided message using a deep-copy and returns the copy.
  1828. func (dns *Msg) CopyTo(r1 *Msg) *Msg {
  1829. r1.MsgHdr = dns.MsgHdr
  1830. r1.Compress = dns.Compress
  1831. if len(dns.Question) > 0 {
  1832. r1.Question = make([]Question, len(dns.Question))
  1833. copy(r1.Question, dns.Question) // TODO(miek): Question is an immutable value, ok to do a shallow-copy
  1834. }
  1835. rrArr := make([]RR, len(dns.Answer)+len(dns.Ns)+len(dns.Extra))
  1836. var rri int
  1837. if len(dns.Answer) > 0 {
  1838. rrbegin := rri
  1839. for i := 0; i < len(dns.Answer); i++ {
  1840. rrArr[rri] = dns.Answer[i].copy()
  1841. rri++
  1842. }
  1843. r1.Answer = rrArr[rrbegin:rri:rri]
  1844. }
  1845. if len(dns.Ns) > 0 {
  1846. rrbegin := rri
  1847. for i := 0; i < len(dns.Ns); i++ {
  1848. rrArr[rri] = dns.Ns[i].copy()
  1849. rri++
  1850. }
  1851. r1.Ns = rrArr[rrbegin:rri:rri]
  1852. }
  1853. if len(dns.Extra) > 0 {
  1854. rrbegin := rri
  1855. for i := 0; i < len(dns.Extra); i++ {
  1856. rrArr[rri] = dns.Extra[i].copy()
  1857. rri++
  1858. }
  1859. r1.Extra = rrArr[rrbegin:rri:rri]
  1860. }
  1861. return r1
  1862. }