forked from cbuijs/sdproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess.go
More file actions
executable file
·672 lines (613 loc) · 25.4 KB
/
process.go
File metadata and controls
executable file
·672 lines (613 loc) · 25.4 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
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
/*
File: process.go
Version: 2.2.2
Updated: 2026-03-23 12:20 CET
Description:
Per-query DNS processing pipeline for sdproxy.
Pipeline (cache-first design):
── pre-cache (every query) ──────────────────────────────────────
0. Sanity + throttle.
1. Normalise qname.
2. Route determination — domain walk (domain_policy exit +
route override), then MAC route override. Domain wins.
3. Parental block gate — CheckParental before cache so a domain
blocked for this group is never served from a cross-group entry.
4. CACHE LOOKUP — hit → apply parental TTL cap, transform, write,
optional background revalidation, lazy log, return.
── cache miss path (only on a miss) ─────────────────────────────
5. rtype / obsolete / AAAA-filter / strict-PTR policy exits.
6. DDR interception.
7. Full client identity (deferred from pre-cache when not needed).
8. Local A/AAAA/PTR from hosts/leases.
9. Upstream pre-validation + forwarding via singleflight.
10. Error handling.
11. Response transforms + parental TTL cap.
12. Final reply + log.
Synthetic & negative caching (controlled by config flags):
cache_synthetic: true — stores policy exit responses (domain_policy,
rtype_policy, AAAA filter, strict_ptr, obsolete qtypes) at
syntheticTTL via CacheSetSynth. On repeat queries the cache hit at
step 4 skips domain walks, policy lookups, and qtype checks.
cache_local_identity: true — stores local A/AAAA/PTR responses from
hosts/leases at syntheticTTL via CacheSetSynth. Safe only when
syntheticTTL ≤ identity.poll_interval.
cache_upstream_negative: false — suppresses CacheSet for upstream
NXDOMAIN and NODATA responses. Default true (RFC 2308 compliant).
Upstream processing optimisations (v2.1.0, no protocol changes):
1. Skip res.msg.Copy() when !shared — when the singleflight result
was not shared with other waiters this goroutine owns the pointer.
CacheSet already packed it to independent wire bytes so we can
mutate res.msg directly (transforms + ID patch). Saves ~1 alloc
per non-coalesced upstream call — the common case on a home router.
2. Upstream pre-validation before sfGroup.Do — a missing or empty
upstream group now fails immediately without allocating a
singleflight slot or key string.
3. Negative caching gate inside the singleflight closure — single
bool load (cacheUpstreamNeg) before CacheSet on every upstream call.
Parental TTL cap on cache hits (v2.0.0 fix):
v1.x cache hits bypassed CapResponseTTL, breaking the parental
heartbeat: TTL-compliant clients cached the full upstream TTL and
stopped re-querying during active parental sessions. Fixed.
Subsystem splits — unchanged:
ddr.go — handleDDR
policy.go — writePolicyResp, walkDomainMaps, CapResponseTTL,
lowerTrimDot, isValidReversePTR, getRouteIdx
transform.go — transformResponse, responseContainsNullIP
cache.go — CacheGet, CacheSet, CacheSetSynth
parental.go — CheckParental
Changes:
2.2.2 - [FEAT] Local identity suffix matching is now restricted to null-IPs
(0.0.0.0 or ::) to prevent unintended wildcarding of legitimate local
hosts. Exact matches still work for any IP.
2.2.1 - [FIX] Removed stray closing brace at the end of the file.
2.2.0 - [FEAT] Local identity suffix matching: logs now indicate if a subdomain
matched a parent domain in the local identity file (e.g. hosts file).
2.1.0 - [FEAT] Synthetic response caching — policy exits, local identity.
buildSynthCacheMsg helper; cacheSynthFlag + cacheLocalIdentity gates.
[FEAT] Configurable upstream negative caching (cacheUpstreamNeg).
[PERF] Skip res.msg.Copy() when !shared — saves 1 alloc per
non-coalesced upstream call.
[PERF] Upstream pre-validation before sfGroup.Do — fail fast on
misconfigured routes without acquiring a singleflight slot.
2.0.0 - [PERF] Cache moved to step 4 — immediately after route + parental.
Policy, DDR, identity deferred to miss path.
[FIX] Parental TTL cap applied to cache hits (v1.x omission).
[PERF] Identity resolution deferred for simple setups.
[PERF] buildClientID lazy on hit path.
1.54.0 - logQueries/syntheticTTL → globals.go; clientName/clientID upfront.
1.53.0 - DDR → ddr.go, policy → policy.go, transforms → transform.go.
1.52.0 - Pool-based CacheGet — no new(dns.Msg) on cache hit.
1.51.0 - syntheticTTL global; NXDOMAIN SOA in buildPolicyRespCache.
1.50.1 - Parental block TypeA → 0.0.0.0; others → NXDOMAIN.
... Older commit-information removed for brevity.
*/
package main
import (
"log"
"net"
"strings"
"sync"
"sync/atomic"
"github.com/miekg/dns"
"golang.org/x/sync/singleflight"
)
// clientIDPool recycles strings.Builder for "ip (name)" log labels.
var clientIDPool = sync.Pool{New: func() any { return new(strings.Builder) }}
// sfGroup coalesces concurrent cache-miss queries for the same
// (qname, qtype, routeIdx, [clientName]) tuple into a single upstream call.
var sfGroup singleflight.Group
// sfResult carries the upstream response and the server address that served it.
type sfResult struct {
msg *dns.Msg
addr string
}
// coalescedTotal counts queries answered from a shared singleflight call.
var coalescedTotal atomic.Int64
// revalSemCap caps simultaneous background revalidation goroutines to prevent
// pile-up when many stale entries expire at once.
const revalSemCap = 32
var revalSem = make(chan struct{}, revalSemCap)
// msgPool recycles *dns.Msg for CacheGet and backgroundRevalidate.
// Pattern: Get → zero (*msg = dns.Msg{}) → use → Put.
var msgPool = sync.Pool{New: func() any { return new(dns.Msg) }}
// ---------------------------------------------------------------------------
// Synthetic response helper
// ---------------------------------------------------------------------------
// buildSynthCacheMsg constructs a minimal dns.Msg for storing in the cache
// as a synthesised response. Called from the miss path when cacheSynthFlag
// or cacheLocalIdentity is true and a policy check or local lookup fires.
//
// For NXDOMAIN a synthetic SOA is placed in the authority section so
// RFC 2308-compliant stub resolvers respect syntheticTTL as the negative-
// caching TTL (same SOA pattern as buildPolicyRespCache in policy.go).
//
// The returned message has the correct Question section so CacheGet can serve
// it verbatim — unlike the policyRespCache templates which use "." as a
// placeholder and must be patched at serve time.
func buildSynthCacheMsg(q dns.Question, rcode int) *dns.Msg {
msg := new(dns.Msg)
msg.Response = true
msg.Rcode = rcode
msg.RecursionAvailable = true
msg.Question = []dns.Question{q}
if rcode == dns.RcodeNameError {
msg.Ns = []dns.RR{&dns.SOA{
Hdr: dns.RR_Header{Name: ".", Rrtype: dns.TypeSOA, Class: dns.ClassINET, Ttl: syntheticTTL},
Ns: "ns.sdproxy.",
Mbox: "hostmaster.sdproxy.",
Serial: 1,
Refresh: 3600,
Retry: 600,
Expire: 86400,
Minttl: syntheticTTL, // must equal Hdr.Ttl — RFC 2308 §3
}}
}
return msg
}
// ---------------------------------------------------------------------------
// ProcessDNS — main query handler, called by all server transports
// ---------------------------------------------------------------------------
func ProcessDNS(w dns.ResponseWriter, r *dns.Msg, clientIP, protocol string) {
// ── 0. Sanity + throttle ──────────────────────────────────────────────
if len(r.Question) == 0 {
dns.HandleFailed(w, r)
return
}
if !AcquireQuery() {
return
}
defer ReleaseQuery()
IncrQueryTotal()
q := r.Question[0]
originalID := r.Id
qNameTrimmed := lowerTrimDot(q.Name)
// ── 1. Route determination ────────────────────────────────────────────
// Build the RouteIdx needed for the cache key in two sub-steps:
// a. Domain walk — one O(label-depth) pass that handles both
// domain_policy exits (synthetic, never cached on default config) and
// domain route overrides.
// b. MAC route — per-client upstream override; requires identity.
// Domain route overrides MAC when both match (most-specific wins).
routeIdx := routeIdxDefault
routeName := "default"
routeOriginType := "DEFAULT"
bypassLocal := false
var (
domainRouteMatched bool
domainRouteUpstream string
domainRouteBypass bool
)
if hasDomainRoutes || hasDomainPolicy {
policyRcode, policyBlocked, drUpstream, drBypass, drMatched := walkDomainMaps(qNameTrimmed)
_ = policyBlocked // consumed via policyRcode != 0 check below
if policyRcode != 0 {
// domain_policy synthetic exit — write, optionally cache, return.
writePolicyResp(w, r, policyRcode)
if cacheSynthFlag {
// Use routeIdxDefault: domain_policy is global and applies
// before the client's route is fully resolved.
synKey := DNSCacheKey{
Name: qNameTrimmed,
Qtype: q.Qtype,
Qclass: q.Qclass,
RouteIdx: routeIdxDefault,
}
CacheSetSynth(synKey, buildSynthCacheMsg(q, policyRcode))
}
return
}
domainRouteMatched = drMatched
domainRouteUpstream = drUpstream
domainRouteBypass = drBypass
}
// Identity is resolved here only when a pre-cache feature needs it
// (MAC routes, parental control, {client-name} upstream URL templates).
// For simple setups without any of those, identity is deferred to step 7.
// clientMAC and clientName are populated pre-cache only when a feature
// needs them (MAC routes, parental, {client-name} templates). For simple
// setups both stay empty here and are filled in at step 5 on the miss path.
var (
clientName string
clientMAC string
identityResolved bool
)
if hasMACRoutes || hasParental || hasClientNameUpstream {
clientMAC = LookupMAC(clientIP)
clientName = LookupNameByMACOrIP(clientMAC, clientIP)
identityResolved = true
}
// Apply MAC route first; domain route overrides if both match.
if hasMACRoutes && clientMAC != "" {
if route, ok := macRoutes[clientMAC]; ok {
if route.Upstream != "" {
routeName = route.Upstream
routeIdx = getRouteIdx(route.Upstream)
routeOriginType = "MAC"
}
bypassLocal = route.BypassLocal
if route.ClientName != "" {
clientName = route.ClientName
}
}
}
if domainRouteMatched {
routeName = domainRouteUpstream
routeIdx = getRouteIdx(domainRouteUpstream)
routeOriginType = "DOMAIN"
bypassLocal = domainRouteBypass
}
// ── 2. Parental block gate ────────────────────────────────────────────
// Runs before the cache lookup so a domain blocked for this client's group
// is never served from a cache entry written by a different group sharing
// the same RouteIdx upstream path.
var parentalForcedTTL uint32
if hasParental && clientMAC != "" {
blocked, blockTTL, forcedTTL := CheckParental(clientMAC, clientIP, clientName, qNameTrimmed)
if blocked {
resp := new(dns.Msg)
resp.SetReply(r)
if q.Qtype == dns.TypeA {
// 0.0.0.0 is less disruptive than NXDOMAIN for A queries —
// clients fail gracefully instead of caching a hard negative.
resp.Answer = append(resp.Answer, &dns.A{
Hdr: dns.RR_Header{Name: q.Name, Rrtype: dns.TypeA,
Class: dns.ClassINET, Ttl: blockTTL},
A: net.IPv4zero,
})
} else {
// All other types: NXDOMAIN prevents IPv6 bypass.
resp.SetRcode(r, dns.RcodeNameError)
}
w.WriteMsg(resp)
if logQueries {
log.Printf("[DNS] [%s] %s -> %s %s | PARENTAL BLOCK",
protocol, buildClientID(clientIP, clientName),
q.Name, dns.TypeToString[q.Qtype])
}
return
}
parentalForcedTTL = forcedTTL
}
// ── 3. CACHE LOOKUP ───────────────────────────────────────────────────
// Primary fast-exit. All pre-cache work above is pure in-memory map
// lookups — no I/O, no syscalls beyond lowerTrimDot.
//
// Policy checks, DDR, and local identity are on the miss path because by
// default their responses are never stored in cache — a hit here proves
// they don't apply.
//
// When cacheSynthFlag / cacheLocalIdentity are true, policy and local
// identity responses ARE stored (via CacheSetSynth). On repeat queries
// the hit here skips those checks entirely.
cacheKey := DNSCacheKey{Name: qNameTrimmed, Qtype: q.Qtype, Qclass: q.Qclass, RouteIdx: routeIdx}
{
poolMsg := msgPool.Get().(*dns.Msg)
*poolMsg = dns.Msg{}
if isStale, isPrefetch, cacheOK := CacheGet(cacheKey, poolMsg); cacheOK {
// Apply parental TTL cap before writing — fixes the v1.x omission
// where cache hits bypassed the heartbeat TTL, causing TTL-compliant
// clients to stop re-querying during active parental sessions.
if parentalForcedTTL > 0 {
CapResponseTTL(poolMsg, parentalForcedTTL)
}
poolMsg.Id = originalID
resp := transformResponse(poolMsg, q.Qtype, true)
w.WriteMsg(resp)
if isStale {
go backgroundRevalidate(cacheKey, routeName, clientName)
}
if logQueries {
// buildClientID is lazy here — avoids a string allocation on
// every silent cache hit in production (logQueries: false).
clientID := buildClientID(clientIP, clientName)
var status string
switch {
case isStale:
status = "STALE (revalidating)"
case isPrefetch:
status = "CACHE HIT (prefetching)"
case responseContainsNullIP(resp):
status = "CACHE HIT (NULL-IP)"
default:
status = "CACHE HIT"
}
log.Printf("[DNS] [%s] %s -> %s %s | ROUTE(%s): %s | %s",
protocol, clientID, q.Name, dns.TypeToString[q.Qtype],
routeOriginType, routeName, status)
}
msgPool.Put(poolMsg)
return
}
msgPool.Put(poolMsg)
}
// ════════════════════════════════════════════════════════════════════════
// CACHE MISS PATH — everything below runs only when the cache has no entry.
// ════════════════════════════════════════════════════════════════════════
// ── 4. Policy exits ───────────────────────────────────────────────────
// Safe on the miss path: none of these call CacheSet on the normal path,
// so there is no cached entry to find at step 3. On first miss they run
// once; when cacheSynthFlag is true the result is stored and future queries
// hit at step 3 without reaching here.
if hasRtypePolicy {
if rcode, blocked := rtypePolicy[q.Qtype]; blocked {
writePolicyResp(w, r, rcode)
if cacheSynthFlag {
CacheSetSynth(cacheKey, buildSynthCacheMsg(q, rcode))
}
return
}
}
if blockUnknownQtypes {
if _, obsolete := obsoleteQtypes[q.Qtype]; obsolete {
writePolicyResp(w, r, dns.RcodeNotImplemented)
if cacheSynthFlag {
CacheSetSynth(cacheKey, buildSynthCacheMsg(q, dns.RcodeNotImplemented))
}
return
}
}
if cfg.Server.FilterAAAA && q.Qtype == dns.TypeAAAA {
// NOERROR + empty answer section — RFC-compliant AAAA suppression.
writePolicyResp(w, r, dns.RcodeSuccess)
if cacheSynthFlag {
CacheSetSynth(cacheKey, buildSynthCacheMsg(q, dns.RcodeSuccess))
}
return
}
if cfg.Server.StrictPTR && q.Qtype == dns.TypePTR && !isValidReversePTR(qNameTrimmed) {
writePolicyResp(w, r, dns.RcodeNameError)
if cacheSynthFlag {
CacheSetSynth(cacheKey, buildSynthCacheMsg(q, dns.RcodeNameError))
}
return
}
// ── 5. Full client identity ───────────────────────────────────────────
// Pre-cache resolved it only when MAC routes / parental / {client-name}
// required it. For simple setups we reach here without it — resolve now.
if !identityResolved {
clientMAC = LookupMAC(clientIP)
clientName = LookupNameByMACOrIP(clientMAC, clientIP)
}
clientID := buildClientID(clientIP, clientName)
// ── 6. DDR interception ───────────────────────────────────────────────
// Synthetic; never cached — ddr.go builds per-address responses that are
// not stable enough to cache meaningfully.
if handleDDR(w, r, q, qNameTrimmed, clientID, protocol) {
return
}
// ── 7. Local A/AAAA/PTR answers from hosts/leases ─────────────────────
// Skipped when the matched route has bypass_local: true.
//
// cacheLocalIdentity: when true, the response is stored via CacheSetSynth
// so repeat lookups for the same local hostname skip the identity file scan.
//
// WARNING: only enable cache_local_identity when syntheticTTL ≤
// identity.poll_interval. If syntheticTTL > poll_interval, a stale local
// address may be served after a hosts/leases file change.
//
// The parental TTL cap is applied AFTER storing — the cached entry always
// carries the full syntheticTTL, and the cap is re-applied on every cache
// hit at step 3 via CapResponseTTL.
if !bypassLocal {
switch q.Qtype {
case dns.TypeA, dns.TypeAAAA:
if addrs, match := LookupIPsByNameLower(qNameTrimmed); len(addrs) > 0 {
resp := new(dns.Msg)
resp.SetReply(r)
resp.Authoritative = true
resp.Answer = make([]dns.RR, 0, len(addrs))
for _, addr := range addrs {
switch {
case addr.Is4() && q.Qtype == dns.TypeA:
ip4 := addr.As4()
resp.Answer = append(resp.Answer, &dns.A{
Hdr: dns.RR_Header{Name: q.Name, Rrtype: dns.TypeA,
Class: dns.ClassINET, Ttl: syntheticTTL},
A: net.IP(ip4[:]),
})
case addr.Is6() && !addr.Is4In6() && q.Qtype == dns.TypeAAAA:
ip6 := addr.As16()
resp.Answer = append(resp.Answer, &dns.AAAA{
Hdr: dns.RR_Header{Name: q.Name, Rrtype: dns.TypeAAAA,
Class: dns.ClassINET, Ttl: syntheticTTL},
AAAA: net.IP(ip6[:]),
})
}
}
if len(resp.Answer) > 0 {
if cacheLocalIdentity {
CacheSetSynth(cacheKey, resp)
}
if parentalForcedTTL > 0 {
CapResponseTTL(resp, parentalForcedTTL)
}
w.WriteMsg(resp)
if logQueries {
matchInfo := ""
if match != qNameTrimmed {
matchInfo = " (matched " + match + ")"
}
log.Printf("[DNS] [%s] %s -> %s %s | ROUTE(%s): %s | LOCAL%s",
protocol, clientID, q.Name, dns.TypeToString[q.Qtype],
routeOriginType, routeName, matchInfo)
}
return
}
}
case dns.TypePTR:
if names := LookupNamesByARPA(qNameTrimmed); len(names) > 0 {
resp := new(dns.Msg)
resp.SetReply(r)
resp.Authoritative = true
resp.Answer = make([]dns.RR, 0, len(names))
for _, name := range names {
resp.Answer = append(resp.Answer, &dns.PTR{
Hdr: dns.RR_Header{Name: q.Name, Rrtype: dns.TypePTR,
Class: dns.ClassINET, Ttl: syntheticTTL},
Ptr: dns.Fqdn(name),
})
}
if cacheLocalIdentity {
CacheSetSynth(cacheKey, resp)
}
w.WriteMsg(resp)
if logQueries {
log.Printf("[DNS] [%s] %s -> %s PTR | ROUTE(%s): %s | LOCAL",
protocol, clientID, q.Name, routeOriginType, routeName)
}
return
}
}
}
// ── 8. Upstream selection + pre-validation ────────────────────────────
// Validate before sfGroup.Do so a misconfigured or missing route fails
// immediately without allocating a singleflight slot or key string.
upstreams, exists := routeUpstreams[routeName]
if !exists || len(upstreams) == 0 {
upstreams = routeUpstreams["default"]
}
if len(upstreams) == 0 {
log.Printf("[DNS] [%s] %s -> %s %s | ROUTE(%s): %s | NO UPSTREAMS CONFIGURED",
protocol, clientID, q.Name, dns.TypeToString[q.Qtype],
routeOriginType, routeName)
dns.HandleFailed(w, r)
return
}
// ── 9. Upstream forwarding — coalesced via singleflight ───────────────
// clientName only varies the key when the upstream URL templates on
// {client-name}; otherwise every device would defeat coalescing.
sfClientName := ""
if hasClientNameUpstream {
sfClientName = clientName
}
sfKey := buildSFKey(qNameTrimmed, q.Qtype, routeIdx, sfClientName)
didUpstream := false
v, sfErr, shared := sfGroup.Do(sfKey, func() (any, error) {
didUpstream = true
IncrUpstreamCall()
msg, addr, err := raceExchange(upstreams, r, clientName)
if err != nil || msg == nil {
return sfResult{}, err
}
// Negative upstream caching gate. cacheUpstreamNeg is a startup bool
// so this branch is a single load — zero overhead when true (default).
isNeg := msg.Rcode == dns.RcodeNameError ||
(msg.Rcode == dns.RcodeSuccess && len(msg.Answer) == 0)
if !isNeg || cacheUpstreamNeg {
CacheSet(cacheKey, msg, routeName)
}
return sfResult{msg: msg, addr: addr}, nil
})
if shared && !didUpstream {
coalescedTotal.Add(1)
}
var finalResp *dns.Msg
var upstreamUsed string
if sfErr == nil {
if res, ok := v.(sfResult); ok && res.msg != nil {
// Skip Copy() when !shared: this goroutine is the sole owner of
// res.msg. CacheSet already packed it into independent wire bytes
// so we can mutate it directly (transforms + parental cap + ID).
// When shared, multiple goroutines hold the same pointer — each
// must work on its own copy to avoid data races.
if shared {
finalResp = res.msg.Copy()
} else {
finalResp = res.msg
}
upstreamUsed = res.addr
}
}
// ── 10. Error ─────────────────────────────────────────────────────────
if finalResp == nil {
log.Printf("[DNS] [%s] %s -> %s %s | ROUTE(%s): %s | FAILED: %v",
protocol, clientID, q.Name, dns.TypeToString[q.Qtype],
routeOriginType, routeName, sfErr)
dns.HandleFailed(w, r)
return
}
// ── 11. Response transforms ───────────────────────────────────────────
finalResp = transformResponse(finalResp, q.Qtype, true)
// ── 12. Final reply ───────────────────────────────────────────────────
if parentalForcedTTL > 0 {
CapResponseTTL(finalResp, parentalForcedTTL)
}
finalResp.Id = originalID
w.WriteMsg(finalResp)
if logQueries {
status := "OK"
switch {
case shared && !didUpstream:
status = "COALESCED"
case responseContainsNullIP(finalResp):
status = "OK (NULL-IP)"
}
log.Printf("[DNS] [%s] %s -> %s %s | ROUTE(%s): %s | UPSTREAM: %s | %s",
protocol, clientID, q.Name, dns.TypeToString[q.Qtype],
routeOriginType, routeName, upstreamUsed, status)
}
}
// ---------------------------------------------------------------------------
// Key builders
// ---------------------------------------------------------------------------
// buildClientID constructs the "ip (name)" log label using a pooled Builder.
// Returns the bare IP when name is empty.
func buildClientID(ip, name string) string {
if name == "" {
return ip
}
sb := clientIDPool.Get().(*strings.Builder)
sb.Reset()
sb.WriteString(ip)
sb.WriteString(" (")
sb.WriteString(name)
sb.WriteByte(')')
s := sb.String()
clientIDPool.Put(sb)
return s
}
// buildSFKey constructs a binary singleflight key without fmt.Sprintf.
// Uses a stack-allocated [512]byte array; one string allocation at the end.
// Layout: name \x00 qtype(2B BE) routeIdx [\x00 clientName]
func buildSFKey(name string, qtype uint16, routeIdx uint8, clientName string) string {
var b [512]byte
n := copy(b[:], name)
b[n] = 0; n++
b[n] = byte(qtype >> 8); n++
b[n] = byte(qtype); n++
b[n] = routeIdx; n++
if clientName != "" {
b[n] = 0; n++
n += copy(b[n:], clientName)
}
return string(b[:n])
}
// ---------------------------------------------------------------------------
// Background revalidation
// ---------------------------------------------------------------------------
// backgroundRevalidate refreshes a stale cache entry without blocking the
// caller. A semaphore caps simultaneous goroutines at revalSemCap.
func backgroundRevalidate(key DNSCacheKey, routeName, clientName string) {
select {
case revalSem <- struct{}{}:
default:
return // semaphore full — skip this revalidation cycle
}
defer func() { <-revalSem }()
upstreams, exists := routeUpstreams[routeName]
if !exists || len(upstreams) == 0 {
upstreams = routeUpstreams["default"]
}
if len(upstreams) == 0 {
return // misconfigured route — nothing to revalidate against
}
req := msgPool.Get().(*dns.Msg)
*req = dns.Msg{}
req.SetQuestion(dns.Fqdn(key.Name), key.Qtype)
req.RecursionDesired = true
msg, _, err := raceExchange(upstreams, req, clientName)
msgPool.Put(req)
if err == nil && msg != nil {
CacheSet(key, msg, routeName)
}
}