-
Notifications
You must be signed in to change notification settings - Fork 225
/
main.go
435 lines (419 loc) · 11.5 KB
/
main.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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
package main
import (
"bufio"
"context"
"crypto/sha256"
"encoding/hex"
"io"
"net/http"
"os"
"path/filepath"
"sort"
"strings"
"github.com/sagernet/sing-box/common/geosite"
"github.com/sagernet/sing-box/common/srs"
C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing-box/option"
"github.com/sagernet/sing/common"
E "github.com/sagernet/sing/common/exceptions"
"github.com/google/go-github/v45/github"
"github.com/v2fly/v2ray-core/v5/app/router/routercommon"
"google.golang.org/protobuf/proto"
)
var githubClient *github.Client
func init() {
accessToken, loaded := os.LookupEnv("ACCESS_TOKEN")
if !loaded {
githubClient = github.NewClient(nil)
return
}
transport := &github.BasicAuthTransport{
Username: accessToken,
}
githubClient = github.NewClient(transport.Client())
}
func fetch(from string) (*github.RepositoryRelease, error) {
names := strings.SplitN(from, "/", 2)
latestRelease, _, err := githubClient.Repositories.GetLatestRelease(context.Background(), names[0], names[1])
if err != nil {
return nil, err
}
return latestRelease, err
}
func get(downloadURL *string) ([]byte, error) {
log.Info("download ", *downloadURL)
response, err := http.Get(*downloadURL)
if err != nil {
return nil, err
}
defer response.Body.Close()
return io.ReadAll(response.Body)
}
func download(release *github.RepositoryRelease) ([]byte, error) {
geositeAsset := common.Find(release.Assets, func(it *github.ReleaseAsset) bool {
return *it.Name == "dlc.dat"
})
geositeChecksumAsset := common.Find(release.Assets, func(it *github.ReleaseAsset) bool {
return *it.Name == "dlc.dat.sha256sum"
})
if geositeAsset == nil {
return nil, E.New("geosite asset not found in upstream release ", release.Name)
}
if geositeChecksumAsset == nil {
return nil, E.New("geosite asset not found in upstream release ", release.Name)
}
data, err := get(geositeAsset.BrowserDownloadURL)
if err != nil {
return nil, err
}
remoteChecksum, err := get(geositeChecksumAsset.BrowserDownloadURL)
if err != nil {
return nil, err
}
checksum := sha256.Sum256(data)
if hex.EncodeToString(checksum[:]) != string(remoteChecksum[:64]) {
return nil, E.New("checksum mismatch")
}
return data, nil
}
func parse(vGeositeData []byte) (map[string][]geosite.Item, error) {
vGeositeList := routercommon.GeoSiteList{}
err := proto.Unmarshal(vGeositeData, &vGeositeList)
if err != nil {
return nil, err
}
domainMap := make(map[string][]geosite.Item)
for _, vGeositeEntry := range vGeositeList.Entry {
code := strings.ToLower(vGeositeEntry.CountryCode)
domains := make([]geosite.Item, 0, len(vGeositeEntry.Domain)*2)
attributes := make(map[string][]*routercommon.Domain)
for _, domain := range vGeositeEntry.Domain {
if len(domain.Attribute) > 0 {
for _, attribute := range domain.Attribute {
attributes[attribute.Key] = append(attributes[attribute.Key], domain)
}
}
switch domain.Type {
case routercommon.Domain_Plain:
domains = append(domains, geosite.Item{
Type: geosite.RuleTypeDomainKeyword,
Value: domain.Value,
})
case routercommon.Domain_Regex:
domains = append(domains, geosite.Item{
Type: geosite.RuleTypeDomainRegex,
Value: domain.Value,
})
case routercommon.Domain_RootDomain:
if strings.Contains(domain.Value, ".") {
domains = append(domains, geosite.Item{
Type: geosite.RuleTypeDomain,
Value: domain.Value,
})
}
domains = append(domains, geosite.Item{
Type: geosite.RuleTypeDomainSuffix,
Value: "." + domain.Value,
})
case routercommon.Domain_Full:
domains = append(domains, geosite.Item{
Type: geosite.RuleTypeDomain,
Value: domain.Value,
})
}
}
domainMap[code] = common.Uniq(domains)
for attribute, attributeEntries := range attributes {
attributeDomains := make([]geosite.Item, 0, len(attributeEntries)*2)
for _, domain := range attributeEntries {
switch domain.Type {
case routercommon.Domain_Plain:
attributeDomains = append(attributeDomains, geosite.Item{
Type: geosite.RuleTypeDomainKeyword,
Value: domain.Value,
})
case routercommon.Domain_Regex:
attributeDomains = append(attributeDomains, geosite.Item{
Type: geosite.RuleTypeDomainRegex,
Value: domain.Value,
})
case routercommon.Domain_RootDomain:
if strings.Contains(domain.Value, ".") {
attributeDomains = append(attributeDomains, geosite.Item{
Type: geosite.RuleTypeDomain,
Value: domain.Value,
})
}
attributeDomains = append(attributeDomains, geosite.Item{
Type: geosite.RuleTypeDomainSuffix,
Value: "." + domain.Value,
})
case routercommon.Domain_Full:
attributeDomains = append(attributeDomains, geosite.Item{
Type: geosite.RuleTypeDomain,
Value: domain.Value,
})
}
}
domainMap[code+"@"+attribute] = common.Uniq(attributeDomains)
}
}
return domainMap, nil
}
type filteredCodePair struct {
code string
badCode string
}
func filterTags(data map[string][]geosite.Item) {
var codeList []string
for code := range data {
codeList = append(codeList, code)
}
var badCodeList []filteredCodePair
var filteredCodeMap []string
var mergedCodeMap []string
for _, code := range codeList {
codeParts := strings.Split(code, "@")
if len(codeParts) != 2 {
continue
}
leftParts := strings.Split(codeParts[0], "-")
var lastName string
if len(leftParts) > 1 {
lastName = leftParts[len(leftParts)-1]
}
if lastName == "" {
lastName = codeParts[0]
}
if lastName == codeParts[1] {
delete(data, code)
filteredCodeMap = append(filteredCodeMap, code)
continue
}
if "!"+lastName == codeParts[1] {
badCodeList = append(badCodeList, filteredCodePair{
code: codeParts[0],
badCode: code,
})
} else if lastName == "!"+codeParts[1] {
badCodeList = append(badCodeList, filteredCodePair{
code: codeParts[0],
badCode: code,
})
}
}
for _, it := range badCodeList {
badList := data[it.badCode]
if badList == nil {
panic("bad list not found: " + it.badCode)
}
delete(data, it.badCode)
newMap := make(map[geosite.Item]bool)
for _, item := range data[it.code] {
newMap[item] = true
}
for _, item := range badList {
delete(newMap, item)
}
newList := make([]geosite.Item, 0, len(newMap))
for item := range newMap {
newList = append(newList, item)
}
data[it.code] = newList
mergedCodeMap = append(mergedCodeMap, it.badCode)
}
sort.Strings(filteredCodeMap)
sort.Strings(mergedCodeMap)
os.Stderr.WriteString("filtered " + strings.Join(filteredCodeMap, ",") + "\n")
os.Stderr.WriteString("merged " + strings.Join(mergedCodeMap, ",") + "\n")
}
func mergeTags(data map[string][]geosite.Item) {
var codeList []string
for code := range data {
codeList = append(codeList, code)
}
var cnCodeList []string
for _, code := range codeList {
codeParts := strings.Split(code, "@")
if len(codeParts) != 2 {
continue
}
if codeParts[1] != "cn" {
continue
}
if !strings.HasPrefix(codeParts[0], "category-") {
continue
}
if strings.HasSuffix(codeParts[0], "-cn") || strings.HasSuffix(codeParts[0], "-!cn") {
continue
}
cnCodeList = append(cnCodeList, code)
}
for _, code := range codeList {
if !strings.HasPrefix(code, "category-") {
continue
}
if !strings.HasSuffix(code, "-cn") {
continue
}
if strings.Contains(code, "@") {
continue
}
cnCodeList = append(cnCodeList, code)
}
newMap := make(map[geosite.Item]bool)
for _, item := range data["geolocation-cn"] {
newMap[item] = true
}
for _, code := range cnCodeList {
for _, item := range data[code] {
newMap[item] = true
}
}
newList := make([]geosite.Item, 0, len(newMap))
for item := range newMap {
newList = append(newList, item)
}
data["geolocation-cn"] = newList
data["cn"] = append(newList, geosite.Item{
Type: geosite.RuleTypeDomainSuffix,
Value: "cn",
})
println("merged cn categories: " + strings.Join(cnCodeList, ","))
}
func generate(release *github.RepositoryRelease, output string, cnOutput string, ruleSetOutput string, ruleSetUnstableOutput string) error {
vData, err := download(release)
if err != nil {
return err
}
domainMap, err := parse(vData)
if err != nil {
return err
}
filterTags(domainMap)
mergeTags(domainMap)
outputPath, _ := filepath.Abs(output)
os.Stderr.WriteString("write " + outputPath + "\n")
outputFile, err := os.Create(output)
if err != nil {
return err
}
defer outputFile.Close()
writer := bufio.NewWriter(outputFile)
err = geosite.Write(writer, domainMap)
if err != nil {
return err
}
err = writer.Flush()
if err != nil {
return err
}
cnCodes := []string{
"geolocation-cn",
}
cnDomainMap := make(map[string][]geosite.Item)
for _, cnCode := range cnCodes {
cnDomainMap[cnCode] = domainMap[cnCode]
}
cnOutputFile, err := os.Create(cnOutput)
if err != nil {
return err
}
defer cnOutputFile.Close()
writer.Reset(cnOutputFile)
err = geosite.Write(writer, cnDomainMap)
if err != nil {
return err
}
err = writer.Flush()
if err != nil {
return err
}
os.RemoveAll(ruleSetOutput)
os.RemoveAll(ruleSetUnstableOutput)
err = os.MkdirAll(ruleSetOutput, 0o755)
err = os.MkdirAll(ruleSetUnstableOutput, 0o755)
if err != nil {
return err
}
for code, domains := range domainMap {
var headlessRule option.DefaultHeadlessRule
defaultRule := geosite.Compile(domains)
headlessRule.Domain = defaultRule.Domain
headlessRule.DomainSuffix = defaultRule.DomainSuffix
headlessRule.DomainKeyword = defaultRule.DomainKeyword
headlessRule.DomainRegex = defaultRule.DomainRegex
var plainRuleSet option.PlainRuleSet
plainRuleSet.Rules = []option.HeadlessRule{
{
Type: C.RuleTypeDefault,
DefaultOptions: headlessRule,
},
}
srsPath, _ := filepath.Abs(filepath.Join(ruleSetOutput, "geosite-"+code+".srs"))
unstableSRSPath, _ := filepath.Abs(filepath.Join(ruleSetUnstableOutput, "geosite-"+code+".srs"))
// os.Stderr.WriteString("write " + srsPath + "\n")
var (
outputRuleSet *os.File
outputRuleSetUnstable *os.File
)
outputRuleSet, err = os.Create(srsPath)
if err != nil {
return err
}
err = srs.Write(outputRuleSet, plainRuleSet, false)
outputRuleSet.Close()
if err != nil {
return err
}
outputRuleSetUnstable, err = os.Create(unstableSRSPath)
if err != nil {
return err
}
err = srs.Write(outputRuleSetUnstable, plainRuleSet, true)
outputRuleSetUnstable.Close()
if err != nil {
return err
}
}
return nil
}
func setActionOutput(name string, content string) {
os.Stdout.WriteString("::set-output name=" + name + "::" + content + "\n")
}
func release(source string, destination string, output string, cnOutput string, ruleSetOutput string, ruleSetOutputUnstable string) error {
sourceRelease, err := fetch(source)
if err != nil {
return err
}
destinationRelease, err := fetch(destination)
if err != nil {
log.Warn("missing destination latest release")
} else {
if os.Getenv("NO_SKIP") != "true" && strings.Contains(*destinationRelease.Name, *sourceRelease.Name) {
log.Info("already latest")
setActionOutput("skip", "true")
return nil
}
}
err = generate(sourceRelease, output, cnOutput, ruleSetOutput, ruleSetOutputUnstable)
if err != nil {
return err
}
setActionOutput("tag", *sourceRelease.Name)
return nil
}
func main() {
err := release(
"v2fly/domain-list-community",
"sagernet/sing-geosite",
"geosite.db",
"geosite-cn.db",
"rule-set",
"rule-set-unstable",
)
if err != nil {
log.Fatal(err)
}
}