-
Notifications
You must be signed in to change notification settings - Fork 18.7k
/
resolver_unix.go
83 lines (74 loc) · 2.51 KB
/
resolver_unix.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
//go:build !windows
package libnetwork
import (
"fmt"
"net"
"github.com/docker/docker/libnetwork/iptables"
)
const (
// output chain used for docker embedded DNS resolver
outputChain = "DOCKER_OUTPUT"
// postrouting chain used for docker embedded DNS resolver
postroutingChain = "DOCKER_POSTROUTING"
)
func (r *Resolver) setupIPTable() error {
if r.err != nil {
return r.err
}
laddr := r.conn.LocalAddr().String()
ltcpaddr := r.tcpListen.Addr().String()
resolverIP, ipPort, _ := net.SplitHostPort(laddr)
_, tcpPort, _ := net.SplitHostPort(ltcpaddr)
rules := [][]string{
{"-t", "nat", "-I", outputChain, "-d", resolverIP, "-p", "udp", "--dport", dnsPort, "-j", "DNAT", "--to-destination", laddr},
{"-t", "nat", "-I", postroutingChain, "-s", resolverIP, "-p", "udp", "--sport", ipPort, "-j", "SNAT", "--to-source", ":" + dnsPort},
{"-t", "nat", "-I", outputChain, "-d", resolverIP, "-p", "tcp", "--dport", dnsPort, "-j", "DNAT", "--to-destination", ltcpaddr},
{"-t", "nat", "-I", postroutingChain, "-s", resolverIP, "-p", "tcp", "--sport", tcpPort, "-j", "SNAT", "--to-source", ":" + dnsPort},
}
var setupErr error
err := r.backend.ExecFunc(func() {
// TODO IPv6 support
iptable := iptables.GetIptable(iptables.IPv4)
// insert outputChain and postroutingchain
if iptable.ExistsNative("nat", "OUTPUT", "-d", resolverIP, "-j", outputChain) {
if err := iptable.RawCombinedOutputNative("-t", "nat", "-F", outputChain); err != nil {
setupErr = err
return
}
} else {
if err := iptable.RawCombinedOutputNative("-t", "nat", "-N", outputChain); err != nil {
setupErr = err
return
}
if err := iptable.RawCombinedOutputNative("-t", "nat", "-I", "OUTPUT", "-d", resolverIP, "-j", outputChain); err != nil {
setupErr = err
return
}
}
if iptable.ExistsNative("nat", "POSTROUTING", "-d", resolverIP, "-j", postroutingChain) {
if err := iptable.RawCombinedOutputNative("-t", "nat", "-F", postroutingChain); err != nil {
setupErr = err
return
}
} else {
if err := iptable.RawCombinedOutputNative("-t", "nat", "-N", postroutingChain); err != nil {
setupErr = err
return
}
if err := iptable.RawCombinedOutputNative("-t", "nat", "-I", "POSTROUTING", "-d", resolverIP, "-j", postroutingChain); err != nil {
setupErr = err
return
}
}
for _, rule := range rules {
if iptable.RawCombinedOutputNative(rule...) != nil {
setupErr = fmt.Errorf("set up rule failed, %v", rule)
return
}
}
})
if err != nil {
return err
}
return setupErr
}