Debian Codegraph @

msg.go

raw
1 package dns
2
3 import (
4 "crypto/rand"
5 "encoding/binary"
6 "fmt"
7 "io"
8 "iter"
9 "net"
10 "slices"
11 "strconv"
12
13 "codeberg.org/miekg/dns/internal/pack"
14 "codeberg.org/miekg/dns/internal/unpack"
15 "codeberg.org/miekg/dns/rdata"
16 "golang.org/x/crypto/cryptobyte"
17 )
18
19 // ID by default returns a 16-bit random number to be used as a message id. The
20 // number is drawn from a cryptographically secure random number generator.
21 // This being a variable the function can be reassigned to a custom function.
22 // For instance, to make it return a static value for testing:
23 //
24 // dns.ID = func() uint16 { return 3 }
25 var ID = id
26
27 // id returns a 16 bits random number to be used as a message id. The random provided should be good enough.
28 func id() uint16 {
29 var b [2]byte
30 _, err := rand.Read(b[:])
31 if err != nil {
32 panic("dns: reading random ID failed: " + err.Error())
33 }
34 return uint16(b[0])<<8 | uint16(b[1])
35 }
36
37 // ClassToString is a maps Classes to strings for each CLASS wire type.
38 var ClassToString = map[uint16]string{
39 ClassINET: "IN",
40 ClassCSNET: "CS",
41 ClassCHAOS: "CH",
42 ClassHESIOD: "HS",
43 ClassNONE: "NONE",
44 ClassANY: "ANY",
45 }
46
47 // OpcodeToString maps Opcodes to strings.
48 var OpcodeToString = map[uint8]string{
49 OpcodeQuery: "QUERY",
50 OpcodeIQuery: "IQUERY",
51 OpcodeStatus: "STATUS",
52 OpcodeNotify: "NOTIFY",
53 OpcodeUpdate: "UPDATE",
54 OpcodeStateful: "STATEFUL",
55 }
56
57 // RcodeToString maps Rcodes to strings.
58 var RcodeToString = map[uint16]string{
59 RcodeSuccess: "NOERROR",
60 RcodeFormatError: "FORMERR",
61 RcodeServerFailure: "SERVFAIL",
62 RcodeNameError: "NXDOMAIN",
63 RcodeNotImplemented: "NOTIMPL",
64 RcodeRefused: "REFUSED",
65 RcodeYXDomain: "YXDOMAIN", // See RFC 2136.
66 RcodeYXRrset: "YXRRSET",
67 RcodeNXRrset: "NXRRSET",
68 RcodeNotAuth: "NOTAUTH",
69 RcodeNotZone: "NOTZONE",
70 RcodeBadSig: "BADSIG", // Also known as RcodeBadVers "BADVERS", see RFC 6891.
71 RcodeStatefulNotImplemented: "DSOTYPENI",
72 RcodeBadKey: "BADKEY",
73 RcodeBadTime: "BADTIME",
74 RcodeBadMode: "BADMODE",
75 RcodeBadName: "BADNAME",
76 RcodeBadAlg: "BADALG",
77 RcodeBadTrunc: "BADTRUNC",
78 RcodeBadCookie: "BADCOOKIE",
79 }
80
81 // packQuestion packs an RR into a question section.
82 func packQuestion(rr RR, msg []byte, off int, compression map[string]uint16) (off1 int, err error) {
83 off, err = pack.Name(rr.Header().Name, msg, off, compression, false)
84 if err != nil {
85 return len(msg), err
86 }
87 rrtype := RRToType(rr)
88 off, err = pack.Uint16(rrtype, msg, off)
89 if err != nil {
90 return len(msg), err
91 }
92
93 off, err = pack.Uint16(rr.Header().Class, msg, off)
94 if err != nil {
95 return len(msg), err
96 }
97 return off, nil
98 }
99
100 func packRR(rr RR, msg []byte, off int, compression map[string]uint16) (headerEnd int, off1 int, err error) {
101 rrtype := RRToType(rr)
102 headerEnd, err = rr.Header().packHeader(msg, off, rrtype, compression)
103 if err != nil {
104 return headerEnd, len(msg), err
105 }
106 off1, err = zpack(rr, msg, headerEnd, compression)
107 if err != nil {
108 return headerEnd, len(msg), err
109 }
110
111 rdlength := off1 - headerEnd
112 if rdlength <= MaxMsgSize { // overflow
113 // The RDLENGTH field is the last field in the header and we set it here.
114 binary.BigEndian.PutUint16(msg[headerEnd-2:], uint16(rdlength))
115 return headerEnd, off1, nil
116 }
117
118 return headerEnd, len(msg), pack.Errorf("inconsistent rdata length")
119 }
120
121 func unpackRR(msg *cryptobyte.String, msgBuf []byte) (RR, error) {
122 h := &Header{}
123 typ, rdlength, err := unpackHeader(h, msg, msgBuf)
124 if err != nil {
125 return nil, err
126 }
127
128 // Directly use the existing buffer by slicing the cryptobyte.String
129 // 1. Verify sufficient bytes remain
130 if len(*msg) < int(rdlength) {
131 return nil, unpack.ErrTruncatedMessage
132 }
133
134 // was: msg.ReadBytes(&data, int(rdlength)), but we want to save the buffer we allocated for that.
135 data := (*msg)[:rdlength]
136 *msg = (*msg)[rdlength:]
137 msgBuf = msgBuf[:unpack.Offset(*msg, msgBuf)]
138
139 var rr RR
140 if newFn, ok := TypeToRR[typ]; ok {
141 rr = newFn()
142 *rr.Header() = *h
143 } else {
144 rr = &RFC3597{Hdr: *h, RRType: typ}
145 }
146
147 if rdlength == 0 {
148 return rr, nil
149 }
150
151 if err := zunpack(rr, cryptobyte.String(data), msgBuf); err != nil {
152 return rr, err
153 }
154
155 return rr, nil
156 }
157
158 // Reset resets the message's answer, ns, extra and pseudo sections to a zero length slice, thereby emptying
159 // them, but keeping the capacity.
160 func (m *Msg) Reset() {
161 m.Answer, m.Ns, m.Extra, m.Pseudo = m.Answer[:0], m.Ns[:0], m.Extra[:0], m.Pseudo[:0]
162 }
163
164 // Packs packs the message m into m.Data.
165 func (m *Msg) Pack() error {
166 if l := m.Len(); cap(m.Data) < l {
167 m.Data = make([]byte, l)
168 } else {
169 m.Data = m.Data[:l]
170 }
171
172 off, err := pack.Uint16(m.ID, m.Data, 0)
173 if err != nil {
174 return pack.Errorf(": %s", "MsgHeader ID")
175 }
176
177 bits := uint16(m.Opcode)<<11 | uint16(m.Rcode&0xF)
178 if m.Response {
179 bits |= _QR
180 }
181 if m.Authoritative {
182 bits |= _AA
183 }
184 if m.Truncated {
185 bits |= _TC
186 }
187 if m.RecursionDesired {
188 bits |= _RD
189 }
190 if m.RecursionAvailable {
191 bits |= _RA
192 }
193 if m.Zero {
194 bits |= _Z
195 }
196 if m.AuthenticatedData {
197 bits |= _AD
198 }
199 if m.CheckingDisabled {
200 bits |= _CD
201 }
202
203 off, err = pack.Uint16(bits, m.Data, off)
204 if err != nil {
205 return pack.Errorf(": %s", "MsgHeader bits")
206 }
207
208 isPseudo := m.isPseudo()
209 counts := uint64(len(m.Question))<<48 |
210 uint64(len(m.Answer))<<32 |
211 uint64(len(m.Ns))<<16 |
212 uint64(len(m.Extra)+isPseudo)
213
214 off, err = pack.Uint64(counts, m.Data, off)
215 if err != nil {
216 return pack.Errorf(": %s", "MsgHeader")
217 }
218
219 // Is this compressible?
220 var compression map[string]uint16
221 if l := len(m.Answer) + len(m.Ns) + len(m.Extra); l > 0 {
222 compression = make(map[string]uint16, l+3) // 3 is randomly chosen, as that much rdata might be compressable...
223 }
224
225 for i := range m.Question {
226 if off, err = packQuestion(m.Question[i], m.Data, off, compression); err != nil {
227 return err
228 }
229 }
230
231 for i := range m.Answer {
232 if _, off, err = packRR(m.Answer[i], m.Data, off, compression); err != nil {
233 return err
234 }
235 }
236 for i := range m.Ns {
237 if _, off, err = packRR(m.Ns[i], m.Data, off, compression); err != nil {
238 return err
239 }
240 }
241 for i := range m.Extra {
242 if _, off, err = packRR(m.Extra[i], m.Data, off, compression); err != nil {
243 return err
244 }
245 }
246
247 // Add an OPT RR if we see any of these.
248 tsigOrsig0 := false
249 if isPseudo > 0 {
250 opt := &OPT{} // hack, empty name, that gets filled if we did something
251 if m.UDPSize > MinMsgSize {
252 opt.Hdr.Name = "."
253 opt.setUDPSize(m.UDPSize)
254 }
255 if m.Rcode > 0xF {
256 opt.Hdr.Name = "."
257 opt.setRcode(m.Rcode) // we leave m.Rcode as packing/unpacking will set the correct bits there.
258 }
259 if m.Security {
260 opt.Hdr.Name = "."
261 opt.setSecurity(true)
262 }
263 if m.CompactAnswers {
264 opt.Hdr.Name = "."
265 opt.setCompactAnswers(true)
266 }
267 if m.Delegation {
268 opt.Hdr.Name = "."
269 opt.setDelegation(true)
270 }
271 if m.Version > 0 {
272 opt.Hdr.Name = "."
273 opt.setVersion(m.Version)
274 }
275 if m.Z > 0 {
276 opt.Hdr.Name = "."
277 opt.setZ(m.Z)
278 }
279 for i := range m.Pseudo {
280 switch x := m.Pseudo[i].(type) {
281 case EDNS0:
282 opt.Hdr.Name = "."
283 opt.Options = append(opt.Options, x)
284 default:
285 tsigOrsig0 = true
286 }
287 }
288 // Only pack opt if something has been put into it, otherwise we may have a TSIG/SIG0.
289 // Pack it here so we don't add it the m.Extra, as the options (only) should be available in pseudo.
290 // Also OPT may be anywhere in m.Extra, here it will be first.
291 if len(opt.Hdr.Name) != 0 {
292 if _, off, err = packRR(opt, m.Data, off, nil); err != nil {
293 return err
294 }
295 }
296 }
297
298 // records that really need to be last, TSIG or SGI0. "Checked" above, we just assume it is the last.
299 if tsigOrsig0 {
300 if _, off, err = packRR(m.Pseudo[len(m.Pseudo)-1], m.Data, off, compression); err != nil {
301 return err
302 }
303 }
304 m.Data = m.Data[:off]
305 return nil
306 }
307
308 // We only allow a single question in the question section.
309 func (m *Msg) unpackQuestion(msg *cryptobyte.String, msgBuf []byte) (RR, error) {
310 name, err := unpack.Name(msg, msgBuf)
311 if err != nil {
312 return nil, err
313 }
314 if msg.Empty() || !msg.ReadUint16(&m.qtype) {
315 return nil, unpack.Errorf("overflow %s", "Question type")
316 }
317 if msg.Empty() || !msg.ReadUint16(&m.qclass) {
318 return nil, unpack.Errorf("overflow %s", "Question class")
319 }
320
321 var rr RR
322 if newFn, ok := TypeToRR[m.qtype]; ok {
323 rr = newFn()
324 *rr.Header() = Header{Name: name, Class: m.qclass}
325 } else {
326 rr = &RFC3597{Header{Name: name, Class: m.qclass}, rdata.RFC3597{RRType: m.qtype}}
327 }
328 return rr, nil
329 }
330
331 func (m *Msg) unpackQuestions(cnt uint16, msg *cryptobyte.String, msgBuf []byte) ([]RR, error) {
332 // We don't preallocate dst according to cnt as that value may be attacker
333 // controlled. A malicious adversary could send us as 12-byte packet
334 // containing only the header that claims to contain 65535 questions. As
335 // Question takes 24-bytes, we'd end up allocating more than 1.5MiB from a
336 // mere 12-byte packet.
337 dst := make([]RR, 0, 1)
338 for i := 0; i < int(cnt); i++ {
339 r, err := m.unpackQuestion(msg, msgBuf)
340 if err != nil {
341 return dst, err
342 }
343 dst = append(dst, r)
344 }
345 return dst, nil
346 }
347
348 func unpackRRs(cnt uint16, msg *cryptobyte.String, msgBuf []byte) ([]RR, error) {
349 if cnt == 0 {
350 return nil, nil
351 }
352 // See unpackQuestions for why we don't pre-allocate here.
353 dst := make([]RR, 0, min(3, cnt))
354 for i := 0; i < int(cnt); i++ {
355 r, err := unpackRR(msg, msgBuf)
356 if err != nil {
357 return dst, err
358 }
359 dst = append(dst, r)
360 }
361
362 return dst, nil
363 }
364
365 // Unpack unpacks a binary message that sits in m.Data to a Msg structure.
366 func (m *Msg) Unpack() (err error) {
367 s := cryptobyte.String(m.Data)
368 var (
369 counts uint64 // read all counters into 64 bits and slice the 16 bits values out of it
370 bits uint16
371 )
372 if !s.ReadUint16(&m.ID) || !s.ReadUint16(&bits) || !s.ReadUint64(&counts) {
373 return unpack.Errorf("overflow %s", "MsgHeader")
374 }
375 m.Response = bits&_QR != 0
376 m.Opcode = uint8(bits>>11) & 0xF
377 m.Authoritative = bits&_AA != 0
378 m.Truncated = bits&_TC != 0
379 m.RecursionDesired = bits&_RD != 0
380 m.RecursionAvailable = bits&_RA != 0
381 m.Zero = bits&_Z != 0 // _Z covers the zero bit, which should be zero; not sure why we set it to the opposite.
382 m.AuthenticatedData = bits&_AD != 0
383 m.CheckingDisabled = bits&_CD != 0
384 m.Rcode = bits & 0xF
385
386 if m.Options > 0 && m.Options <= MsgOptionUnpackHeader {
387 return nil
388 }
389
390 if m.offset > MsgHeaderSize {
391 if !s.Skip(int(m.offset - MsgHeaderSize)) {
392 return unpack.Errorf("overflow %s", "MsgHeader")
393 }
394 goto Rest
395 }
396
397 if m.Question, err = m.unpackQuestions(uint16((counts>>48)&0xFFFF), &s, m.Data); err != nil {
398 return err
399 }
400 if m.Options > 0 && m.Options <= MsgOptionUnpackQuestion {
401 m.offset = uint16(len(m.Data) - len(s))
402 return nil
403 }
404
405 Rest:
406 m.offset = 0 // reset offset here, as it has done its purpose
407 if m.Answer, err = unpackRRs(uint16((counts>>32)&0xFFFF), &s, m.Data); err != nil {
408 return err
409 }
410 if m.Options > 0 && m.Options <= MsgOptionUnpackAnswer {
411 return nil
412 }
413
414 if m.Ns, err = unpackRRs(uint16((counts>>16)&0xFFFF), &s, m.Data); err != nil {
415 return err
416 }
417
418 if m.Extra, err = unpackRRs(uint16(counts&0xFFFF), &s, m.Data); err != nil {
419 return err
420 }
421
422 // Check for the OPT/TSIG/SIG RR and move it to the Pseudo section.
423 m.Pseudo = m.Pseudo[:0] // Reset pseudo as we need to fill it from the Extra section.
424 counts = 0 // reuse counts, use the two 32 bit halves
425 for i := len(m.Extra) - 1; i >= 0; i-- {
426
427 switch opt := m.Extra[i].(type) {
428 case *OPT:
429 if uint32(counts) > 0 {
430 return unpack.Errorf("multiple OPT RRs")
431 }
432
433 m.Security = opt.security()
434 m.CompactAnswers = opt.compactAnswers()
435 m.Delegation = opt.delegation()
436 m.Z = opt.z()
437 m.Rcode += opt.rcode() // See TestMsgExtendedRcode.
438 m.Version = opt.version()
439 // RFC 6891 mandates that the payload size in an OPT record less than 512 (MinMsgSize) bytes must be treated as equal to 512 bytes.
440 m.UDPSize = max(opt.udpSize(), MinMsgSize)
441
442 // We are travelling backwards through the options, so add them in reverse too, i.e. in front.
443 // Make space for len(opt.Options) RRs to be put there. This avoids having to: make([]RR, len(opt.Options)).
444 m.Pseudo = append(m.Pseudo[:0], append(make([]RR, len(opt.Options)), m.Pseudo[0:]...)...)
445 for j := range opt.Options {
446 m.Pseudo[j] = RR(opt.Options[j])
447 }
448 m.Extra[i] = nil // sentinel value, deleted after the loop
449
450 counts = counts&^0xFFFFFFFF | 1
451
452 case *TSIG, *SIG:
453 if uint32(counts>>32) > 0 {
454 return unpack.Errorf("multiple TSIG/SIG RRs")
455 }
456
457 m.Pseudo = append([]RR{m.Extra[i]}, m.Pseudo...)
458 m.Extra[i] = nil // sentinel
459
460 counts += 1 << 32
461 }
462 }
463 if !s.Empty() {
464 return unpack.Errorf("%d more octets", len(s))
465 }
466
467 // TODO(miek): might it be possible, to do this in the loop - I've tried, but switching elements while
468 // looping remained problematic. For now, another loop over m.Extra.
469 m.Extra = slices.DeleteFunc(m.Extra, func(rr RR) bool { return rr == nil })
470
471 return nil
472 }
473
474 // Convert a complete message to a string with dig-like output. String also looks at the [Msg.Options] and
475 // only prints up to that point, i.e. options set to [MsgOptionUnpackHeader] means String will only return the
476 // header. The string format isn't fixed and can change in future releases.
477 func (m *Msg) String() string {
478 if m == nil {
479 return "<nil> Msg"
480 }
481 sb := builderPool.Get()
482
483 sb.WriteString(m.MsgHeader.String())
484 // if core EDNS flags are set, we print this (flags are already handled in MsgHeader)
485 if m.UDPSize > 0 || m.Security || m.CompactAnswers || m.Delegation || m.Z > 0 {
486 sb.WriteString(";; EDNS, version: ")
487 sb.WriteString(strconv.Itoa(int(m.Version)))
488 sb.WriteString(", udp: ")
489 sb.WriteString(strconv.Itoa(int(m.UDPSize)))
490 sb.WriteByte('\n')
491 }
492
493 sections := [5]string{"QUESTION", "PSEUDO", "ANSWER", "AUTHORITY", "ADDITIONAL"}
494 const (
495 Question = iota
496 Pseudo
497 Answer
498 Authority
499 Additional
500 // Stateful
501 )
502 sb.WriteString(";; ")
503 sb.WriteString(sections[Question])
504 sb.WriteString(": ")
505 sb.WriteString(strconv.Itoa(len(m.Question)))
506 sb.WriteString(", ")
507
508 sb.WriteString(sections[Pseudo])
509 sb.WriteString(": ")
510 sb.WriteString(strconv.Itoa(len(m.Pseudo)))
511 sb.WriteString(", ")
512
513 sb.WriteString(sections[Answer])
514 sb.WriteString(": ")
515 sb.WriteString(strconv.Itoa(len(m.Answer)))
516 sb.WriteString(", ")
517
518 sb.WriteString(sections[Authority])
519 sb.WriteString(": ")
520 sb.WriteString(strconv.Itoa(len(m.Ns)))
521 sb.WriteString(", ")
522
523 sb.WriteString(sections[Additional])
524 sb.WriteString(": ")
525 sb.WriteString(strconv.Itoa(len(m.Extra)))
526 sb.WriteString(", ")
527
528 sb.WriteString("DATA SIZE: ")
529 sb.WriteString(strconv.Itoa(len(m.Data)))
530 sb.WriteByte('\n')
531
532 if m.Options > 0 && m.Options <= MsgOptionUnpackHeader {
533 return sb.String()
534 }
535
536 if len(m.Question) > 0 {
537 sb.WriteString("\n;; ")
538 sb.WriteString(sections[Question])
539 sb.WriteString(" SECTION:\n")
540 for _, r := range m.Question {
541 // as we fake RRs to be present in the question section, just manual unpack print the header without the TTL here.
542 sb.WriteString(r.Header().Name)
543 sb.WriteByte('\t')
544 sb.WriteByte('\t')
545 sb.WriteString(classToString(r.Header().Class))
546 sb.WriteByte('\t')
547 rrtype := RRToType(r)
548 if rrtype == 0 {
549 if r1, ok := r.(*RFC3597); ok {
550 rrtype = r1.RRType
551 }
552 }
553 sb.WriteString(typeToString(rrtype))
554 sb.WriteByte('\n')
555 }
556 }
557 if m.Options > 0 && m.Options <= MsgOptionUnpackQuestion {
558 return sb.String()
559 }
560 if len(m.Pseudo) > 0 {
561 sb.WriteString("\n;; ")
562 sb.WriteString(sections[Pseudo])
563 sb.WriteString(" SECTION:\n")
564 for _, r := range m.Pseudo {
565 sb.WriteString(r.String())
566 sb.WriteByte('\n')
567 }
568 }
569 if len(m.Answer) > 0 {
570 sb.WriteString("\n;; ")
571 sb.WriteString(sections[Answer])
572 sb.WriteString(" SECTION:\n")
573 for _, r := range m.Answer {
574 sb.WriteString(r.String())
575 sb.WriteByte('\n')
576 }
577 }
578 if m.Options > 0 && m.Options <= MsgOptionUnpackAnswer {
579 return sb.String()
580 }
581 if len(m.Ns) > 0 {
582 sb.WriteString("\n;; ")
583 sb.WriteString(sections[Authority])
584 sb.WriteString(" SECTION:\n")
585 for _, r := range m.Ns {
586 sb.WriteString(r.String())
587 sb.WriteByte('\n')
588 }
589 }
590 if len(m.Extra) > 0 {
591 sb.WriteString("\n;; ")
592 sb.WriteString(sections[Additional])
593 sb.WriteString(" SECTION:\n")
594 for _, r := range m.Extra {
595 sb.WriteString(r.String())
596 sb.WriteByte('\n')
597 }
598 }
599 s := sb.String()
600 builderPool.Put(sb)
601 return s
602 }
603
604 // isPseudo returns (1 or 2) if we should have a pseudo section in this message, or not (0). It returns an
605 // int becuse we need that number of the Extra section sizing.
606 func (m *Msg) isPseudo() int {
607 n := 0
608 if m.UDPSize > MinMsgSize || m.Security || m.CompactAnswers || m.Delegation || m.Z > 0 || m.Rcode > 0xF {
609 n = 1
610 }
611 lp := len(m.Pseudo)
612 if lp > 0 {
613 switch m.Pseudo[lp-1].(type) {
614 case *TSIG:
615 n++
616 case *SIG:
617 n++
618 default:
619 if n == 0 { // not any of the message options are set
620 n = 1
621 }
622 }
623 }
624 return n
625 }
626
627 // Len returns the message length when in uncompressed wire format.
628 func (m *Msg) Len() int {
629 l := MsgHeaderSize
630
631 for i := range m.Question {
632 // See Header.Len() too, we always add a +1, even if the name is the root label.
633 // 4 is for the type and class
634 l += len(m.Question[i].Header().Name) + 1 + 4
635 break
636 }
637 for i := range m.Answer {
638 l += m.Answer[i].Len()
639 }
640 for i := range m.Ns {
641 l += m.Ns[i].Len()
642 }
643 for i := range m.Extra {
644 l += m.Extra[i].Len()
645 }
646 for i := range m.Pseudo {
647 l += m.Pseudo[i].Len()
648 }
649
650 // Smallest possible RR header where the name is the root label. This should actually be 11, but we return
651 // len(name) +1 for all domain names, which is not correct for the root which is just 1.
652 const minHeaderSize = 12
653
654 // isPseudo call is basically already done in the above loop where we get the length, only things left
655 // are the extra checks we do here. See [isPseudo] and keep in sync.
656 if len(m.Pseudo) > 0 || m.UDPSize > MinMsgSize || m.Security || m.CompactAnswers || m.Delegation || m.Z > 0 || m.Rcode > 0xF {
657 // If we find things in pseudo we get an OPT RR (fix length) plus the length of the option. OPT is always 11, 10 + "." (root label)
658 // In case of only a TSIG/SIG0 we overestimate, but because of speed we don't want to the full i.Pseudo check.
659 l += minHeaderSize
660 }
661
662 return min(l, MaxMsgSize)
663 }
664
665 // Hijack allows user hijacking the allocation in m.Data; this means that when the message is written through
666 // the default ResponseWriter its buffer is not returned the message pool. This is only applicable when the
667 // message was created by the default server.
668 func (m *Msg) Hijack() { m.hijacked.Store(true) }
669
670 // io.Reader and io.Writer interfaces implementation.
671
672 // Write writes the buffer p to the m.Data. If m's Data buffer is empty [Msg.Pack] is called.
673 func (m *Msg) Write(p []byte) (n int, err error) {
674 if len(m.Data) == 0 {
675 if err := m.Pack(); err != nil {
676 return 0, err
677 }
678 }
679 n = copy(m.Data, p)
680 return n, nil
681 }
682
683 // Read reads the data from m.Data into p. If m's Data buffer is empty [Msg.Pack] is called.
684 func (m *Msg) Read(p []byte) (n int, err error) {
685 // TODO(miek): pool allocation here?
686 if len(m.Data) == 0 {
687 if err := m.Pack(); err != nil {
688 return 0, err
689 }
690 }
691 n = copy(p, m.Data)
692 if len(p) > len(m.Data) {
693 return n, io.EOF
694 }
695 return n, nil
696 }
697
698 // WriteTo writes the message to w. w must be a [ResponseWriter], when w is _not_ a *net.UDPConn, the write is
699 // prefixed with an uint16 with the length of the buffer, otherwise the m.Data is written as-is. If w is a
700 // [ResponseController] a write timeout is applied.
701 //
702 // If the message has not be hijacked, and m was create by the server, the Data buffer is returned
703 // to the server's pool and zeroed out in m.
704 func (m *Msg) WriteTo(w io.Writer) (int64, error) {
705 r, ok := w.(ResponseWriter)
706 if !ok {
707 return 0, fmt.Errorf("dns: writer is not a ResponseWriter")
708 }
709
710 if len(m.Data) == 0 {
711 if err := m.Pack(); err != nil {
712 return 0, err
713 }
714 }
715
716 if rc, ok := w.(ResponseController); ok {
717 rc.SetWriteDeadline()
718 }
719
720 if sock, ok := r.Conn().(*net.UDPConn); ok {
721 sess := r.Session()
722 if sess != nil {
723 oob := sourceFromOOB(sess.OOB)
724 n, _, err := sock.WriteMsgUDP(m.Data, oob, sess.Addr)
725 msgPut(m)
726 return int64(n), err
727 }
728
729 n, err := r.Conn().Write(m.Data)
730 msgPut(m)
731 return int64(n), err
732 }
733
734 l := make([]byte, 2)
735 binary.BigEndian.PutUint16(l, uint16(len(m.Data)))
736 l = append(l, m.Data...)
737 n, err := r.Write(l)
738 msgPut(m)
739 return int64(n), err
740 }
741
742 // msgPut puts the message's buffer back in the pool, if desired.
743 func msgPut(m *Msg) {
744 if m.msgPool == nil {
745 return
746 }
747 if m.hijacked.Load() {
748 return
749 }
750 m.msgPool.Put(m.Data)
751 m.Data, m.msgPool = nil, nil
752 }
753
754 // ReadFrom reads from r. When r is a *net.TCPConn, first 2 bytes of length are read, then m.Data is *resized*
755 // to this length and the data is read. Otherwise the data is read into m.Data. It is expected any deadlines
756 // are set if there is an underlying socket. No read timeouts are applied.
757 func (m *Msg) ReadFrom(r io.Reader) (int64, error) {
758 if len(m.Data) == 0 {
759 if err := m.Pack(); err != nil {
760 return 0, err
761 }
762 }
763
764 if sock, ok := r.(*net.UDPConn); ok {
765 n, err := sock.Read(m.Data)
766 m.Data = m.Data[:n]
767 return int64(n), err
768 }
769
770 // When doing io.Copy that underlaying type we get from net is net.tcpConnWithoutWriteTo, not a
771 // net.TCPConn.For udp this seems not to be the case, so the fallthrough when things are not UDP like
772 // is to assume TCP.
773
774 l := uint16(0)
775 if err := binary.Read(r, binary.BigEndian, &l); err != nil {
776 return 0, err
777 }
778 if l < MsgHeaderSize {
779 // ignore remaining data
780 return int64(l), fmt.Errorf("dns: message size %d, can not be smaller than %d", l, MsgHeaderSize)
781 }
782
783 li := int(l)
784 if len(m.Data) < li {
785 m.Data = append(m.Data, make([]byte, li-len(m.Data))...)
786 } else {
787 m.Data = m.Data[:li]
788 }
789 n, err := io.ReadFull(r, m.Data)
790 m.Data = m.Data[:n]
791 if err == nil && n != li {
792 return int64(n), fmt.Errorf("dns: message size %d does not match prefix %d", li, n)
793 }
794 return int64(n), err
795 }
796
797 // All allows ranging over the RRs of all the sections in m. This includes the question, pseudo and stateful
798 // sections. See [ZoneParser.RRs] also.
799 func (m *Msg) All() iter.Seq[RR] {
800 return func(yield func(RR) bool) {
801 for i := range m.Question {
802 if !yield(m.Question[i]) {
803 return
804 }
805 }
806 for i := range m.Answer {
807 if !yield(m.Answer[i]) {
808 return
809 }
810 }
811 for i := range m.Ns {
812 if !yield(m.Ns[i]) {
813 return
814 }
815 }
816 for i := range m.Extra {
817 if !yield(m.Extra[i]) {
818 return
819 }
820 }
821 for i := range m.Pseudo {
822 if !yield(m.Pseudo[i]) {
823 return
824 }
825 }
826 }
827 }
828
829 // Copy returns a shallow copy of the message, specifically the RR contained in the message are copied by
830 // reference, not via a deep copy. If m was hijacked via [Msg.Hijack] the returned Msg will not be hijacked.
831 // The msgPool of m will not be copied, meaning the new message's buffer will not be returned to the pool, but
832 // be garbage collected.
833 func (m *Msg) Copy() *Msg {
834 return &Msg{
835 MsgHeader: m.MsgHeader,
836 Question: m.Question,
837 Answer: m.Answer,
838 Ns: m.Ns,
839 Extra: m.Extra,
840 Pseudo: m.Pseudo,
841 Data: m.Data,
842 }
843 }
844
845 // NewMsg returns a new message with the question section sets to z (z is made fully qualified) and the type t. If the type isn't know nil
846 // is returned, the recursion desired bit is set. If c is given it is used as the class.
847 func NewMsg(z string, t uint16, c ...uint16) *Msg {
848 var rr RR
849 newFn, ok := TypeToRR[t]
850 if !ok {
851 return nil
852 }
853 m := new(Msg)
854 m.ID = ID()
855 m.RecursionDesired = true
856 rr = newFn()
857 rr.Header().Name = dnsutilFqdn(z)
858 rr.Header().Class = ClassINET
859 if len(c) > 0 {
860 rr.Header().Class = c[0]
861 }
862 m.Question = []RR{rr}
863 return m
864 }