-
Notifications
You must be signed in to change notification settings - Fork 16
/
udpme.go
84 lines (73 loc) · 1.52 KB
/
udpme.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package main
import (
"flag"
"log"
"net"
"github.com/miekg/dns"
)
var (
listenAddr = flag.String("l", "127.0.0.1:5353", "listen address")
upstreamAddr = flag.String("u", "8.8.8.8", "upstream address")
testEDNS0 = flag.Bool("t", false, "test upstream edns0 support")
)
func main() {
flag.Parse()
if *testEDNS0 {
test()
return
}
run()
}
func test() {
m := new(dns.Msg)
m.SetQuestion("cloudflare.com.", dns.TypeA)
m.SetEdns0(512, false)
u := newUpstream(*upstreamAddr)
r, err := u.exchange(m)
if err != nil {
log.Printf("err: %s", err)
} else {
if opt := r.IsEdns0(); opt != nil {
log.Printf("edns0 response received")
} else {
log.Printf("response received without edns0")
}
}
}
func run() {
p, err := net.ListenPacket("udp", *listenAddr)
if err != nil {
log.Fatal(err)
}
log.Printf("server started at %s", *listenAddr)
u := newUpstream(*upstreamAddr)
readBuf := make([]byte, 64*1024)
for {
n, addr, err := p.ReadFrom(readBuf)
if err != nil {
log.Fatalf("listener err: %s", err)
}
q := new(dns.Msg)
if err := q.Unpack(readBuf[:n]); err != nil {
log.Printf("invalid incoming package from [%s], err: %s", addr, err)
continue
}
go func() {
r, err := u.exchange(q)
if err != nil {
log.Printf("err: %s", err)
r = new(dns.Msg)
r.SetReply(q)
r.Rcode = dns.RcodeServerFailure
}
if r != nil {
writeBuf, err := r.Pack()
if err != nil {
log.Printf("failed to pack response, %s", err)
return
}
p.WriteTo(writeBuf, addr)
}
}()
}
}