Three endpoints answered FAIL for something the caller asked for and got:
- an up-to-date GFWList came back as "could not update GFWList: latest version
is …. GFWList is up to date", because the check returned an error;
- deleting the GFWList when it was already gone returned the raw
"remove …: no such file or directory";
- the update check said "failed to get latest version from Package file: 1".
The up-to-date case is now a sentinel error the controller turns into a
success carrying alreadyUpToDate, deleting what is already gone succeeds, and
the two package-index messages say what was missing. "which can not be nil"
also became a sentence about the request.
A DNS or connection failure produced "Could not download the asset from
api.github.com (HTTP )" in the GUI, because the localized message always
rendered an HTTP status and there was none. Unreachable hosts now use their own
code with the innermost reason, so the user sees the DNS or connection error
instead of an empty pair of brackets.
When the OOM killer takes v2rayA the core survives, is adopted by init and
keeps 20170/20171, so every later start failed with "port is already in use"
until someone killed it by hand (second half of v2rayA/v2rayA discussion
#1932). A process holding one of our ports that runs our core binary and whose
parent is init is ours to clean up.
The version mismatch also said only which two numbers differ, so users who had
installed xray-core concluded v2rayA was broken (#1930, #1903, #1891); it now
says which binary v2rayA needs.
A custom inbound port was open to anyone who could reach it, and older v2rayA
versions did offer authenticated inbounds, so users who relied on them had no
replacement (v2rayA/v2rayA discussions #1894, #1907).
CustomInbound carries optional credentials, which become the inbound's account
list. Half a credential pair is rejected: it would silently leave the port open.
The hijack wrote the file directly, so on any systemd-resolved, resolvconf or
openresolv system it overwrote the resolver's own file through the symlink and
destroyed the link; stopping the proxy then wrote a second hijacked file with
public resolvers rather than restoring anything. The machine was left bypassing
its resolver with no way back short of reinstalling, which is what v2rayA/v2rayA
discussion #1958 and defect B of #1920 describe.
Save the original first — the target when it is a symlink, the content
otherwise — replace the link instead of writing through it, and put the
original back on stop. Closing the hijacker now also waits for a tick that is
already writing, which used to put the hijacked file back after the restore.
Shutdown asks for the teardown twice: pre_run calls CheckAndStopTransparentProxy
and then Stop calls it again through beforeStop. Both ran the user's pre-stop
and post-stop transparent hooks, so a hook that is not idempotent ran twice on
every exit.
Record whether this process installed the rules and make the teardown a no-op
once they are gone. Rules left behind by an earlier process are still removed
by cleanupResidualTransparentProxyRules when the next ones are written.
v2raya_core is started with XRAY_LOCATION_ASSET and looks nowhere else, while
v2rayA only created links in that directory as a side effect of looking a file
up for itself. On a host whose XDG runtime directory is cleared between login
sessions, the core then started with an empty asset directory and failed with
"failed to open geosite.dat" although the files were installed in
/usr/share/v2raya all along; the failure reads like a broken config.
Link the four dat files the core loads by name into that directory before
starting it, taking them from the XDG data directories or the two system
directories a distribution installs into.
The shadowsocks userinfo, the vmess body and the SSR link trimmed a single "="
from their base64, so a value that needed two padding characters was exported
with one left over. A strict decoder rejects that, and a lenient one decodes
the stray character as data: editing such a shadowsocks node in the GUI turned
its password into "test\r..." because the escaped "=" reached the decoder.
Three regressions from the previous transparent-proxy commit:
- the redirect ingress rules lost the "*" to "+" translation, so an excluded
interface pattern such as docker* stopped matching and Docker traffic was
redirected; the egress rules and both tproxy directions still translated it;
- the whitelist now parses its entries, and the GUI submits the textarea lines
as typed, so a pasted CIDR with surrounding whitespace aborted the whole
setup where the shell used to swallow it;
- the DNS readiness probe resolves a name, so a dead or slow upstream failed it
even with the listener up, and the core could no longer start at all. The
probe is now advisory: it still waits when DNS is healthy, but a failure is
logged instead of aborting the start.
Defaulting the port made an absent port legal, and with it a link that carries
no host at all: `socks5://` was accepted and stored as a node with an empty
server, where the previous port conversion had rejected it.
A Reality VLESS proxy carries reality-opts.spider-x and a TLS VMess proxy
carries client-fingerprint; both were dropped by the mapping, so the imported
node handshook with an empty spider path and the default fingerprint and the
provider's server could refuse it.
The GUI shows backend error text as is, so errors were never localized.
common.Coded wraps an error with a stable code and scalar parameters;
ResponseError adds "errorCode" and "params" next to the unchanged English
"message" when the chain carries one. Thirty-two user-facing errors are
coded (no server selected, core start failure, port occupied, malformed
link with protocol and detail, subscription fetch failure with host,
server/subscription not found with ids, bad request with the field,
credentials, session, admin, request in progress, GFW list missing,
invalid config, asset download, transparent setup, mux range, custom
inbound fields). logError now keeps the error chain instead of
flattening it. Messages, status codes and control flow are unchanged; the
two strings the GUI matches on stay as they are.
tools_test.go becomes an external test package so the common tests
compile again; its FillEmpty equality assertion, which never ran before,
is skipped with the reason.
Errors that reach the GUI were written for the log: "ResolveURL failed:
invalid parameters", "httpGetUsingSpecificClient: response is nil",
"LocateServerRaw: invalid TYPE", "bad request", "illegal base64 data at
input byte 18". Reword the messages that can reach a user so each names
the input that was rejected (link scheme, missing password, port, server
id, request field), states the expected form for malformed input, drops
Go function names, keeps the %w chain so errors.Is/As still work, and
never echoes passwords, tokens or full share links (hosts only).
Messages the GUI string-matches ("invalid config", "the last request is
being processed") are unchanged.
Interface names and whitelist IPs from the settings were interpolated
into iptables/nft command text run through sh -c; they are now validated
(interface names may still use the "*" wildcard, translated to "+" for
iptables) and rejected with a message naming the value. nftTproxy emitted
"elements = { }" for an empty whitelist, an nft syntax error that failed
the whole setup. waitForDnsPort dialed UDP, which succeeds without a
listener; it now sends a DNS query and waits for an answer. The resolv
hijacker's ticker goroutine never exited because Stop does not close the
channel. A failing transparent pre-stop hook skipped rule deletion and
left the tproxy chains and resolv hijack behind. The DNS REDIRECT rules
ran through raw ExecCommands instead of the iptables backend setter, so
nft-only hosts silently skipped them. On darwin/BSD sysctl was invoked
with the whole command line as the program name.
ParseSSURL read the userinfo re-percent-escaped through u.User.String()
and decoded only the URL-safe alphabet, so SIP002 links with a standard
alphabet failed and keys containing "/" were stored encoded; accept both
alphabets, padded or not, and the raw method:password form. ParseSocksURL
ran Atoi on the port before its 1080 default, rejecting socks5://host.
ParseVlessURL stored the id re-escaped, so non-UUID ids with spaces or
non-ASCII were hashed encoded and double-encoded on export. The VLESS
exporter dropped idleTimeout, healthCheckTimeout, permitWithoutStream and
initialWindowsSize for gRPC although the parser reads them. Tests cover
each case.
ParseTuicURL read the certificate pin and name verification only as
pinnedPeerCertSha256/verifyPeerCertByName while the GUI form and other
clients emit pinned_peer_cert_sha256/verify_peer_cert_by_name, so a pin
typed into the form was dropped. ParseTrojanURL read host only for the
trojan-go scheme although ConfigurationMC uses it as the WebSocket Host
header for plain trojan as well.
ImportSubscription redeclared err with := inside the block, so a failure
of AppendSubscriptions was assigned to the shadow and the function
returned nil.
ParseHttpURL ran strconv.Atoi on the port before the per-scheme default,
so a link without a port failed with "invalid parameters" and the
Port == 0 branches were unreachable. Parse the port only when present.
A proxy link never carries a path or query; one that does is a
subscription URL pasted into the server box. Reject it with a message
that says so instead of the bare parameter error.
A subscription that serves a Clash config went through the line parser,
which picked up a stray URL from the rules and produced a "successful"
subscription holding one bogus http node. Detect a YAML body with a
proxies list and map each proxy onto the share link v2rayA already parses
for its type: anytls, trojan, vless, vmess, ss (obfs and v2ray-plugin),
ssr, hysteria2, tuic, socks5 and http. Unsupported types are counted in
the log; a config with no usable proxy fails the import instead of
storing an empty subscription.
u.User.String() returns URL-encoded userinfo, causing the password to be
incorrectly stored when it contains special characters like '/'. For
example, a password of '/' would be stored as '%2F'.
Switch to u.User.Password() which returns the decoded password directly,
consistent with how juicity, hysteria2, http, and socks5 handle it.
Proxy server domains previously fell through to the default (proxy)
upstream: the upstream query is dispatched through the proxy outbound,
but dialing the proxy outbound itself requires resolving the server
domain, creating a circular dependency that left the proxy channel
unusable ("dns read length via dispatcher: io: read/write on closed
pipe").
Generate a highest-priority DNS module rule matching all node server
hostnames against a dedicated direct upstream (system DNS when
available). The upstream is prepended, not appended, because the module
treats the last non-bootstrap upstream as the default.
iptables requires -p tcp or -p udp when using the REDIRECT target with
--to-port. The generated rule lacked the protocol match, so on legacy
iptables the command failed with "Need TCP, UDP, SCTP or DCCP with port
specification", aborting transparent proxy startup entirely.
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.
Locally originated DNS queries are marked 0x40 by DNS_MARK in mangle OUTPUT, then nat OUTPUT REDIRECT rewrites their destination port from 53 to 52353. When the packet re-enters PREROUTING via loopback, the dport-53 TPROXY rule no longer matches, so the generic mark-0x40 rule diverts it to the transparent proxy port 52345 where it is dropped. All local UDP DNS times out and transparent proxy appears completely broken (TCP DNS survives because the proxied connection still reaches 52353).
Add TP_PRE RETURN rules for dport 52353 ahead of the TPROXY rules in the legacy IPv4, legacy IPv6, and nftables variants so already-redirected DNS traffic is delivered to the DNS module untouched.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
## 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
- Fix nftTproxy.GetCleanCommands using wrong table name ('ip' instead of
'inet') when IPv6 is disabled, causing nftables table to persist after
teardown
- Fix legacyRedirect.RemoveIPWhitelist not handling IPv6 CIDRs (always
used iptables even for IPv6 addresses, causing silent delete failure)
- Suppress errors in ip rule/route del cleanup commands with
2>/dev/null || true (applies to both legacy and nft TProxy modes)
- Normalize mixed tab/space indentation in nftRedirect's tp_rule chain
for consistency
k.GetIntegerValue() returns uint64 on Windows, but proxyEnable was
declared as uint32. Add explicit uint32() conversion to fix the
cross-compilation error:
cannot use k.GetIntegerValue("ProxyEnable") (value of type uint64)
as uint32 value in assignment
Two fixes for the redirect/tproxy interface exclusion feature:
1. Add missing -o/oifname rules for the OUTPUT path
- The TP_RULE chain is jumped from both PREROUTING (tp_pre) and
OUTPUT (tp_out). The existing -i/iifname rules only match the
PREROUTING path correctly (packets arriving on a given interface).
- For the OUTPUT path (locally-originated traffic), the input
interface is always 'lo', so -i never matches the excluded
interface. Add corresponding -o/oifname rules so that locally-
originated traffic going out through an excluded interface is
also bypassed (RETURN before the final REDIRECT/TPROXY action).
- Applies to both redirect and tproxy modes, legacy iptables and
nftables implementations, for both IPv4 and IPv6.
2. Rename nftables set 'interface'/'interface6' to 'local_ips'/'local_ips6'
- These sets store IPv4/IPv6 addresses of local interfaces,
dynamically maintained by the LocalIPWatcher to prevent proxy
loops (traffic destined to local IPs returns early).
- The old name 'interface' was misleading: it suggested it stores
interface names, but the type is ipv4_addr/ipv6_addr.
- The rename affects nftRedirect and nftTproxy, including the
set definitions, chain references (ip daddr @local_ips), and
AddIPWhitelist/RemoveIPWhitelist nft command strings.
core: fix geosite.dat parsing in DNS resolver
- Replace broken GeoSiteList unmarshal with correct varint-length-delimited
stream parser matching xray-core's format
- Add result caching to avoid re-reading the file per tag expansion
service: persist kernel exit status for proper state restoration
- Add LastKernelExitStatus (running/stopped/crashed) to DB
- Set 'running' on graceful shutdown while kernel is active so it
is automatically restored on next startup
- Set 'stopped' when user explicitly stops the kernel via API
- Set 'crashed' when the kernel exits unexpectedly
- Check saved status at startup and log appropriate messages
- Expose lastKernelExit field via GET /api/version for the frontend