forked from arkrz/v2sub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.go
327 lines (284 loc) · 6.85 KB
/
lib.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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
package main
import (
"encoding/base64"
"encoding/json"
"fmt"
"github.com/arkrz/v2sub/template"
"github.com/arkrz/v2sub/types"
"github.com/modood/table"
"io/ioutil"
"net/http"
"net/url"
"os"
"strconv"
"strings"
)
const (
vmessProtocol = "vmess"
trojanProtocol = "trojan"
socksProtocol = "socks"
ssProtocol = "shadowsocks"
)
// ExitWithMsg 输出 msg 并退出
func ExitWithMsg(msg interface{}, code int) {
fmt.Println(msg)
os.Exit(code)
}
// FileExist 判断文件是否存在
func FileExist(name string) bool {
fileInfo, err := os.Stat(name)
if err != nil || fileInfo.IsDir() {
return false
}
return true
}
// ReadConfig 读取 v2sub 配置文件
func ReadConfig(name string) (*types.Config, error) {
data, err := ioutil.ReadFile(name)
if err != nil {
return template.ConfigTemplate, nil // return error?
}
cfg := &types.Config{}
if err = json.Unmarshal(data, cfg); err != nil {
return template.ConfigTemplate, err
}
return cfg, nil
}
// GetSub 从url中获取订阅信息并进行base64解码
// http请求错误不发送任何信息; 解码错误发送nil
func GetSub(url string, ch chan<- []string) {
body, err := httpGet(url)
if err != nil {
body, err = httpGet(url) // 尝试两次
if err != nil {
return // send none
}
}
bodyStr := string(body)
complementLen := (4 - (len(bodyStr) % 4)) % 4
for i := 0; i < complementLen; i++ {
bodyStr += "="
}
res, err := base64.StdEncoding.DecodeString(bodyStr)
if err != nil {
ch <- nil
return // send nil
}
ch <- strings.Split(string(res[:len(res)-1]), "\n") // 多一个换行符
}
func httpGet(url string) ([]byte, error) {
data, err := http.Get(url)
if err != nil {
return nil, err
}
defer func() {
_ = data.Body.Close()
}()
return ioutil.ReadAll(data.Body)
}
// ParseNodes 返回正确解析的节点 以及 无法解析的数据
func ParseNodes(data []string) (types.Nodes, []string) {
const vmessPrefix = vmessProtocol + "://"
const trojanPrefix = trojanProtocol + "://"
const ssPrefix = "ss" + "://"
var nodes types.Nodes
var retData []string
for i := range data {
switch {
// vmess
case strings.HasPrefix(data[i], vmessPrefix):
data[i] = strings.ReplaceAll(data[i], vmessPrefix, "")
if nodeData, err := base64.StdEncoding.DecodeString(data[i]); err != nil {
retData = append(retData, data[i])
} else {
var node = &types.Node{}
if err = json.Unmarshal(nodeData, node); err != nil {
retData = append(retData, data[i])
} else {
node.Protocol = vmessProtocol
nodes = append(nodes, node)
}
}
// trojan
case strings.HasPrefix(data[i], trojanPrefix):
data[i] = strings.ReplaceAll(data[i], trojanPrefix, "")
node, ok := parseTrojanSub(data[i])
if !ok {
retData = append(retData, data[i])
} else {
node.Protocol = trojanProtocol
nodes = append(nodes, node)
}
// ss
case strings.HasPrefix(data[i], ssPrefix):
data[i] = strings.ReplaceAll(data[i], ssPrefix, "")
node, ok := parseSSSub(data[i])
if !ok {
retData = append(retData, data[i])
} else {
node.Protocol = ssProtocol
nodes = append(nodes, node)
}
default:
retData = append(retData, data[i])
}
}
return nodes, retData
}
func parseTrojanSub(data string) (*types.Node, bool) {
idEnd := strings.Index(data, "@")
if idEnd < 0 {
return nil, false
}
id := data[:idEnd]
data = data[idEnd+1:]
addrEnd := strings.Index(data, ":")
if addrEnd < 0 {
return nil, false
}
addr := data[:addrEnd]
data = data[addrEnd+1:]
portEnd := strings.Index(data, "?")
if portEnd < 0 {
return nil, false
}
port, err := strconv.Atoi(data[:portEnd])
if err != nil {
return nil, false
}
data = data[portEnd+1:]
nameBegin := strings.Index(data, "#") + 1
if nameBegin <= 0 {
return nil, false
}
name := data[nameBegin:]
name, err = url.QueryUnescape(name) //URL解码
if err != nil {
return nil, false
}
name = name[:len(name)-1] //多一个 /r
return &types.Node{
Name: name,
Addr: addr,
Port: port,
UID: id,
}, true
}
func parseSSSub(data string) (*types.Node, bool) {
idEnd := strings.Index(data, "@")
if idEnd < 0 {
return nil, false
}
id := data[:idEnd]
data = data[idEnd+1:]
addrEnd := strings.Index(data, ":")
if addrEnd < 0 {
return nil, false
}
addr := data[:addrEnd]
data = data[addrEnd+1:]
portEnd := strings.Index(data, "#")
if portEnd < 0 {
return nil, false
}
port, err := strconv.Atoi(data[:portEnd])
if err != nil {
return nil, false
}
data = data[portEnd+1:]
name, err := url.QueryUnescape(data) //URL解码
if err != nil {
return nil, false
}
name = name[:len(name)-1] //多一个 /r
byteID, err := base64.RawURLEncoding.DecodeString(id)
if err != nil {
return nil, false
}
strID := string(byteID)
methodEnd := strings.Index(strID, ":")
if methodEnd < 0 {
return nil, false
}
return &types.Node{
Name: name,
Addr: addr,
Port: port,
UID: strID[methodEnd+1:],
Type: strID[:methodEnd],
}, true
}
// WriteFile 覆写文件
// 若文件不存在则会创建并写入
func WriteFile(name string, data []byte) error {
file, err := os.Create(name)
if err != nil {
return err
}
_, err = file.Write(data)
if err != nil {
return err
}
return file.Close()
}
func setRuleProxy(config *types.V2ray) {
config.DNSConfigs = template.DefaultDNSConfigs
config.RouterConfig = template.DefaultRouterConfigs
}
func setGlobalProxy(config *types.V2ray) {
config.DNSConfigs = nil
config.RouterConfig = nil
}
func listenOnLocal(config *types.V2ray) {
for i := range config.InboundConfigs {
config.InboundConfigs[i].ListenOn = template.ListenOnLocalAddr
}
}
func listenOnWan(config *types.V2ray) {
for i := range config.InboundConfigs {
config.InboundConfigs[i].ListenOn = template.ListenOnWanAddr
}
}
func listenOnPort(config *types.V2ray) {
for i := range config.InboundConfigs {
switch config.InboundConfigs[i].Protocol {
case template.ListenOnSocksProtocol:
if flags.socksPort != 0 {
config.InboundConfigs[i].Port = uint32(flags.socksPort)
}
case template.ListenOnHttpProtocol:
if flags.httpPort != 0 {
config.InboundConfigs[i].Port = uint32(flags.httpPort)
}
}
}
}
func parsePort(v interface{}) (port int) {
portStr := fmt.Sprintf("%v", v)
port, _ = strconv.Atoi(portStr)
return
}
func printAsTable(nodes types.Nodes) {
var tableData []types.TableRow
for i := range nodes {
tableData = append(tableData, types.TableRow{
Index: i,
Name: nodes[i].Name,
Addr: nodes[i].Addr,
Port: parsePort(nodes[i].Port),
Protocol: nodes[i].Protocol,
Ping: nodes[i].Ping})
}
table.Output(tableData)
}
func allDone(cfg *types.Config) {
var msg string
for _, inboundConfig := range cfg.V2rayConfig.InboundConfigs {
if len(msg) == 0 {
msg = "\n开始监听...\n"
}
msg += fmt.Sprintf("%s://%s:%d\n", inboundConfig.Protocol, inboundConfig.ListenOn, inboundConfig.Port)
}
msg += "\nAll done."
fmt.Println(msg)
}