forked from nextdns/nextdns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
activate.go
78 lines (72 loc) · 1.63 KB
/
activate.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
package main
import (
"errors"
"fmt"
"net"
"github.com/nextdns/nextdns/config"
"github.com/nextdns/nextdns/host"
"github.com/nextdns/nextdns/hosts"
)
func activation(args []string) error {
cmd := args[0]
var c config.Config
c.Parse("nextdns "+cmd, nil, true)
defer c.Save()
switch cmd {
case "activate":
c.AutoActivate = true
return activate(c)
case "deactivate":
c.AutoActivate = false
return deactivate()
default:
return fmt.Errorf("%s: unknown command", cmd)
}
}
func listenIP(listen string) (string, error) {
host, port, err := net.SplitHostPort(listen)
if err != nil {
return "127.0.0.1", nil
}
switch port {
case "53", "domain":
// Can only activate on default port
default:
return "", fmt.Errorf("activate: %s: non 53 port not supported", listen)
}
switch host {
case "", "0.0.0.0":
return "127.0.0.1", nil
case "::":
return "::1", nil
}
if net.ParseIP(host) != nil {
return host, nil
}
addrs := hosts.LookupHost(host)
if len(addrs) == 0 {
return "", fmt.Errorf("activate: %s: no address found", listen)
}
return addrs[0], nil
}
func activate(c config.Config) error {
if len(c.Listens) == 0 {
return errors.New("missing listen setting")
}
listen := c.Listens[0]
if c.SetupRouter {
// Setup router might make nextdns listen on a custom port so it can
// be chained behind dnsmasq for instance. To make the router use
// nextdns, we want it to go thru the whole chain so it benefits
// from dnsmasq cache.
listen = "127.0.0.1:53"
}
listenIP, err := listenIP(listen)
if err != nil {
return err
}
return host.SetDNS(listenIP)
}
func deactivate() error {
return host.ResetDNS()
}