blob: 56d3b7011aa10fcfd15037cbcbea8ccbc3f9b04b [file] [log] [blame]
Tim Windelschmidt6d33a432025-02-04 14:34:25 +01001// Copyright The Monogon Project Authors.
2// SPDX-License-Identifier: Apache-2.0
3
Jan Schär4a180222024-07-29 16:32:54 +02004package dns
5
6import (
7 "errors"
8 "fmt"
9 "net"
10
11 "github.com/miekg/dns"
12)
13
14// CreateTestRequest creates a Request for use in tests.
15func CreateTestRequest(qname string, qtype uint16, proto string) *Request {
16 var addr net.Addr
17 switch proto {
18 case "udp":
19 addr = &net.UDPAddr{}
20 case "tcp":
21 addr = &net.TCPAddr{}
22 default:
23 panic(fmt.Sprintf("Unknown protocol %q", proto))
24 }
25 req := &Request{
26 Reply: new(dns.Msg),
27 Writer: &testWriter{addr: addr},
28 Qopt: &dns.OPT{Hdr: dns.RR_Header{Name: ".", Rrtype: dns.TypeOPT}},
29 Ropt: &dns.OPT{Hdr: dns.RR_Header{Name: ".", Rrtype: dns.TypeOPT}},
30 Qname: qname,
31 QnameCanonical: dns.CanonicalName(qname),
32 Qtype: qtype,
33 }
34 req.Reply.Response = true
35 req.Reply.Question = []dns.Question{{
36 Name: qname,
37 Qtype: qtype,
38 Qclass: dns.ClassINET,
39 }}
40 req.Reply.RecursionAvailable = true
41 req.Reply.RecursionDesired = true
42 req.Qopt.SetUDPSize(advertiseUDPSize)
43 req.Ropt.SetUDPSize(advertiseUDPSize)
44 return req
45}
46
47type testWriter struct {
48 addr net.Addr
49 msg *dns.Msg
50}
51
52func (t *testWriter) LocalAddr() net.Addr { return t.addr }
53func (t *testWriter) RemoteAddr() net.Addr { return t.addr }
54func (*testWriter) Write([]byte) (int, error) {
55 return 0, errors.New("testWriter only supports WriteMsg")
56}
57func (*testWriter) Close() error { return nil }
58func (*testWriter) TsigStatus() error { return nil }
59func (*testWriter) TsigTimersOnly(bool) {}
60func (*testWriter) Hijack() {}
61
62func (t *testWriter) WriteMsg(msg *dns.Msg) error {
63 if msg == nil {
64 panic("WriteMsg(nil)")
65 }
66 if t.msg != nil {
67 panic("duplicate WriteMsg()")
68 }
69 t.msg = msg
70 return nil
71}