The DNS module spoke UDP, TCP and DNS over TLS. An https:// upstream is
now an RFC 8484 POST through an http.Client the upstream keeps between
queries; the TLS handshake is done in the dialer so the server name is
the upstream's hostname while the address dialled is what bootstrap
resolved for it — the module cannot ask itself for its own upstream's
address. A direct upstream dials on a marked socket, as the other
protocols do; a proxied one dials through the xray dispatcher, so the
request leaves through the chosen outbound.
Two things the dispatcher path had wrong for tls:// upstreams: it sent
plain DNS over TCP whatever the protocol, and bootstrap replaced the
hostname by an IP without keeping it, so TLS had nothing to verify
against. The hostname is kept as ServerName on the upstream, the
dispatcher path wraps the connection in TLS for tcp-tls, and the direct
miekg client verifies the same name. The service adds https and tls
hostnames to the bootstrap list, which it skipped for every scheme
address before. CheckDnsUpstream accepts https:// URLs with a host and
still refuses quic://.
Verified on the VM with a raw UDP client against the module, names not
in its cache: https://dns.google/dns-query direct (bootstrap dns.google
→ 8.8.8.8, a v2raya_core connection to 8.8.8.8:443), https://1.1.1.1
/dns-query via proxy (the connection goes to the proxy server's :443),
tls://dns.google via proxy (rewritten to 8.8.8.8:853, TLS verified as
dns.google) and tls://1.1.1.1 direct all answer; the previous rules
restore unchanged. A unit test runs the DoH client against an httptest
TLS server.
A read of the tree for home-grown code that a dependency or the platform
covers. Each item names what replaces it.
- IPv4 CIDR membership was a binary-string trie (infra/dataStructure/trie)
fed with CIDRs rendered as bit strings; net.IPNet.Contains, which the
same file already used for IPv6, does it. The trie package is gone.
- The response replay cache was an LRU with its own linked list, indexes
and timeout strategy (infra/dataStructure/lru), of which one fixed-size
instance existed; hashicorp/golang-lru/v2, already in go.mod, is that
cache, typed. go mod tidy also dropped go-nanoid, which nothing imported.
- The HTTP client for subscription updates through the local proxy carried
a CONNECT dialer of its own (pkg/util/proxyWithHttp); http.Transport's
Proxy handles socks5:// and http:// URLs, resolves hostnames on the
SOCKS proxy and uses CONNECT for https. Verified on the VM: a
subscription update succeeds in both "pac" and "proxy" modes.
- core/dns/qtype.go listed nine type names in two switches before falling
back to miekg/dns tables that contain the same names; dns.Type.String
and dns.StringToType are the tables.
- The GUI tracked prefers-color-scheme with its own media query and
toggled a theme-dark class nothing reads any more; Vuetify's "system"
theme follows the OS itself. Verified in headless Chrome: auto follows
the OS in both directions, an explicit choice overrides it.
- The AUR packages carried .INSTALL hooks whose only content was a
coloured "Completed!" banner, duplicated in the deb/rpm after-install
scripts; pacman and apt report that themselves. The hooks are gone, the
release workflow stops copying them, and after_install/after_upgrade
keep only daemon-reload and the restart.
- The tap release job downloaded eight artifacts in eight steps;
actions/download-artifact takes a pattern with merge-multiple.
A custom latency test URL that http.NewRequest rejects made a spawned
goroutine dereference nil and exit the process; the URL is validated
before any goroutine starts and the request error is handled. A
Shadowsocks link whose plugin field has no ";" panicked the parser, and
from the automatic subscription update that goroutine was unrecovered;
the parser accepts it and each updater recovers and logs.
The DNS module took the last non-bootstrap upstream as the fallback
while the template emitted upstreams in rule order with deduplication,
so a catch-all rule anywhere but last, or one whose upstream was
deduplicated, was not the fallback. The template names the fallback in
a new default_upstream field and the module honours it.
PUT /routingA stored the rules without regenerating the running core.
It goes through ApplyCoreConfig like the other config writers, with
restore on failure. UpdateSubscription logged a failed core reload and
answered success; it returns the error. PATCH /subscription joins the
mutation turn.
Subscription fetching retried through a direct connection when the
selected proxy failed, leaking the subscription URL; it returns the
error. Subscription documents are capped at 32 MiB and downloaded
assets at 256 MiB. PUT /gfwList validates the downloaded file as a
geosite list before replacing the working one.
The login handler took its one-at-a-time semaphore before reading the
body, so a client sending headers and no body blocked every login; the
body is read first and the HTTP server has header and idle timeouts.
Share links: a VLESS or VMess link without a numeric port is rejected
at parse time instead of producing port 0; an SSR link with a password
that is not base64 is rejected instead of importing empty; the SIP003
path gets its leading slash prepended, not a trailing one appended.
The macOS system proxy quoted shell arguments with strconv.Quote,
which leaves $(...) live; values are single-quoted. The Windows system
proxy snapshot includes AutoConfigURL, which teardown deleted and never
restored. Latency test responses with a non-2xx status are closed. The
version response carries the docker flag the GUI's port hints read.
Three service packages outside the executable's dependency graph
(common/antiPollution, pkg/util/gopeed, kernel/vmessInfo), a blank
import of miekg/dns the core already imports, the --core-type flag no
code read, the PutAccount handler whose route was commented out, two GUI
API wrappers without a caller, two .SRCINFO files the release regenerates
and an unreferenced runit sample. The workflow path filters watched a
root go.mod that does not exist and the PR build skipped core/.
The module asked every upstream with DNSSEC OK and handed the upstream's
additional section back untouched, so a client got an OPT record it never
sent — carrying the module's loop token and the DO flag — and RRSIG
records it did not ask for. macOS's resolver treats such an answer as
invalid and waits out its 30-second timeout on every uncached name, which
made the tun mode's loopback resolver unusable there. Upstream queries no
longer set DO (the module validates nothing), and the response is
rewritten to the client's EDNS: no OPT when the client sent none, a fresh
OPT with the client's UDP size and DO bit when it did, and RRSIGs only for
a DO client.
On Linux the module's upstream, bootstrap and health-check sockets carry
SO_MARK 0x80, which the transparent-proxy rules exempt. Windows and macOS
have no mark: once a TUN holds the default route, those sockets would send
the module's own queries into the TUN, where the core's port-53
interception hands them straight back to the module. The module config
gains egress_interface; when set, every dialer created by
newMarkedDnsClient binds to it with IP_UNICAST_IF / IPV6_UNICAST_IF on
Windows and IP_BOUND_IF / IPV6_BOUND_IF on macOS. Unset, the dialers are
unchanged, and Linux keeps the mark.
The darwin and windows tests dial through the dialer and read the option
back; they run on those platforms. The interface lookup itself is tested
everywhere.
A rule that sends a name to a local resolver which forwards back to v2rayA
makes the two exchange the same query until one of them runs out of memory;
v2rayA/v2rayA discussion #1950 reproduces it with dnsmasq on OpenWrt. The
firewall-level self-redirect is already handled by the 0x80 mark, but nothing
saw the loop at the resolver level.
Every query this process sends upstream carries a random per-process token in
an EDNS0 local option. A query that arrives carrying that token has come back
around such a loop and is answered with SERVFAIL, with one log line per ten
seconds naming the question and how many were refused.
RuleConfig.QueryType had no string decoder while the service writes
query_type as "A"/"AAAA", so any DNS rule with a query type made the core
exit at startup; accept names and numbers. ECS was gated on
IsGlobalUnicast, which is true for RFC 1918 and ULA, so LAN clients'
private prefixes were still sent upstream; also require a non-private,
non-loopback, non-link-local address. Cache hits returned the stored
message with its original TTLs; subtract the elapsed time, floored at
min_ttl, on a copy. The listener logged bind failures inside the serve
goroutines and Start returned nil; bind synchronously so the error is
reported. DNS-over-TCP read the length prefix with a single Read; use
io.ReadFull. CacheConfig.NegativeCache was never read; negative answers
are no longer cached when it is off.
The native anytls, juicity and tuic outbounds were rebuilt with an empty
SenderConfig and dialed with their own dialers, so streamSettings.sockopt
(the 0x80 loop-protection mark) never reached their server connections
and transparent-proxy mode re-captured them. Carry the original
streamSettings into the rebuilt sender settings and dial through the
xray dialer that applies them.
RFC 7871 requires that non-globally-routable client addresses are not
sent as EDNS Client Subnet. Sending ECS with loopback/private addresses
(e.g. 127.0.0.1 from the local listeners) breaks split-horizon zones:
AliDNS returned only the CNAME without the target A record for such
queries, so Cloudflare-fronted proxy servers could never be resolved.
Review (goal verification) found that socket_test.go asserted
Dialer.Control != nil without build tags, so 'go test ./core/dns/'
fails on Windows where markedDialer() deliberately omits Control
(SO_MARK is a Linux-only option; markFd is a no-op there).
Move the Control assertions to socket_unix_test.go (//go:build !windows);
socket_test.go keeps the platform-neutral assertions (Net/UDPSize/timeouts/
Dialer non-nil). Verified: Linux go build + go test all pass, and
GOOS=windows go vet compiles the test files cleanly.
Follow-up review of 525654e found:
1. Log gating was incomplete: only the direct/route path was gated;
cache-hit/cache-miss, proxy and dispatcher per-query logs were still
unconditional log.Printf (the hottest paths under load). Gate them
behind V2RAYA_DNS_DEBUG=1 too; error logs stay visible.
2. Stopping the transparent proxy left the direct nat OUTPUT/PREROUTING
REDIRECT --to-port 52353 rules and the fwmark 0x80 exemption rules in
place (Tproxy/Redirect GetCleanCommands only clean their own chains).
Once the DNS module exits, local DNS queries hit a dead port and DNS
fails. Add cleanDnsRedirectRules() and run it on the normal stop path.
3. module.go bootstrap client inlined its own markFd + marked dialer;
reuse newMarkedDnsClient (keeping the 3s fail-fast timeout).
4. dnsLogf/dnsDebugEnabled were duplicated in socket_unix.go /
socket_windows.go; move them to a common debug.go.
5. No unit tests for newMarkedDnsClient; add tests asserting
Net/UDPSize/Timeout and a non-nil Dialer.Control.
Verified: go build ./dns/... ./kernel/v2ray/... ; go test ./dns/...
Fixes defects in the v2.4.8+ transparent-proxy DNS path that cause the
core to exhaust memory within seconds on low-RAM hosts (see discussion
#1915: '2.4.9 内存占用过高' / '有严重的内存泄漏,别用了。本地DNS完全废掉了'):
1. core/dns: upstream queries from NewUpstreamManager /
GetOrCreateUpstream / getClientForProtocol used bare &dns.Client{}
with no Dialer configured, so their sockets never carried
SO_MARK=0x80. The unmarked queries were hijacked by the module's own
transparent-proxy DNS redirect rules and looped back into :52353 —
an infinite self-query loop and memory snowball.
2. service/kernel/v2ray/transparent.go: the unconditional DNS hijack
rules (REDIRECT --to-port 52353) had no fwmark-0x80 exemption, and
being inserted with -I they sat at the head of nat OUTPUT/PREROUTING,
so marked traffic was looped back as well.
3. core/dns: per-query info logging (query/route/upstream) produced
thousands of lines/second under load, amplifying CPU/IO/memory
pressure.
Fix:
- Route every upstream client through newMarkedDnsClient, whose
net.Dialer sets SO_MARK=0x80 on all sockets. miekg/dns dials UDP
through net.Dialer too, so Dialer.Control covers UDP sockets — no
manual socket path is needed. UDPSize=4096 keeps a sane receive
buffer for queries without an EDNS0 OPT record.
- Append the DNS redirects with -A and insert the mark exemption with
-I so the exemption is matched first; also delete the exemption
rules in the residual-rule cleanup so they don't accumulate across
restarts.
- redirect mode: insert the DNS_REDIRECT jumps after the TP_PRE/TP_OUT
jumps so they actually take precedence (-I inserts at chain head),
keeping local and LAN TCP DNS flowing to the DNS module (:52353)
instead of the proxy inbound (:52345).
- Gate per-query info logs behind V2RAYA_DNS_DEBUG=1; error logs stay
always visible.
Verified: unpatched v2.4.11 core RSS 230MB->1GB in ~6s then OOM/hang;
patched build stable at ~25MB idle / ~243MB loaded, DNS and SOCKS proxy
working.
exchangeUDPWithMark used dns.DefaultMsgSize (512 bytes) as the UDP
receive buffer. The query sets EDNS0 UDP size 4096, so the upstream
may respond with up to 4096 bytes. With a 512-byte buffer, UDP
datagram data beyond 512 bytes is silently discarded (UDP datagram
property), causing truncated/corrupted DNS responses.
Fix: use dns.MaxMsgSize (65535) as the receive buffer, matching the
maximum possible UDP datagram size. This ensures large DNS responses
(common with DNSSEC or many A/AAAA records) are fully received.
## 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
syscall.SetsockoptInt takes int (Linux) vs syscall.Handle (Windows)
as its first argument. The existing code used int(fd) which fails on
Windows where fd is uintptr and syscall.Handle = uintptr.
Fix: extract a platform-specific setSocketMark(fd uintptr) helper:
- socket_unix.go (!windows) : calls SetsockoptInt(int(fd), ...)
- socket_windows.go (windows): no-op (SO_MARK is Linux-only)