-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathinit_core.go
More file actions
216 lines (196 loc) · 6.7 KB
/
init_core.go
File metadata and controls
216 lines (196 loc) · 6.7 KB
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
/*
File: init_core.go
Version: 1.105.0
Updated: 11-May-2026 08:37 CEST
Description:
High-level initialization orchestrator and general IO helpers for sdproxy.
Dispatches specific tasks to init_routing, init_policy, and init_upstreams.
Changes:
1.105.0 - [LOGGING] Orchestrated baseline Global Block, DGA, and Bootstrap
diagnostic messages organically using `logSystem`.
1.104.0 - [REFACTOR] Large-scale decomposition. Logic for routing, policies,
and upstreams moved to dedicated init_*.go sub-files.
*/
package main
import (
"bufio"
"fmt"
"io"
"log"
"net"
"net/http"
"net/netip"
"os"
"strings"
"github.com/miekg/dns"
)
// readConfigListFile reads a file line by line, stripping whitespace and inline comments.
func readConfigListFile(filePath string) ([]string, error) {
f, err := os.Open(filePath)
if err != nil {
return nil, err
}
defer f.Close()
var lines []string
scanner := bufio.NewScanner(f)
buf := make([]byte, 64*1024)
scanner.Buffer(buf, 2*1024*1024)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if idx := strings.IndexByte(line, '#'); idx >= 0 {
line = strings.TrimSpace(line[:idx])
}
if line != "" {
lines = append(lines, line)
}
}
return lines, scanner.Err()
}
// readConfigListURL fetches a list of strings from a remote HTTP/HTTPS endpoint securely.
func readConfigListURL(urlStr string) ([]string, error) {
req, err := http.NewRequest(http.MethodGet, urlStr, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", cfg.Server.UserAgent)
resp, err := catHTTPClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("bad HTTP status code: %d", resp.StatusCode)
}
var lines []string
lr := io.LimitReader(resp.Body, 10*1024*1024)
scanner := bufio.NewScanner(lr)
buf := make([]byte, 64*1024)
scanner.Buffer(buf, 2*1024*1024)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if idx := strings.IndexByte(line, '#'); idx >= 0 {
line = strings.TrimSpace(line[:idx])
}
if line != "" {
lines = append(lines, line)
}
}
return lines, scanner.Err()
}
// initBlockAction parses the global 'BLOCK' definition.
func initBlockAction() {
action := strings.ToUpper(strings.TrimSpace(cfg.Server.BlockAction))
if action == "" || action == "NULL" {
globalBlockAction = BlockActionNull
} else if action == "DROP" {
globalBlockAction = BlockActionDrop
} else if action == "LOG" {
globalBlockAction = BlockActionLog
} else if action == "IP" {
globalBlockAction = BlockActionIP
for _, ipStr := range cfg.Server.BlockIPs {
if ip := net.ParseIP(strings.TrimSpace(ipStr)); ip != nil {
if ip.To4() != nil { globalBlockIPv4 = append(globalBlockIPv4, ip.To4()) } else { globalBlockIPv6 = append(globalBlockIPv6, ip.To16()) }
}
}
if len(globalBlockIPv4) == 0 && len(globalBlockIPv6) == 0 { globalBlockAction = BlockActionNull }
} else if rcode, ok := dns.StringToRcode[action]; ok {
globalBlockAction = BlockActionRcode
globalBlockRcode = rcode
} else {
globalBlockAction = BlockActionNull
}
if logSystem {
log.Printf("[INIT] Global Block Action: %s", action)
}
}
// initDGA parses the ML classification definitions for Domain Generation Algorithms.
func initDGA() {
if cfg.Server.DGA.Enabled {
hasDGA = true
if cfg.Server.DGA.Threshold <= 0 { cfg.Server.DGA.Threshold = 80.0 }
if cfg.Server.DGA.Action == "" { cfg.Server.DGA.Action = "BLOCK" }
if logSystem {
log.Printf("[INIT] DGA ML Detection enabled (Threshold: %.1f, Action: %s)", cfg.Server.DGA.Threshold, cfg.Server.DGA.Action)
}
}
}
// initRouteIndex constructs the numerical lookup map required by the cache architecture.
func initRouteIndex() {
routeIdxByName = make(map[string]uint16, len(cfg.Upstreams)+4)
routeIdxByName["local"] = routeIdxLocal
nextIdx := uint16(1)
assignIdx := func(name string) {
if _, exists := routeIdxByName[name]; !exists {
routeIdxByName[name] = nextIdx
nextIdx++
}
}
for groupName := range cfg.Upstreams { assignIdx(groupName) }
for _, dr := range cfg.DomainRoutes { assignIdx(dr.Upstream) }
for _, route := range cfg.Routes {
u := route.Upstream
if u == "" && route.Group != "" {
if grp, ok := cfg.Groups[route.Group]; ok { u = grp.Upstream }
}
if u != "" { assignIdx(u) }
}
routeIdxDefault = routeIdxByName["default"]
}
// initRRs parses global and per-group spoofed records natively
func initRRs() {
globalRRs = make(map[string]spoofRecord)
groupRRs = make(map[string]map[string]spoofRecord)
parseRRMap := func(source map[string]interface{}, dest map[string]spoofRecord) {
for k, v := range source {
domain := lowerTrimDot(k)
var rec spoofRecord
switch val := v.(type) {
case string:
if ip, err := netip.ParseAddr(strings.TrimSpace(val)); err == nil { rec.IPs = append(rec.IPs, ip.Unmap()) } else { rec.CNAME = lowerTrimDot(val) }
case []interface{}:
for _, item := range val {
if str, ok := item.(string); ok {
if ip, err := netip.ParseAddr(strings.TrimSpace(str)); err == nil { rec.IPs = append(rec.IPs, ip.Unmap()) }
}
}
}
dest[domain] = rec
}
}
parseRRMap(cfg.RRs, globalRRs)
for grpName, grpCfg := range cfg.Groups {
if len(grpCfg.RRs) > 0 {
gm := make(map[string]spoofRecord)
parseRRMap(grpCfg.RRs, gm)
groupRRs[grpName] = gm
}
}
hasRRs = len(globalRRs) > 0 || len(groupRRs) > 0
}
// initDDR maps RFC 9462 Discovery of Designated Resolvers endpoints.
func initDDR() {
if cfg.Server.ECHConfigList != "" {
if b, err := os.ReadFile(cfg.Server.ECHConfigList); err == nil { ddrECHConfig = b }
}
if cfg.Server.DDR.Enabled {
ddrHostnames = make(map[string]bool)
source := cfg.Server.DDR.HostnameSource
if source == "" { source = "strict" }
var raw []string
if source == "strict" || source == "both" { raw = append(raw, cfg.Server.DDR.Hostnames...) }
if source == "tls" || source == "both" { raw = append(raw, tlsAuthorizedNames...) }
for _, h := range raw {
clean := strings.ToLower(strings.TrimSuffix(h, "."))
if clean != "" && !strings.Contains(clean, "*") && net.ParseIP(clean) == nil {
if !ddrHostnames[clean] { ddrHostnames[clean] = true; ddrHostnamesList = append(ddrHostnamesList, clean) }
}
}
for _, s := range cfg.Server.DDR.IPv4 { if ip := net.ParseIP(s); ip != nil { ddrIPv4 = append(ddrIPv4, ip) } }
for _, s := range cfg.Server.DDR.IPv6 { if ip := net.ParseIP(s); ip != nil { ddrIPv6 = append(ddrIPv6, ip) } }
ddrDoHPort, ddrDoTPort, ddrDoQPort = 0, 0, 0
for _, addr := range cfg.Server.ListenDoH { ddrDoHPort = extractPort(addr, 443) }
for _, addr := range cfg.Server.ListenDoT { ddrDoTPort = extractPort(addr, 853) }
for _, addr := range cfg.Server.ListenDoQ { ddrDoQPort = extractPort(addr, 853) }
}
}