forked from opusb/tpclash2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.go
99 lines (87 loc) · 2.25 KB
/
template.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package main
import (
"net"
"os"
"regexp"
"text/template"
"github.com/sirupsen/logrus"
)
var confFuncsMap = template.FuncMap{
"IfName": getMainNic,
"MainNic": getMainNic,
"MainIP": getMainIP,
"DefaultDNS": getDefaultDNS,
}
func getMainNic() string {
ifaces, err := net.Interfaces()
if err != nil {
logrus.Errorf("[helper/if-name] failed to list network interfaces: %v", err)
return ""
}
for _, iface := range ifaces {
if iface.Flags&net.FlagLoopback == 0 && iface.Flags&net.FlagUp != 0 {
addrs, err := iface.Addrs()
if err != nil {
logrus.Errorf("[helper/if-name] failed to get addrs: %v", err)
return ""
}
for _, addr := range addrs {
if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
return iface.Name
}
}
}
}
}
logrus.Error("[helper/if-name] failed to get main interface")
return ""
}
func getMainIP() string {
ifaces, err := net.Interfaces()
if err != nil {
logrus.Errorf("[helper/if-name] failed to list network interfaces: %v", err)
return ""
}
for _, iface := range ifaces {
if iface.Flags&net.FlagLoopback == 0 && iface.Flags&net.FlagUp != 0 {
addrs, err := iface.Addrs()
if err != nil {
logrus.Errorf("[helper/if-name] failed to get addrs: %v", err)
return ""
}
for _, addr := range addrs {
if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
return ipnet.IP.To4().String()
}
}
}
}
}
logrus.Error("[helper/if-name] failed to get main interface")
return ""
}
func getDefaultDNS() []string {
resolvConf := "/run/systemd/resolve/resolv.conf"
_, err := os.Stat(resolvConf)
if err != nil {
resolvConf = "/etc/resolv.conf"
}
bs, err := os.ReadFile(resolvConf)
if err != nil {
logrus.Errorf("[helper/default-dns] failed to read resole.conf: %v", err)
return nil
}
regx := regexp.MustCompile(`(?m)^nameserver\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})`)
matches := regx.FindAllStringSubmatch(string(bs), -1)
if len(matches) == 0 {
logrus.Errorf("[helper/default-dns] failed to parse resole.conf: missing nameservers")
return nil
}
var servers []string
for _, match := range matches {
servers = append(servers, match[1])
}
return servers
}