-
Notifications
You must be signed in to change notification settings - Fork 295
/
util.go
244 lines (224 loc) · 5.48 KB
/
util.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
package util
import (
"context"
"errors"
"fmt"
"github.com/nxtrace/NTrace-core/config"
"log"
"net"
"net/url"
"os"
"runtime"
"strings"
"sync"
"github.com/fatih/color"
)
var Uninterrupted = GetenvDefault("NEXTTRACE_UNINTERRUPTED", "")
var EnvToken = GetenvDefault("NEXTTRACE_TOKEN", "")
var UserAgent = fmt.Sprintf("NextTrace %s/%s/%s", config.Version, runtime.GOOS, runtime.GOARCH)
var RdnsCache sync.Map
var PowProviderParam = ""
var DisableMPLS = GetenvDefault("NEXTTRACE_DISABLEMPLS", "")
var EnableHidDstIP = GetenvDefault("NEXTTRACE_ENABLEHIDDENDSTIP", "")
var DestIP string
func LookupAddr(addr string) ([]string, error) {
// 如果在缓存中找到,直接返回
if hostname, ok := RdnsCache.Load(addr); ok {
//fmt.Println("hit RdnsCache for", addr, hostname)
return []string{hostname.(string)}, nil
}
// 如果缓存中未找到,进行 DNS 查询
names, err := net.LookupAddr(addr)
if err != nil {
return nil, err
}
// 将查询结果存入缓存
if len(names) > 0 {
RdnsCache.Store(addr, names[0])
}
return names, nil
}
// LocalIPPort get the local ip and port based on our destination ip
func LocalIPPort(dstip net.IP) (net.IP, int) {
serverAddr, err := net.ResolveUDPAddr("udp", dstip.String()+":12345")
if err != nil {
log.Fatal(err)
}
// We don't actually connect to anything, but we can determine
// based on our destination ip what source ip we should use.
if con, err := net.DialUDP("udp", nil, serverAddr); err == nil {
defer con.Close()
if udpaddr, ok := con.LocalAddr().(*net.UDPAddr); ok {
return udpaddr.IP, udpaddr.Port
}
}
return nil, -1
}
func LocalIPPortv6(dstip net.IP) (net.IP, int) {
serverAddr, err := net.ResolveUDPAddr("udp", "["+dstip.String()+"]:12345")
if err != nil {
log.Fatal(err)
}
// We don't actually connect to anything, but we can determine
// based on our destination ip what source ip we should use.
if con, err := net.DialUDP("udp", nil, serverAddr); err == nil {
defer con.Close()
if udpaddr, ok := con.LocalAddr().(*net.UDPAddr); ok {
return udpaddr.IP, udpaddr.Port
}
}
return nil, -1
}
func DomainLookUp(host string, ipVersion string, dotServer string, disableOutput bool) (net.IP, error) {
// ipVersion: 4, 6, all
var (
r *net.Resolver
ips []net.IP
)
switch dotServer {
case "dnssb":
r = DNSSB()
case "aliyun":
r = Aliyun()
case "dnspod":
r = Dnspod()
case "google":
r = Google()
case "cloudflare":
r = Cloudflare()
default:
r = newUDPResolver()
}
ipsStr, err := r.LookupHost(context.Background(), host)
for _, v := range ipsStr {
ips = append(ips, net.ParseIP(v))
}
if err != nil {
return nil, errors.New("DNS lookup failed")
}
//var ipv6Flag = false
//TODO: 此处代码暂无意义
//if ipv6Flag {
// fmt.Println("[Info] IPv6 UDP Traceroute is not supported right now.")
// if len(ips) == 0 {
// os.Exit(0)
// }
//}
// Filter by IPv4/IPv6
if ipVersion != "all" {
var filteredIPs []net.IP
for _, ip := range ips {
if ipVersion == "4" && ip.To4() != nil {
filteredIPs = []net.IP{ip}
break
} else if ipVersion == "6" && strings.Contains(ip.String(), ":") {
filteredIPs = []net.IP{ip}
break
}
}
ips = filteredIPs
}
if (len(ips) == 1) || (disableOutput) {
return ips[0], nil
} else {
fmt.Println("Please Choose the IP You Want To TraceRoute")
for i, ip := range ips {
fmt.Fprintf(color.Output, "%s %s\n",
color.New(color.FgHiYellow, color.Bold).Sprintf("%d.", i),
color.New(color.FgWhite, color.Bold).Sprintf("%s", ip),
)
}
var index int
fmt.Printf("Your Option: ")
_, err := fmt.Scanln(&index)
if err != nil {
index = 0
}
if index >= len(ips) || index < 0 {
fmt.Println("Your Option is invalid")
os.Exit(3)
}
return ips[index], nil
}
}
func GetenvDefault(key, defVal string) string {
val, ok := os.LookupEnv(key)
if ok {
_, ok := os.LookupEnv("NEXTTRACE_DEBUG")
if ok {
fmt.Println("ENV", key, "detected as", val)
}
return val
}
return defVal
}
func GetHostAndPort() (host string, port string) {
var hostP = GetenvDefault("NEXTTRACE_HOSTPORT", "origin-fallback.nxtrace.org")
// 解析域名
hostArr := strings.Split(hostP, ":")
// 判断是否有指定端口
if len(hostArr) > 1 {
// 判断是否为 IPv6
if strings.HasPrefix(hostP, "[") {
tmp := strings.Split(hostP, "]")
host = tmp[0]
host = host[1:]
if port = tmp[1]; port != "" {
port = port[1:]
}
} else {
host, port = hostArr[0], hostArr[1]
}
} else {
host = hostP
}
if port == "" {
// 默认端口
port = "443"
}
return
}
func GetProxy() *url.URL {
proxyURLStr := GetenvDefault("NEXTTRACE_PROXY", "")
if proxyURLStr == "" {
return nil
}
proxyURL, err := url.Parse(proxyURLStr)
if err != nil {
log.Println("Failed to parse proxy URL:", err)
return nil
}
return proxyURL
}
func GetPowProvider() string {
var powProvider string
if PowProviderParam == "" {
powProvider = GetenvDefault("NEXTTRACE_POWPROVIDER", "api.nxtrace.org")
} else {
powProvider = PowProviderParam
}
if powProvider == "sakura" {
return "pow.nexttrace.owo.13a.com"
}
return ""
}
func StringInSlice(val string, list []string) bool {
for _, v := range list {
if v == val {
return true
}
}
return false
}
func HideIPPart(ip string) string {
parsedIP := net.ParseIP(ip)
if parsedIP == nil {
return ""
}
if parsedIP.To4() != nil {
// IPv4: 隐藏后16位
return strings.Join(strings.Split(ip, ".")[:2], ".") + ".0.0/16"
}
// IPv6: 隐藏后96位
return parsedIP.Mask(net.CIDRMask(32, 128)).String() + "/32"
}