Compare commits

...

31 Commits

Author SHA1 Message Date
MkQtS
cbd681a8fb Refactor exporting plaintext list 2026-01-09 14:39:51 +08:00
MkQtS
2b031241a2 Feat: add support for partial include
- refactor inclusion logic
- add basic deduplicate
2026-01-09 14:39:36 +08:00
MkQtS
345d66ffa0 Refactor: promote refMap 2026-01-09 10:54:44 +08:00
MkQtS
e7564e29d8 Remove support for partial include
This reverts e640ac2783

It is problematic and I will implement a new one
2026-01-09 10:54:44 +08:00
MkQtS
c823945856 Refactor exportPlainTextList
- remove unnecessary variable
- improve readablity
2026-01-09 10:54:44 +08:00
MkQtS
2ad6b58045 Refactor parseEntry
- add value/attribute checker(check missing space)
- allow multiple spaces
- sort attributes
- improve readablity
2026-01-09 10:54:44 +08:00
MkQtS
4c6ab37622 Refactor: use string attr before toProto 2026-01-09 10:54:44 +08:00
MkQtS
e5c3408a13 Refactor: reduce the use of strings.TrimSpace 2026-01-09 10:54:44 +08:00
xizi
67389b37cc Add schoopia (#3156)
Add domains for 翻转校园
2026-01-09 09:54:32 +08:00
TripleA
39431a9e8f google-deepmind: add missing subdomain for Google AI Labs (#3157) 2026-01-09 09:47:54 +08:00
xizi
b8fc0cd9d7 feat(jiguang): add missing domain easytomessage.com (#3155)
Add missing domain for Jiguang (JPush) service.

According to the official Jiguang documentation, `easytomessage.com` is a required domain for the push service to function correctly on network-restricted environments.

Reference:
https://community.jiguang.cn/article/408970
2026-01-09 09:46:36 +08:00
bafometik
9f59a5e666 category-ru: add more domains (#3144) 2026-01-08 23:07:32 +08:00
Aleksandr Fedotov
07f769cf85 Add category-retail-ru (#3154) 2026-01-08 23:00:26 +08:00
MkQtS
6833d994c0 category-dev: add more domains 2026-01-08 13:59:24 +08:00
MkQtS
b150c66d47 category-password-management: add authpass.app 2026-01-08 13:59:24 +08:00
MkQtS
248c0f7b86 geolocation: add more domains 2026-01-08 13:59:24 +08:00
un1ntend3d
de2c5cf208 category-cryptocurrency: add bingx.com (#3140) 2026-01-08 12:27:24 +08:00
MkQtS
44d511e74e Add technogym (#3152) 2026-01-08 12:18:11 +08:00
TripleA
5928f612ba Update category-public-tracker (#3151)
Strict comparison by www removed
2026-01-08 11:59:21 +08:00
Aleksandr Fedotov
246b6150af Add mosmetro (#3146) 2026-01-08 11:50:46 +08:00
Aleksandr Fedotov
ffb25af399 Add category-ecommerce-ru (#3149) 2026-01-08 11:41:48 +08:00
Aleksandr Fedotov
f96f3d1abd Add category-entertainment-ru (#3150) 2026-01-08 11:34:37 +08:00
Aleksandr Fedotov
8fc66473ff category-ru: remove anime domains (#3148)
* animevost.org is changing mirrors; the domain is unstable

* seasonvar.ru is already in the category-ru
2026-01-08 11:30:46 +08:00
xizi
49101e3aab taptap: add tapapks.com (#3147)
Add missing download domain.
2026-01-08 11:21:25 +08:00
bafometik
d2c662bf5e mailru-group: add tamtam.chat (#3145) 2026-01-07 15:13:39 +08:00
MkQtS
7a6e4cb1f5 Update apple (#3138)
* apple: deduplicate

- swift is included in apple-dev
- `full:certs.apple.com @cn` is added in apple-pki
- `full:crl.apple.com @cn` is added in apple-pki
- `full:ocsp-lb.apple.com.akadns.net @cn` is added in apple-pki
- `full:ocsp.apple.com @cn` is added in apple-pki
- `full:ocsp2-lb.apple.com.akadns.net @cn` is added in apple-pki
- `full:ocsp2.apple.com @cn` is added in apple-pki
- `full:valid.apple.com @cn` is added in apple-pki

* apple: move `valid.origin-apple.com.akadns.net` to apple-pki

keep consistent with valid.apple.com
2026-01-06 16:07:03 +08:00
MkQtS
511577436c category-collaborate-cn: add todesk.cn (#3139) 2026-01-06 15:51:06 +08:00
MkQtS
8a2718204b google: deduplicate (#3137)
- `full:safebrowsing-cache.google.com @cn` appears twice
- `full:crl.pki.goog @cn` is added in google-trust-services
- `full:firebase-settings.crashlytics.com @cn` is added in firebase
- `full:ocsp.pki.goog @cn` is added in google-trust-services
- `full:pki-goog.l.google.com @cn` is added in google-trust-services
- `full:redirector.c.play.google.com @cn` is added in google-play
2026-01-06 14:08:09 +08:00
HedgDifuse
e3b3197a42 Add category-proxy-tunnels with ngrok and pinggy (#3130)
* add category-proxy-tunnels

* add ngrok and pinggy
2026-01-06 12:33:11 +08:00
I'm xun.
f8488acb8c google-deepmind: add ai.studio (#3134) 2026-01-05 18:25:38 +08:00
6kembion9-byte
ed2bce57e7 Add more torrent domains (#3118)
* category-public-tracker: add nnmclub.to

* geolocation-!cn: add rutor.info
2026-01-05 17:06:33 +08:00
30 changed files with 329 additions and 303 deletions

View File

@@ -1,5 +1,5 @@
include:apple-ads
include:apple-dev
include:apple-dev # swift inside
# Not include:apple-intelligence
include:apple-pki
include:apple-tvplus
@@ -7,7 +7,6 @@ include:apple-update
include:beats
include:icloud
include:itunes
include:swift
# All .apple domains
apple
@@ -856,7 +855,7 @@ full:s4.mzstatic.com @cn
full:s5.mzstatic.com @cn
# The rules below are from https://github.com/felixonmars/dnsmasq-china-list/blob/master/apple.china.conf
# Revision: 4d392cc0a822ac5626bb97fef3fe5e04e86b28b0
# Revision: f6a2093b254a7d2baca959bd16581666ca394303
# Duplicates removed
# According to the consensus in #503, do not include the domain name apps.apple.com directly.
# Use in config file like this: "geosite:apple@cn"
@@ -874,7 +873,6 @@ full:cds-cdn.v.aaplimg.com @cn
full:cds.apple.com @cn
full:cds.apple.com.akadns.net @cn
full:cdsassets.apple.com @cn
full:certs.apple.com @cn
full:cl2-cn.apple.com @cn
full:cl4-cn.apple.com @cn
full:clientflow.apple.com @cn
@@ -882,7 +880,6 @@ full:clientflow.apple.com.akadns.net @cn
full:cn-smp-paymentservices.apple.com @cn
full:configuration.apple.com @cn
full:configuration.apple.com.akadns.net @cn
full:crl.apple.com @cn
full:cstat.apple.com @cn
full:cstat.cdn-apple.com @cn
full:dd-cdn.origin-apple.com.akadns.net @cn
@@ -935,10 +932,6 @@ full:mesu-china.apple.com.akadns.net @cn
full:mesu.apple.com @cn
full:ml.cdn-apple.com @cn
full:music.apple.com @cn
full:ocsp-lb.apple.com.akadns.net @cn
full:ocsp.apple.com @cn
full:ocsp2-lb.apple.com.akadns.net @cn
full:ocsp2.apple.com @cn
full:oscdn.apple.com @cn
full:oscdn.origin-apple.com.akadns.net @cn
full:osxapps.itunes.g.aaplimg.com @cn
@@ -981,8 +974,6 @@ full:tj-pod1-smp-device.apple.com @cn
full:updates-http.cdn-apple.com @cn
full:updates-http.cdn-apple.com.akadns.net @cn
full:updates.cdn-apple.com @cn
full:valid.apple.com @cn
full:valid.origin-apple.com.akadns.net @cn
full:weather-data.apple.com @cn
full:weather-data.apple.com.akadns.net @cn
full:weather-map.apple.com @cn

View File

@@ -7,3 +7,4 @@ full:ocsp.apple.com @cn
full:ocsp2-lb.apple.com.akadns.net @cn
full:ocsp2.apple.com @cn
full:valid.apple.com @cn
full:valid.origin-apple.com.akadns.net @cn

View File

@@ -8,6 +8,7 @@ orayimg.com
sunlogin.net
## ToDesk
todesk.cn
todesk.com
## 连连控

View File

@@ -79,7 +79,6 @@ include:spaceship
include:st
include:synology
include:symantec
include:tailscale
include:theboringcompany
include:tonec
include:uber

View File

@@ -25,6 +25,7 @@ include:zb
1inch.io
aave.com
bingx.com
bitbank.cc
bitcoin.org
bitfinex.com

View File

@@ -114,7 +114,9 @@ mobatek.net
mpv.io
mysql.com
neovim.io
netfilter.org
newpipe.net
nftables.org
nixos.org
nodesource.com
notepad-plus-plus.org

View File

@@ -1,3 +1,5 @@
include:category-ecommerce-ru
include:adidas
include:bestbuy
include:booking
@@ -19,7 +21,6 @@ include:momo
include:muji
include:nike
include:nordstrom
include:ozon
include:pchome
include:rakuten
include:ruten
@@ -27,6 +28,7 @@ include:shopee
include:shopify
include:suruga-ya
include:target
include:technogym
include:walmart
include:wish

View File

@@ -0,0 +1,2 @@
include:ozon
include:wildberries

View File

@@ -5,6 +5,7 @@ include:applysquare
include:hugecore
include:hujiang
include:koolearn
include:schoopia
include:shanbay
include:xueersi
include:yuanfudao

View File

@@ -1,5 +1,6 @@
# This list contains services related to entertainment & games & music & podcasts & videos outside China mainland.
include:category-entertainment-ru
include:category-games-!cn
include:category-novel
@@ -46,7 +47,6 @@ include:mytvsuper
include:netflix
include:niconico
include:now
include:okko
include:olevod
include:pbs
include:pixiv
@@ -54,7 +54,6 @@ include:plutotv
include:pocketcasts
include:primevideo
include:roku
include:rutube
include:showtimeanytime
include:sling
include:sonypictures

View File

@@ -0,0 +1,3 @@
include:okko
include:rutube
include:wink

View File

@@ -2,6 +2,7 @@ include:agilebits # 1password
include:bitwarden
include:lastpass
authpass.app
authy.com
dashlane.com
enpass.io

View File

@@ -0,0 +1,3 @@
include:ngrok
include:pinggy
include:tailscale

View File

@@ -117,6 +117,7 @@ full:music-torrent.net
full:mvgforumtracker.mvgroup.org
full:mvgroup.org
full:new-line.net
full:nnmclub.to
full:nyaa.tracker.wf
full:odd-hd.fr
full:oh.fuuuuuck.com
@@ -410,34 +411,6 @@ full:udp.tracker.projectk.org
full:wepzone.net
full:wg.mortis.me
full:ws.peer.ooo
full:www.all4nothin.net
full:www.bit-hdtv.com
full:www.bitseduce.com
full:www.biztorrents.com
full:www.blackcats-games.net
full:www.elitezones.ro
full:www.freerainbowtables.com
full:www.genesis-sp.org
full:www.learnbits.me
full:www.legittorrents.info
full:www.megatorrents.kg
full:www.mvgroup.org
full:www.peckservers.com
full:www.shnflac.net
full:www.siambt.com
full:www.thegeeks.bz
full:www.theoccult.bz
full:www.theplace.bz
full:www.thetradersden.org
full:www.thevault.bz
full:www.torrent.eu.org
full:www.torrentsnipe.info
full:www.tribalmixes.com
full:www.tvnihon.com
full:www.worldboxingvideoarchive.com
full:www.xwt-classics.net
full:www.yuwabits.net
full:www.zone-torrent.net
full:xbtrutor.com
full:xtremewrestlingtorrents.net
full:y.paranoid.agency
@@ -446,3 +419,32 @@ full:yggtracker.i2p.rocks
full:yolo.liberbear.com
full:z.paranoid.agency
full:zupix.online
all4nothin.net
bit-hdtv.com
bitseduce.com
biztorrents.com
blackcats-games.net
elitezones.ro
freerainbowtables.com
genesis-sp.org
learnbits.me
legittorrents.info
megatorrents.kg
mvgroup.org
peckservers.com
shnflac.net
siambt.com
thegeeks.bz
theoccult.bz
theplace.bz
thetradersden.org
thevault.bz
torrent.eu.org
torrentsnipe.info
tribalmixes.com
tvnihon.com
worldboxingvideoarchive.com
xwt-classics.net
yuwabits.net
zone-torrent.net

6
data/category-retail-ru Normal file
View File

@@ -0,0 +1,6 @@
# Fix Price
fix-price.com
# Lenta
lenta.com
lenta.tech

View File

@@ -16,18 +16,31 @@ xn--p1ai
ru.com
ru.net
include:category-ecommerce-ru
include:category-entertainment-ru
include:category-gov-ru
include:category-retail-ru
# Public transportation
include:mosmetro
include:avito
include:mailru-group
include:okko
include:ozon
include:rutube
include:wildberries
include:wink
include:x5
include:yandex
# Anime
animevost.org
seasonvar.ru
# Dodo Pizza
dodopizza.ru
dodopizza.com
dodostatic.net
dodois.com
dodois.io
# Rostics
rostics.ru
uni.rest
unirest.tech
trbcdn.net
tbank-online.com
taxsee.com

View File

@@ -12,6 +12,7 @@ include:taboola
# Anti-censorship & Anti-GFW & Privacy protection & VPN tools
include:category-anticensorship
include:category-proxy-tunnels
# Art & Design & Photography
include:artstation
@@ -284,6 +285,7 @@ include:nyaa
include:piratebay
include:rarbg
dmhy.org
rutor.info
# User scripts
greasyfork.org

View File

@@ -108,6 +108,8 @@ include:ziroom
## 无忧易售
51selling.com
## 爱回收
aihuishou.com
## 唯品会
appsimg.com
appvipshop.com
@@ -176,6 +178,7 @@ znds.com # 智能电视网
423down.com # 423Down
acwifi.net # 路由器技术分享
appinn.com # 小众软件
chongdiantou.com # 充电头网
ghxi.com # 果核剥壳
iplaysoft.com # 异次元软件世界
@@ -314,12 +317,16 @@ include:zhubajie
7moor.com
## 安兔兔
antutu.com
antutu.net
## 拓竹科技
bambulab.com
bblmw.com
## BOSS 直聘
bosszhipin.com
zhipin.com
## 下厨房
chuimg.com
xiachufang.com
## 天润融通 AI外呼 客服
clink.cn
## 当贝
@@ -429,6 +436,10 @@ suzuki-china.com # 铃木中国官网
udesk.cn # 沃丰科技
ysjf.com # 影视飓风
# 飞牛
fnnas.com
fnnas.net
fnos.net
# 稿定(厦门)信息服务有限公司
## 花瓣网 闽ICP备2021013850号
huaban.com
@@ -645,7 +656,6 @@ apk3.com
apk8.com
aplaybox.com
appchina.com
appinn.com
arpun.com
asklib.com
babytree.com
@@ -1351,7 +1361,6 @@ xdqtech.com # 上邻 | 新渡桥科技 浙ICP备2020031247号-1
xdtool.com # 闽ICP备2024056202号-4
xdwan.com
xfdown.com
xiachufang.com
xiaobaixitong.com
xiaoe-tech.com
xiaogouh5.com

View File

@@ -544,11 +544,13 @@ full:google-ohttp-relay-safebrowsing.fastly-edge.com
# Domains and services below are available in China mainland
# Use in config file like this: "geosite:google@cn"
gvt1-cn.com @cn
gvt2-cn.com @cn
full:www.recaptcha.net @cn
full:safebrowsing-cache.google.com @cn
# The rules below are from https://github.com/felixonmars/dnsmasq-china-list/blob/master/google.china.conf
# Revision: 1f28a2d5789f411c13de69837bb354f4b21e58ff
# Revision: 1c2d107d4e7eaa0b192e08bb0beddde4aab247f6
# Duplicates removed
# Use in config file like this: "geosite:google@cn"
full:265.com @cn
full:2mdn-cn.net @cn
@@ -578,7 +580,6 @@ full:cnappinstall.googleadapis.com @cn
full:connectivitycheck.gstatic.com @cn
full:content.googleadapis.com @cn
full:crashlyticsreports-pa.googleapis.com @cn
full:crl.pki.goog @cn
full:csi.gstatic.com @cn
full:dartsearch-cn.net @cn
full:dg-meta.video.google.com @cn
@@ -590,7 +591,6 @@ full:download.mlcc.google.com @cn
full:download.qatp1.net @cn
full:download.tensorflow.google.com @cn
full:emmapplecodevice.googleapis.com @cn
full:firebase-settings.crashlytics.com @cn
full:fontfiles.googleapis.com @cn
full:fonts.googleapis.com @cn
full:fonts.gstatic.com @cn
@@ -629,10 +629,8 @@ full:logger-dev.corp.google.com @cn
full:logger.corp.google.com @cn
full:login.corp.google.com @cn
full:monitoring.qpdp1.net @cn
full:ocsp.pki.goog @cn
full:pagead-googlehosted.l.google.com @cn
full:performanceparameters.googleapis.com @cn
full:pki-goog.l.google.com @cn
full:prod-controlbe.floonet.goog @cn
full:prod-databe.floonet.goog @cn
full:prod.databe.floonet.goog @cn
@@ -651,7 +649,6 @@ full:redirector.bdn.dev @cn
full:redirector.c.chat.google.com @cn
full:redirector.c.mail.google.com @cn
full:redirector.c.pack.google.com @cn
full:redirector.c.play.google.com @cn
full:redirector.c.youtubeeducation.com @cn
full:redirector.gcpcdn.gvt1.com @cn
full:redirector.gvt1.com @cn
@@ -690,6 +687,3 @@ full:www.destinationurl.com @cn
full:www.gstatic.com @cn
full:www.pxcc.com @cn
full:xn--flw351e.com @cn
gvt1-cn.com @cn
gvt2-cn.com @cn

View File

@@ -16,6 +16,7 @@ full:webchannel-alkalimakersuite-pa.clients6.google.com
generativeai.google
makersuite.google.com
ai.studio
aistudio.google.com
bard.google.com
gemini.google
@@ -31,6 +32,7 @@ jules.google.com
# Google AI Labs
labs.google
labs.google.com
aisandbox-pa.googleapis.com
# Android Studio Gemini Code Assist

View File

@@ -3,6 +3,7 @@
5566ua.com
aurorapush.cn
e0n.cn
easytomessage.com
japps.cn
jchat.io
jiguang.cn

View File

@@ -6,3 +6,4 @@ include:vk
boosty.to
donationalerts.com
memealerts.com
tamtam.chat

2
data/mosmetro Normal file
View File

@@ -0,0 +1,2 @@
mosmetro.ru
mosmetro.tech

9
data/ngrok Normal file
View File

@@ -0,0 +1,9 @@
ngrok-free.app
ngrok-free.dev
ngrok-free.pizza
ngrok.app
ngrok.com
ngrok.dev
ngrok.io
ngrok.pizza
ngrok.pro

2
data/pinggy Normal file
View File

@@ -0,0 +1,2 @@
pinggy.io
pinggy.link

4
data/schoopia Normal file
View File

@@ -0,0 +1,4 @@
# 翻转校园 河南昱荣教育科技有限公司 豫ICP备2021021028号
schoopia.com
# 同学派 翻转校园app内置服务
tongxuepie.com

View File

@@ -1,3 +1,4 @@
tapapks.com
tapimg.com
tapimg.net
taptap.cn

9
data/technogym Normal file
View File

@@ -0,0 +1,9 @@
# data source: https://crt.sh/?id=17424181
letsmoveforabetterworld.com
technogym.bg
technogym.ch
technogym.com
technogym.com.br
technogym.ru
technogym.su
wellnessinstitute.com

423
main.go
View File

@@ -29,10 +29,29 @@ const (
RuleTypeInclude string = "include"
)
var (
TypeChecker = regexp.MustCompile(`^(domain|full|keyword|regexp|include)$`)
ValueChecker = regexp.MustCompile(`^[a-z0-9!\.-]+$`)
AttrChecker = regexp.MustCompile(`^[a-z0-9!-]+$`)
)
var (
refMap = make(map[string]*List)
plMap = make(map[string]*ParsedList)
finalMap = make(map[string][]Entry)
cirIncMap = make(map[string]bool) // Used for circular inclusion detection
)
type Entry struct {
Type string
Value string
Attrs []*router.Domain_Attribute
Attrs []string
}
type Inclusion struct {
Source string
MustAttrs []string
BannedAttrs []string
}
type List struct {
@@ -42,149 +61,107 @@ type List struct {
type ParsedList struct {
Name string
Inclusion map[string]bool
Inclusions []Inclusion
Entry []Entry
}
func (l *ParsedList) toPlainText(listName string) error {
var entryBytes []byte
for _, entry := range l.Entry {
var attrString string
if entry.Attrs != nil {
func makeProtoList(listName string, entries []Entry) (*router.GeoSite, error) {
site := &router.GeoSite{
CountryCode: listName,
}
for _, entry := range entries {
pdomain := &router.Domain{Value: entry.Value}
for _, attr := range entry.Attrs {
attrString += "@" + attr.GetKey() + ","
}
attrString = strings.TrimRight(":"+attrString, ",")
}
// Entry output format is: type:domain.tld:@attr1,@attr2
entryBytes = append(entryBytes, []byte(entry.Type+":"+entry.Value+attrString+"\n")...)
}
if err := os.WriteFile(filepath.Join(*outputDir, listName+".txt"), entryBytes, 0644); err != nil {
return err
}
return nil
pdomain.Attribute = append(pdomain.Attribute, &router.Domain_Attribute{
Key: attr,
TypedValue: &router.Domain_Attribute_BoolValue{BoolValue: true},
})
}
func (l *ParsedList) toProto() (*router.GeoSite, error) {
site := &router.GeoSite{
CountryCode: l.Name,
}
for _, entry := range l.Entry {
switch entry.Type {
case RuleTypeDomain:
site.Domain = append(site.Domain, &router.Domain{
Type: router.Domain_RootDomain,
Value: entry.Value,
Attribute: entry.Attrs,
})
pdomain.Type = router.Domain_RootDomain
case RuleTypeRegexp:
// check regexp validity to avoid runtime error
_, err := regexp.Compile(entry.Value)
if err != nil {
return nil, fmt.Errorf("invalid regexp in list %s: %s", l.Name, entry.Value)
}
site.Domain = append(site.Domain, &router.Domain{
Type: router.Domain_Regex,
Value: entry.Value,
Attribute: entry.Attrs,
})
pdomain.Type = router.Domain_Regex
case RuleTypeKeyword:
site.Domain = append(site.Domain, &router.Domain{
Type: router.Domain_Plain,
Value: entry.Value,
Attribute: entry.Attrs,
})
pdomain.Type = router.Domain_Plain
case RuleTypeFullDomain:
site.Domain = append(site.Domain, &router.Domain{
Type: router.Domain_Full,
Value: entry.Value,
Attribute: entry.Attrs,
})
default:
return nil, fmt.Errorf("unknown domain type: %s", entry.Type)
pdomain.Type = router.Domain_Full
}
site.Domain = append(site.Domain, pdomain)
}
return site, nil
}
func exportPlainTextList(list []string, refName string, pl *ParsedList) {
for _, listName := range list {
if strings.EqualFold(refName, listName) {
if err := pl.toPlainText(strings.ToLower(refName)); err != nil {
fmt.Println("Failed:", err)
continue
func writePlainList(exportedName string) error {
targetList, exist := finalMap[strings.ToUpper(exportedName)]
if !exist || len(targetList) == 0 {
return fmt.Errorf("'%s' list does not exist or is empty.", exportedName)
}
fmt.Printf("'%s' has been generated successfully.\n", listName)
file, err := os.Create(filepath.Join(*outputDir, strings.ToLower(exportedName) + ".txt"))
if err != nil {
return err
}
defer file.Close()
w := bufio.NewWriter(file)
for _, entry := range targetList {
// Entry output format is: type:domain.tld:@attr1,@attr2
var attrString string
if entry.Attrs != nil {
attrString = ":@" + strings.Join(entry.Attrs, ",@")
}
fmt.Fprintln(w, entry.Type + ":" + entry.Value + attrString)
}
return w.Flush()
}
func removeComment(line string) string {
idx := strings.Index(line, "#")
if idx == -1 {
return line
}
return strings.TrimSpace(line[:idx])
}
func parseEntry(line string) (Entry, error) {
var entry Entry
parts := strings.Fields(line)
func parseDomain(domain string, entry *Entry) error {
kv := strings.Split(domain, ":")
// Parse type and value
rawTypeVal := parts[0]
kv := strings.Split(rawTypeVal, ":")
if len(kv) == 1 {
entry.Type = RuleTypeDomain
entry.Value = strings.ToLower(kv[0])
return nil
}
if len(kv) == 2 {
entry.Type = RuleTypeDomain // Default type
entry.Value = strings.ToLower(rawTypeVal)
} else if len(kv) == 2 {
entry.Type = strings.ToLower(kv[0])
if strings.EqualFold(entry.Type, RuleTypeRegexp) {
if entry.Type == RuleTypeRegexp {
entry.Value = kv[1]
} else {
entry.Value = strings.ToLower(kv[1])
}
return nil
} else {
return entry, fmt.Errorf("invalid format: %s", line)
}
// Check type and value
if !TypeChecker.MatchString(entry.Type) {
return entry, fmt.Errorf("invalid type: %s", entry.Type)
}
if entry.Type == RuleTypeRegexp {
if _, err := regexp.Compile(entry.Value); err != nil {
return entry, fmt.Errorf("invalid regexp: %s", entry.Value)
}
} else if !ValueChecker.MatchString(entry.Value) {
return entry, fmt.Errorf("invalid value: %s", entry.Value)
}
return fmt.Errorf("invalid format: %s", domain)
// Parse/Check attributes
for _, part := range parts[1:] {
if !strings.HasPrefix(part, "@") {
return entry, fmt.Errorf("invalid attribute: %s", part)
}
func parseAttribute(attr string) (*router.Domain_Attribute, error) {
var attribute router.Domain_Attribute
if len(attr) == 0 || attr[0] != '@' {
return &attribute, fmt.Errorf("invalid attribute: %s", attr)
}
attribute.Key = strings.ToLower(attr[1:]) // Trim attribute prefix `@` character
attribute.TypedValue = &router.Domain_Attribute_BoolValue{BoolValue: true}
return &attribute, nil
}
func parseEntry(line string) (Entry, error) {
line = strings.TrimSpace(line)
parts := strings.Split(line, " ")
var entry Entry
if len(parts) == 0 {
return entry, fmt.Errorf("empty entry")
}
if err := parseDomain(parts[0], &entry); err != nil {
return entry, err
}
for i := 1; i < len(parts); i++ {
attr, err := parseAttribute(parts[i])
if err != nil {
return entry, err
attr := strings.ToLower(part[1:]) // Trim attribute prefix `@` character
if !AttrChecker.MatchString(attr) {
return entry, fmt.Errorf("invalid attribute key: %s", attr)
}
entry.Attrs = append(entry.Attrs, attr)
}
// Sort attributes
sort.Slice(entry.Attrs, func(i, j int) bool {
return entry.Attrs[i] < entry.Attrs[j]
})
return entry, nil
}
@@ -201,9 +178,13 @@ func Load(path string) (*List, error) {
}
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
line = removeComment(line)
if len(line) == 0 {
line := scanner.Text()
// Remove comments
if idx := strings.Index(line, "#"); idx != -1 {
line = line[:idx]
}
line = strings.TrimSpace(line)
if line == "" {
continue
}
entry, err := parseEntry(line)
@@ -216,99 +197,80 @@ func Load(path string) (*List, error) {
return list, nil
}
func isMatchAttr(Attrs []*router.Domain_Attribute, includeKey string) bool {
isMatch := false
mustMatch := true
matchName := includeKey
if strings.HasPrefix(includeKey, "!") {
isMatch = true
mustMatch = false
matchName = strings.TrimLeft(includeKey, "!")
}
for _, Attr := range Attrs {
attrName := Attr.Key
if mustMatch {
if matchName == attrName {
isMatch = true
break
}
} else {
if matchName == attrName {
isMatch = false
break
}
}
}
return isMatch
}
func createIncludeAttrEntrys(list *List, matchAttr *router.Domain_Attribute) []Entry {
newEntryList := make([]Entry, 0, len(list.Entry))
matchName := matchAttr.Key
for _, entry := range list.Entry {
matched := isMatchAttr(entry.Attrs, matchName)
if matched {
newEntryList = append(newEntryList, entry)
}
}
return newEntryList
}
func ParseList(list *List, ref map[string]*List) (*ParsedList, error) {
pl := &ParsedList{
Name: list.Name,
Inclusion: make(map[string]bool),
}
entryList := list.Entry
for {
newEntryList := make([]Entry, 0, len(entryList))
hasInclude := false
for _, entry := range entryList {
func ParseList(refList *List) error {
//TODO: one Entry -> multiple ParsedLists
pl := &ParsedList{Name: refList.Name}
for _, entry := range refList.Entry {
if entry.Type == RuleTypeInclude {
refName := strings.ToUpper(entry.Value)
if entry.Attrs != nil {
inc := Inclusion{Source: strings.ToUpper(entry.Value)}
for _, attr := range entry.Attrs {
InclusionName := strings.ToUpper(refName + "@" + attr.Key)
if pl.Inclusion[InclusionName] {
continue
}
pl.Inclusion[InclusionName] = true
refList := ref[refName]
if refList == nil {
return nil, fmt.Errorf("list not found: %s", entry.Value)
}
attrEntrys := createIncludeAttrEntrys(refList, attr)
if len(attrEntrys) != 0 {
newEntryList = append(newEntryList, attrEntrys...)
}
}
if strings.HasPrefix(attr, "-") {
inc.BannedAttrs = append(inc.BannedAttrs, attr[1:]) // Trim attribute prefix `-` character
} else {
InclusionName := refName
if pl.Inclusion[InclusionName] {
continue
inc.MustAttrs = append(inc.MustAttrs, attr)
}
pl.Inclusion[InclusionName] = true
refList := ref[refName]
if refList == nil {
return nil, fmt.Errorf("list not found: %s", entry.Value)
}
newEntryList = append(newEntryList, refList.Entry...)
}
hasInclude = true
pl.Inclusions = append(pl.Inclusions, inc)
} else {
newEntryList = append(newEntryList, entry)
pl.Entry = append(pl.Entry, entry)
}
}
entryList = newEntryList
if !hasInclude {
break
plMap[refList.Name] = pl
return nil
}
}
pl.Entry = entryList
return pl, nil
func ResolveList(pl *ParsedList) error {
if _, pldone := finalMap[pl.Name]; pldone { return nil }
if cirIncMap[pl.Name] {
return fmt.Errorf("circular inclusion in: %s", pl.Name)
}
cirIncMap[pl.Name] = true
defer delete(cirIncMap, pl.Name)
entry2String := func(e Entry) string { // Attributes already sorted
return e.Type + ":" + e.Value + "@" + strings.Join(e.Attrs, "@")
}
isMatchAttrFilters := func(entry Entry, incFilter Inclusion) bool {
if len(incFilter.MustAttrs) == 0 && len(incFilter.BannedAttrs) == 0 { return true }
attrMap := make(map[string]bool)
for _, attr := range entry.Attrs {
attrMap[attr] = true
}
for _, m := range incFilter.MustAttrs {
if !attrMap[m] { return false }
}
for _, b := range incFilter.BannedAttrs {
if attrMap[b] { return false }
}
return true
}
bscDupMap := make(map[string]bool) // Used for basic duplicates detection
var finalList []Entry
for _, dentry := range pl.Entry {
if dstring := entry2String(dentry); !bscDupMap[dstring] {
bscDupMap[dstring] = true
finalList = append(finalList, dentry)
}
}
for _, inc := range pl.Inclusions {
if err := ResolveList(plMap[inc.Source]); err != nil {
return err
}
for _, ientry := range finalMap[inc.Source] {
if isMatchAttrFilters(ientry, inc) {
if istring := entry2String(ientry); !bscDupMap[istring] {
bscDupMap[istring] = true
finalList = append(finalList, ientry)
}
}
}
}
finalMap[pl.Name] = finalList
return nil
}
func main() {
@@ -317,7 +279,7 @@ func main() {
dir := *dataPath
fmt.Println("Use domain lists in", dir)
ref := make(map[string]*List)
// Generate refMap
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
@@ -329,7 +291,7 @@ func main() {
if err != nil {
return err
}
ref[list.Name] = list
refMap[list.Name] = list
return nil
})
if err != nil {
@@ -337,6 +299,22 @@ func main() {
os.Exit(1)
}
// Generate plMap
for _, refList := range refMap {
if err := ParseList(refList); err != nil {
fmt.Println("Failed to ParseList:", err)
os.Exit(1)
}
}
// Generate finalMap
for _, pl := range plMap {
if err := ResolveList(pl); err != nil {
fmt.Println("Failed to ResolveList:", err)
os.Exit(1)
}
}
// Create output directory if not exist
if _, err := os.Stat(*outputDir); os.IsNotExist(err) {
if mkErr := os.MkdirAll(*outputDir, 0755); mkErr != nil {
@@ -345,43 +323,28 @@ func main() {
}
}
protoList := new(router.GeoSiteList)
var existList []string
for refName, list := range ref {
pl, err := ParseList(list, ref)
if err != nil {
fmt.Println("Failed:", err)
os.Exit(1)
// Export plaintext list
if *exportLists != "" {
exportedListSlice := strings.Split(*exportLists, ",")
for _, exportedList := range exportedListSlice {
if err := writePlainList(exportedList); err != nil {
fmt.Println("Failed to write list:", err)
continue
}
site, err := pl.toProto()
fmt.Printf("list: '%s' has been generated successfully.\n", exportedList)
}
}
// Generate dat file
protoList := new(router.GeoSiteList)
for siteName, siteEntries := range finalMap {
site, err := makeProtoList(siteName, siteEntries)
if err != nil {
fmt.Println("Failed:", err)
os.Exit(1)
}
protoList.Entry = append(protoList.Entry, site)
// Flatten and export plaintext list
if *exportLists != "" {
if existList != nil {
exportPlainTextList(existList, refName, pl)
} else {
exportedListSlice := strings.Split(*exportLists, ",")
for _, exportedListName := range exportedListSlice {
fileName := filepath.Join(dir, exportedListName)
_, err := os.Stat(fileName)
if err == nil || os.IsExist(err) {
existList = append(existList, exportedListName)
} else {
fmt.Printf("'%s' list does not exist in '%s' directory.\n", exportedListName, dir)
}
}
if existList != nil {
exportPlainTextList(existList, refName, pl)
}
}
}
}
// Sort protoList so the marshaled list is reproducible
sort.SliceStable(protoList.Entry, func(i, j int) bool {
return protoList.Entry[i].CountryCode < protoList.Entry[j].CountryCode
@@ -389,11 +352,11 @@ func main() {
protoBytes, err := proto.Marshal(protoList)
if err != nil {
fmt.Println("Failed:", err)
fmt.Println("Failed to marshal:", err)
os.Exit(1)
}
if err := os.WriteFile(filepath.Join(*outputDir, *outputName), protoBytes, 0644); err != nil {
fmt.Println("Failed:", err)
fmt.Println("Failed to write output:", err)
os.Exit(1)
} else {
fmt.Println(*outputName, "has been generated successfully.")