Repository navigation
Expand file tree
/
Copy pathprocess_cache.go
More file actions
233 lines (201 loc) · 6.99 KB
/
Copy pathprocess_cache.go
File metadata and controls
233 lines (201 loc) · 6.99 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
/*
File: process_cache.go
Version: 1.34.0
Last Updated: 13-Nov-2026 14:10 CET
Description:
Background cache revalidation and synthetic message builders.
Extracted from process.go to separate background worker logic and
message synthesis from the direct execution pipeline.
Changes:
1.34.0 - [SECURITY/FIX] Rejected `consensus-log(...)` responses alongside
`consensus(...)` in `backgroundRevalidate` so unverified consensus-failed
responses in `block_action: "LOG"` mode never overwrite valid cached
records during background refreshes.
1.33.0 - [SECURITY/FIX] Rejected synthetic consensus failure responses
(`strings.HasPrefix(addr, "consensus(")`) in `backgroundRevalidate`
so background cache refreshes never overwrite valid cached records
with synthetic consensus block payloads.
1.32.0 - [CRITICAL/FIX] Marked `backgroundRevalidate` context with
`WithBypassUpstreamThrottle` (`throttle.go` 2.7.0) since background
revalidation is already bounded by the 32-slot `revalSem` semaphore
and must not contend for client-facing `AcquireUpstream` slots.
1.31.0 - [FIX] Replaced raw `dns.TypeToString[key.Qtype]` lookup with `qtypeName(key.Qtype)`
in `backgroundRevalidate` log output for consistency on unknown QTYPEs.
1.30.0 - [SECURITY/FIX] Marked synthesized `EDNS0_SUBNET` in `backgroundRevalidate`
with the internal `SourceScope: 255` marker (sanitized to `0` in
`prepareForwardQuery`).
1.29.0 - [SECURITY/FIX] Updated `buildSynthCacheMsg` to accept `r *dns.Msg` and
preserve `r.RecursionDesired` (alongside `Authoritative = true`) on all
synthesized cache messages.
1.28.0 - [SECURITY/FIX] Preserved `key.Qclass` in `backgroundRevalidate` instead
of hardcoding `dns.ClassINET` via `SetQuestion`.
1.27.0 - [SECURITY/FIX] Preserved `key.RecursionDesired` in `backgroundRevalidate`.
1.26.0 - [SECURITY/FIX] Addressed an undeclared memory leak within the error
handling branches natively.
1.25.0 - [FEAT/FIX] Injected `rotateAnswersInPlace` evaluation natively into
the `CacheGetExpired` infinite-stale fallback generator.
*/
package main
import (
"context"
"fmt"
"log"
"net/netip"
"strings"
"time"
"github.com/miekg/dns"
)
// ---------------------------------------------------------------------------
// Synthetic Cache Response Builder
// ---------------------------------------------------------------------------
// buildSynthCacheMsg generates a fully compliant, self-contained DNS response
// corresponding to a local policy action (e.g., NULL-IP Blocks, NXDOMAIN),
// preserving the client's RecursionDesired flag.
func buildSynthCacheMsg(r *dns.Msg, q dns.Question, action int) *dns.Msg {
rd := true
if r != nil {
rd = r.RecursionDesired
}
if action == PolicyActionBlock {
var dummy dns.Msg
dummy.RecursionDesired = rd
dummy.Question = []dns.Question{q}
return generateBlockMsg(&dummy, syntheticTTL)
}
msg := msgPool.Get().(*dns.Msg)
*msg = dns.Msg{}
msg.Response = true
msg.Authoritative = true
msg.RecursionDesired = rd
msg.RecursionAvailable = true
msg.Question = []dns.Question{q}
if action >= 0 {
msg.Rcode = action
if action == dns.RcodeNameError || action == dns.RcodeSuccess {
SetNegativeSOA(msg, q.Name, syntheticTTL)
}
}
return msg
}
// ---------------------------------------------------------------------------
// Background Revalidation
// ---------------------------------------------------------------------------
func TriggerBackgroundRevalidate(key DNSCacheKey, routeName, clientName string, previousHits uint32, revertGate func()) {
select {
case revalSem <- struct{}{}:
go func() {
defer func() { <-revalSem }()
backgroundRevalidate(key, routeName, clientName, previousHits, revertGate)
}()
default:
if revertGate != nil {
revertGate()
}
}
}
func backgroundRevalidate(key DNSCacheKey, routeName, clientName string, previousHits uint32, revertGate func()) {
success := false
defer func() {
if r := recover(); r != nil {
log.Printf("[PANIC] Recovered in backgroundRevalidate: %v", r)
}
if !success && revertGate != nil {
revertGate()
}
}()
group := effectiveUpstreamGroup(routeName)
if group == nil {
return
}
req := msgPool.Get().(*dns.Msg)
*req = dns.Msg{}
req.SetQuestion(dns.Fqdn(key.Name), key.Qtype)
if key.Qclass != 0 {
req.Question[0].Qclass = key.Qclass
}
req.RecursionDesired = key.RecursionDesired
req.CheckingDisabled = key.CdBit
opt := &dns.OPT{
Hdr: dns.RR_Header{Name: ".", Rrtype: dns.TypeOPT, Class: dns.ClassINET},
}
opt.SetUDPSize(4096)
if key.DoBit {
opt.SetDo()
}
var bgAddr netip.Addr
if key.ECS != "" && key.ECS != "passed-ecs" {
if prefix, err := netip.ParsePrefix(key.ECS); err == nil {
bgAddr = prefix.Addr()
if group.ECSAction == "pass" {
var family uint16 = 1
if bgAddr.Is6() {
family = 2
}
ecsOpt := &dns.EDNS0_SUBNET{
Code: dns.EDNS0SUBNET,
Family: family,
SourceNetmask: uint8(prefix.Bits()),
SourceScope: 255, // Internal pre-validated marker (reset to 0 in prepareForwardQuery)
Address: bgAddr.AsSlice(),
}
opt.Option = append(opt.Option, ecsOpt)
}
} else if addr, err := netip.ParseAddr(key.ECS); err == nil {
bgAddr = addr.Unmap()
if group.ECSAction == "pass" {
var family uint16 = 1
var bits uint8 = 32
if bgAddr.Is6() {
family = 2
bits = 128
}
opt.Option = append(opt.Option, &dns.EDNS0_SUBNET{
Code: dns.EDNS0SUBNET,
Family: family,
SourceNetmask: bits,
SourceScope: 255,
Address: bgAddr.AsSlice(),
})
}
}
}
req.Extra = append(req.Extra, opt)
bgTimeout := 10 * time.Second
if upstreamTimeout > 0 && upstreamTimeout < bgTimeout {
bgTimeout = upstreamTimeout
}
ctx, cancel := context.WithTimeout(WithBypassUpstreamThrottle(context.Background()), bgTimeout)
defer cancel()
clientID := "background-worker"
if clientName != "" {
clientID = "background-worker (" + clientName + ")"
}
msg, addr, err := group.Exchange(ctx, req, clientID, clientName, bgAddr)
isConsensusFail := strings.HasPrefix(addr, "consensus(") || strings.HasPrefix(addr, "consensus-log(")
if logCaching {
var status string
if err != nil {
status = fmt.Sprintf("FAILED: %v", err)
} else if isConsensusFail {
status = "CONSENSUS FAILED"
} else if msg != nil {
status = RcodeStr(msg.Rcode)
}
log.Printf("[CACHE] [BG-REVAL] %s -> %s %s | ROUTE: %s | UPSTREAM: %s | HITS: %d | %s",
clientID, key.Name, qtypeName(key.Qtype), routeName, cleanUpstreamHost(addr), previousHits, status)
}
msgPool.Put(req)
if err != nil || msg == nil || isConsensusFail {
return
}
if cfg.Cache.AnswerSort == "ip-sort" {
applyAnswerSort(msg, "ip-sort")
}
isNeg := msg.Rcode == dns.RcodeNameError || (msg.Rcode == dns.RcodeSuccess && len(msg.Answer) == 0)
if !isNeg || cacheUpstreamNeg {
CacheSet(key, msg, routeName)
success = true
} else {
success = false
}
}