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