Files
Markson Joe Hon 9fcbd6a5db fix(core/dns): fix DNS split routing, bootstrap loop, and response corruption
## Issue 1: DNS rule matching logic (MatchAll + OrMatcher)

BuildMatchers flattened all geosite-expanded domains into a single list,
and the old MatchAny used AND logic (all matchers must match). This
made geosite:cn rules impossible to hit (e.g. qq.com and baidu.com
can never match simultaneously).

Fix: introduce OrMatcher to group matchers from the same rule field
with OR semantics, while different field groups use AND. The thousands
of domains from geosite:cn expansion are wrapped in a single OrMatcher
so matching any one domain satisfies the rule.

## Issue 2: Bootstrap self-reference loop (SO_MARK + public DNS fallback)

Bootstrap resolution runs before the DNS listener starts, but iptables
already hijacks :53 traffic:
- bootstrap query to system DNS(:53) → iptables redirects to 127.2.0.17:53
- DNS module not yet listening → connection refused → bootstrap fails
- Domain upstreams (e.g. dns.google) remain unresolved → relies on proxy
- Proxy DNS may re-enter DNS module → loop or REFUSED

Fix:
1. Add SO_MARK=0x80 to bootstrap DNS client to bypass iptables redirect
2. collectBootstrapDns() with 3-tier priority (config > system > hardcoded)
3. Hardcoded fallback includes Alibaba/Tencent/Google/Cloudflare: 13 servers
4. isOwnAddress() filters self-referencing addresses (127.0.0.1:53 etc.)

## Issue 3: handlePacket mutates cached response in-place

m = resp.RawMsg; m.SetReply(msg) directly modifies the *dns.Msg shared
with the cache, corrupting subsequent cache hits. SetReply also forces
Rcode=RcodeSuccess, overwriting NXDOMAIN etc. from upstream.

Fix: Pack/Unpack deep copy before modification; preserve original Rcode.

## Issue 4: Double OPT record causes FORMERR

Three exchange functions called AddECSSubnet BEFORE SetEdns0.
miekg/dns v1.1.72's SetEdns0 always appends a new OPT record without
checking for existing ones, producing a malformed query with two OPT
records.

Fix: call SetEdns0 before AddECSSubnet; use UDP size 4096 in
AddECSSubnet instead of 512 to preserve the size set by SetEdns0.

## Issue 5: localhost upstream skipped in template (template_dns.go)

localhost upstream was continue-skipped during config generation,
making the geosite:private rule reference a non-existent upstream.

Fix: map localhost to 127.0.0.1, keep it as a valid upstream.

## Incidental fixes

- handler.go: remove duplicate :53 in log format (dns.google:53:53)
- response.go: use 4096 instead of dns.DefaultMsgSize(512) for ECS
2026-07-22 14:01:39 +08:00
..