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