| Tim Windelschmidt | 6d33a43 | 2025-02-04 14:34:25 +0100 | [diff] [blame^] | 1 | // Copyright The Monogon Project Authors. |
| 2 | // SPDX-License-Identifier: Apache-2.0 |
| 3 | |
| Jan Schär | 4a18022 | 2024-07-29 16:32:54 +0200 | [diff] [blame] | 4 | package dns |
| 5 | |
| 6 | import ( |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "net" |
| 10 | |
| 11 | "github.com/miekg/dns" |
| 12 | ) |
| 13 | |
| 14 | // CreateTestRequest creates a Request for use in tests. |
| 15 | func 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 | |
| 47 | type testWriter struct { |
| 48 | addr net.Addr |
| 49 | msg *dns.Msg |
| 50 | } |
| 51 | |
| 52 | func (t *testWriter) LocalAddr() net.Addr { return t.addr } |
| 53 | func (t *testWriter) RemoteAddr() net.Addr { return t.addr } |
| 54 | func (*testWriter) Write([]byte) (int, error) { |
| 55 | return 0, errors.New("testWriter only supports WriteMsg") |
| 56 | } |
| 57 | func (*testWriter) Close() error { return nil } |
| 58 | func (*testWriter) TsigStatus() error { return nil } |
| 59 | func (*testWriter) TsigTimersOnly(bool) {} |
| 60 | func (*testWriter) Hijack() {} |
| 61 | |
| 62 | func (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 | } |