-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathconfig.go
More file actions
401 lines (347 loc) · 13 KB
/
config.go
File metadata and controls
401 lines (347 loc) · 13 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
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
/*
File: config.go
Version: 1.37.0
Updated: 21-Apr-2026 15:10 CEST
Description:
All YAML-mapped configuration structs for sdproxy. Covers every top-level
config section: server, logging, cache, identity, upstreams, routes,
domain_routes, rtype/domain policy, parental groups, categories, and webui.
Changes:
1.37.0 - [FEAT] Expanded `SupportIPVersion` documentation to reflect new
enforcement across listeners, upstreams, and bootstrap resolvers.
1.36.0 - [FEAT] Added `SupportIPVersion` to Server configuration to selectively
filter resource loading for IPv4 and IPv6 globally.
1.35.0 - [FEAT] Added `Mode` to `UpstreamGroupConfig`. This enables "strict"
deep-inspection payload matching for the `secure` strategy, allowing
the engine to validate exact end-answers (A/AAAA) independently of
RR-set order or CNAME differences.
*/
package main
import (
"fmt"
"log"
"strings"
"gopkg.in/yaml.v3"
)
// ---------------------------------------------------------------------------
// ACLConfig
// ---------------------------------------------------------------------------
// ACLConfig holds IP/Subnet allow and deny lists.
type ACLConfig struct {
Allow []string `yaml:"allow"`
Deny []string `yaml:"deny"`
}
// ---------------------------------------------------------------------------
// RouteConfig / ParsedRoute
// ---------------------------------------------------------------------------
// RouteConfig maps a MAC/IP/CIDR/ASN key to an upstream group, an optional client
// name override, the optional bypass_local flag, and an optional parental group.
type RouteConfig struct {
Upstream string `yaml:"upstream"`
ClientName string `yaml:"client_name"`
BypassLocal bool `yaml:"bypass_local"`
Group string `yaml:"group"`
}
// ParsedRoute is the resolved runtime form of RouteConfig.
type ParsedRoute struct {
Upstream string
ClientName string
BypassLocal bool
}
// ---------------------------------------------------------------------------
// DomainRouteConfig / domainRouteEntry
// ---------------------------------------------------------------------------
// DomainRouteConfig is the YAML config form for domain_routes entries.
type DomainRouteConfig struct {
Upstream string `yaml:"upstream"`
BypassLocal bool `yaml:"bypass_local"`
}
// UnmarshalYAML handles both the compact scalar and the expanded map form.
func (d *DomainRouteConfig) UnmarshalYAML(value *yaml.Node) error {
switch value.Kind {
case yaml.ScalarNode:
d.Upstream = value.Value
return nil
case yaml.MappingNode:
type plain DomainRouteConfig
return value.Decode((*plain)(d))
default:
return fmt.Errorf("domain_routes: expected string or map, got %s", value.Tag)
}
}
type domainRouteEntry struct {
upstream string
bypassLocal bool
}
// ---------------------------------------------------------------------------
// UpstreamGroupConfig
// ---------------------------------------------------------------------------
// UpstreamGroupConfig is the YAML config form for upstreams entries.
type UpstreamGroupConfig struct {
Strategy string `yaml:"strategy"`
Preference string `yaml:"preference"`
Mode string `yaml:"mode"`
Servers []string `yaml:"servers"`
}
func (u *UpstreamGroupConfig) UnmarshalYAML(value *yaml.Node) error {
if value.Kind == yaml.SequenceNode {
return value.Decode(&u.Servers)
} else if value.Kind == yaml.MappingNode {
type plain UpstreamGroupConfig
return value.Decode((*plain)(u))
}
return fmt.Errorf("upstreams: expected list of strings or map, got %v", value.Kind)
}
// ---------------------------------------------------------------------------
// ScheduleList
// ---------------------------------------------------------------------------
type ScheduleList []string
func (sl *ScheduleList) UnmarshalYAML(value *yaml.Node) error {
switch value.Kind {
case yaml.ScalarNode:
if value.Value != "" {
*sl = ScheduleList{value.Value}
}
return nil
case yaml.SequenceNode:
var list []string
if err := value.Decode(&list); err != nil {
return err
}
*sl = ScheduleList(list)
return nil
default:
return fmt.Errorf("schedule: expected a string or a list of strings, got %s", value.Tag)
}
}
// ---------------------------------------------------------------------------
// GroupConfig
// ---------------------------------------------------------------------------
type GroupConfig struct {
Upstream string `yaml:"upstream"`
BypassLocal bool `yaml:"bypass_local"`
Schedule ScheduleList `yaml:"schedule"`
BlockTTL int `yaml:"block_ttl"`
Budget map[string]string `yaml:"budget"`
BudgetTracking string `yaml:"budget_tracking"`
}
// ---------------------------------------------------------------------------
// CategoryConfig
// ---------------------------------------------------------------------------
type CategoryConfig struct {
ListURLs []string
IdlePause string `yaml:"idle_pause"`
SessionWindow string `yaml:"session_window"`
Add []string `yaml:"add"`
Remove []string `yaml:"remove"`
}
func (c *CategoryConfig) UnmarshalYAML(value *yaml.Node) error {
type plain CategoryConfig
type withURL struct {
plain `yaml:",inline"`
Source yaml.Node `yaml:"source"`
ListURL string `yaml:"list_url"`
ListURLs []string `yaml:"list_urls"`
}
var w withURL
if err := value.Decode(&w); err != nil {
return err
}
*c = CategoryConfig(w.plain)
switch {
case w.Source.Kind == yaml.ScalarNode && w.Source.Value != "":
c.ListURLs = []string{w.Source.Value}
case w.Source.Kind == yaml.SequenceNode:
if err := w.Source.Decode(&c.ListURLs); err != nil {
return fmt.Errorf("source: %w", err)
}
case len(w.ListURLs) > 0:
c.ListURLs = w.ListURLs
case w.ListURL != "":
c.ListURLs = []string{w.ListURL}
}
return nil
}
// ---------------------------------------------------------------------------
// ParentalConfig
// ---------------------------------------------------------------------------
type ParentalConfig struct {
FastStart bool `yaml:"fast_start"`
ForcedTTL int `yaml:"forced_ttl"`
BlockTTL int `yaml:"block_ttl"`
TickerInterval int `yaml:"ticker_interval"`
DefaultIdlePause string `yaml:"default_idle_pause"`
DefaultSessionWindow string `yaml:"default_session_window"`
SnapshotDir string `yaml:"snapshot_dir"`
Consolidation *bool `yaml:"consolidation"`
SynthesiseParents *bool `yaml:"synthesise_parents"`
RemoveRedundantSubdomains *bool `yaml:"remove_redundant_subdomains"`
StripServiceLabels *bool `yaml:"strip_service_labels"`
ParentConsolidationThreshold int `yaml:"parent_consolidation_threshold"`
ConsolidationHomogeneityPct int `yaml:"consolidation_homogeneity_pct"`
Categories map[string]CategoryConfig `yaml:"categories"`
}
// ---------------------------------------------------------------------------
// WebUIConfig
// ---------------------------------------------------------------------------
type WebUIConfig struct {
Enabled bool `yaml:"enabled"`
Listen string `yaml:"listen"`
ListenHTTP []string `yaml:"listen_http"`
ListenHTTPS []string `yaml:"listen_https"`
ForceHTTPS bool `yaml:"force_https"`
Password string `yaml:"password"`
APIToken string `yaml:"api_token"`
ACL ACLConfig `yaml:"acl"`
LoginRatelimit struct {
Enabled bool `yaml:"enabled"`
MaxAttempts int `yaml:"max_attempts"`
LockoutMinutes int `yaml:"lockout_minutes"`
} `yaml:"login_ratelimit"`
StatsEnabled bool `yaml:"stats_enabled"`
StatsRefreshSec int `yaml:"stats_refresh_sec"`
StatsTopN int `yaml:"stats_top_n"`
StatsGraphsEnabled bool `yaml:"stats_graphs_enabled"`
HistoryDir string `yaml:"history_dir"`
HistoryRetentionHours int `yaml:"history_retention_hours"`
HistorySaveInterval string `yaml:"history_save_interval"`
}
// ---------------------------------------------------------------------------
// Top-level Config
// ---------------------------------------------------------------------------
type Config struct {
Server struct {
ListenUDP []string `yaml:"listen_udp"`
ListenTCP []string `yaml:"listen_tcp"`
ListenDoT []string `yaml:"listen_dot"`
ListenDoH []string `yaml:"listen_doh"`
ListenDoQ []string `yaml:"listen_doq"`
UDPWorkers int `yaml:"udp_workers"`
TLSCert string `yaml:"tls_cert"`
TLSKey string `yaml:"tls_key"`
MemoryLimitMB int `yaml:"memory_limit_mb"`
ACL ACLConfig `yaml:"acl"`
RateLimit struct {
Enabled bool `yaml:"enabled"`
QPS float64 `yaml:"qps"`
Burst float64 `yaml:"burst"`
IPv4PrefixLength int `yaml:"ipv4_prefix_length"`
IPv6PrefixLength int `yaml:"ipv6_prefix_length"`
MaxTrackedIPs int `yaml:"max_tracked_ips"`
Exempt []string `yaml:"exempt"`
PenaltyBox struct {
Enabled bool `yaml:"enabled"`
StrikeThreshold int `yaml:"strike_threshold"`
BanDurationMin int `yaml:"ban_duration_min"`
} `yaml:"penalty_box"`
} `yaml:"rate_limit"`
SupportIPVersion string `yaml:"support_ip_version"`
RebindingProtection bool `yaml:"rebinding_protection"`
FilterAAAA bool `yaml:"filter_aaaa"`
FilterIPs bool `yaml:"filter_ips"`
StrictPTR bool `yaml:"strict_ptr"`
FlattenCNAME bool `yaml:"flatten_cname"`
TargetName bool `yaml:"target_name"`
MinimizeAnswer bool `yaml:"minimize_answer"`
BlockObsoleteQtypes bool `yaml:"block_obsolete_qtypes"`
UpstreamSelection string `yaml:"upstream_selection"`
UpstreamStaggerMs int `yaml:"upstream_stagger_ms"`
UpstreamTimeoutMs int `yaml:"upstream_timeout_ms"`
SyntheticTTL int `yaml:"synthetic_ttl"`
BootstrapServers []string `yaml:"bootstrap_servers"`
DDR struct {
Enabled bool `yaml:"enabled"`
Hostnames []string `yaml:"hostnames"`
IPv4 []string `yaml:"ipv4"`
IPv6 []string `yaml:"ipv6"`
} `yaml:"ddr"`
} `yaml:"server"`
Logging struct {
LogQueries *bool `yaml:"log_queries"`
StripTime bool `yaml:"strip_time"`
LogASNDetails bool `yaml:"log_asn_details"`
} `yaml:"logging"`
Cache struct {
Enabled bool `yaml:"enabled"`
Size int `yaml:"size"`
MinTTL int `yaml:"min_ttl"`
MaxTTL int `yaml:"max_ttl"`
NegativeTTL int `yaml:"negative_ttl"`
StaleTTL int `yaml:"stale_ttl"`
PrefetchBefore int `yaml:"prefetch_before"`
PrefetchMinHits int `yaml:"prefetch_min_hits"`
SweepIntervalS int `yaml:"sweep_interval_s"`
CacheSynthetic bool `yaml:"cache_synthetic"`
CacheLocalIdentity bool `yaml:"cache_local_identity"`
CacheUpstreamNegative bool `yaml:"cache_upstream_negative"`
AnswerSort string `yaml:"answer_sort"`
} `yaml:"cache"`
Identity struct {
HostsFiles []string `yaml:"hosts_files"`
DnsmasqLeases []string `yaml:"dnsmasq_leases"`
IscLeases []string `yaml:"isc_leases"`
KeaLeases []string `yaml:"kea_leases"`
OdhcpdLeases []string `yaml:"odhcpd_leases"`
IPInfoASN []string `yaml:"ipinfo_asn"`
ASNCacheDir string `yaml:"asn_cache_dir"`
ASNPollInterval string `yaml:"asn_poll_interval"`
ASNFastStart bool `yaml:"asn_fast_start"`
PollInterval int `yaml:"poll_interval"`
} `yaml:"identity"`
Upstreams map[string]UpstreamGroupConfig `yaml:"upstreams"`
Routes map[string]RouteConfig `yaml:"routes"`
RoutesFiles map[string]RouteConfig `yaml:"routes_files"`
DomainRoutes map[string]DomainRouteConfig `yaml:"domain_routes"`
DomainRoutesFiles map[string]DomainRouteConfig `yaml:"domain_routes_files"`
RtypePolicy map[string]string `yaml:"rtype_policy"`
RtypePolicyFiles map[string]string `yaml:"rtype_policy_files"`
DomainPolicy map[string]string `yaml:"domain_policy"`
DomainPolicyFiles map[string]string `yaml:"domain_policy_files"`
Groups map[string]GroupConfig `yaml:"groups"`
Parental ParentalConfig `yaml:"parental"`
WebUI WebUIConfig `yaml:"webui"`
}
var cfg Config
func validateConfig() error {
// Normalize support_ip_version
v := strings.ToLower(cfg.Server.SupportIPVersion)
switch v {
case "ipv4", "ipv6", "both":
cfg.Server.SupportIPVersion = v
default:
cfg.Server.SupportIPVersion = "both"
}
if cfg.Cache.CacheLocalIdentity {
st := cfg.Server.SyntheticTTL
if st == 0 {
st = 60
}
pi := cfg.Identity.PollInterval
if pi > 0 && st > pi {
return fmt.Errorf(
"cache_local_identity: synthetic_ttl (%ds) > identity.poll_interval (%ds) — "+
"stale local addresses may be served; lower synthetic_ttl or raise poll_interval",
st, pi)
}
}
sortMethod := strings.ToLower(cfg.Cache.AnswerSort)
switch sortMethod {
case "", "none", "round-robin", "random", "ip-sort":
cfg.Cache.AnswerSort = sortMethod
default:
log.Printf("[WARN] Invalid cache.answer_sort %q — falling back to 'none'", sortMethod)
cfg.Cache.AnswerSort = "none"
}
for name, grp := range cfg.Groups {
if grp.Budget == nil {
continue
}
norm := make(map[string]string, len(grp.Budget))
for k, v := range grp.Budget {
norm[strings.ToLower(k)] = v
}
grp.Budget = norm
cfg.Groups[name] = grp
}
return nil
}