Skip to content

Commit eea7d80

Browse files
committed
Add AdGuard DNS filter support
1 parent 9024716 commit eea7d80

File tree

9 files changed

+723
-0
lines changed

9 files changed

+723
-0
lines changed
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
package main
2+
3+
import (
4+
"io"
5+
"os"
6+
"strings"
7+
8+
"github.com/sagernet/sing-box/cmd/sing-box/internal/convertor/adguard"
9+
"github.com/sagernet/sing-box/common/srs"
10+
"github.com/sagernet/sing-box/log"
11+
"github.com/sagernet/sing-box/option"
12+
E "github.com/sagernet/sing/common/exceptions"
13+
14+
"github.com/spf13/cobra"
15+
)
16+
17+
var (
18+
flagRuleSetConvertType string
19+
flagRuleSetConvertOutput string
20+
)
21+
22+
var commandRuleSetConvert = &cobra.Command{
23+
Use: "convert [source-path]",
24+
Short: "Convert adguard DNS filter to rule-set",
25+
Args: cobra.ExactArgs(1),
26+
Run: func(cmd *cobra.Command, args []string) {
27+
err := convertRuleSet(args[0])
28+
if err != nil {
29+
log.Fatal(err)
30+
}
31+
},
32+
}
33+
34+
func init() {
35+
commandRuleSet.AddCommand(commandRuleSetConvert)
36+
commandRuleSetConvert.Flags().StringVarP(&flagRuleSetConvertType, "type", "t", "", "Source type, available: adguard")
37+
commandRuleSetConvert.Flags().StringVarP(&flagRuleSetConvertOutput, "output", "o", flagRuleSetCompileDefaultOutput, "Output file")
38+
}
39+
40+
func convertRuleSet(sourcePath string) error {
41+
var (
42+
reader io.Reader
43+
err error
44+
)
45+
if sourcePath == "stdin" {
46+
reader = os.Stdin
47+
} else {
48+
reader, err = os.Open(sourcePath)
49+
if err != nil {
50+
return err
51+
}
52+
}
53+
var rules []option.HeadlessRule
54+
switch flagRuleSetConvertType {
55+
case "adguard":
56+
rules, err = adguard.Convert(reader)
57+
case "":
58+
return E.New("source type is required")
59+
default:
60+
return E.New("unsupported source type: ", flagRuleSetConvertType)
61+
}
62+
if err != nil {
63+
return err
64+
}
65+
var outputPath string
66+
if flagRuleSetConvertOutput == flagRuleSetCompileDefaultOutput {
67+
if strings.HasSuffix(sourcePath, ".txt") {
68+
outputPath = sourcePath[:len(sourcePath)-4] + ".srs"
69+
} else {
70+
outputPath = sourcePath + ".srs"
71+
}
72+
} else {
73+
outputPath = flagRuleSetConvertOutput
74+
}
75+
outputFile, err := os.Create(outputPath)
76+
if err != nil {
77+
return err
78+
}
79+
defer outputFile.Close()
80+
err = srs.Write(outputFile, option.PlainRuleSet{Rules: rules}, true)
81+
if err != nil {
82+
outputFile.Close()
83+
os.Remove(outputPath)
84+
return err
85+
}
86+
outputFile.Close()
87+
return nil
88+
}

0 commit comments

Comments
 (0)