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.
TestDown passed a directory where Down expects the destination file path and
then read the result from the working directory, so it could not pass; TestTemp
was a leftover scratch benchmark that wrote a 512 MiB file to a hard-coded
Windows path and called log.Fatal, which killed the whole test binary. Both
tests also fetch a file from GitHub and compare it with a fixed checksum.
Remove TestTemp, fix the destination, and run the two network tests only when
V2RAYA_NETWORK_TESTS=1. go test ./... is green now.
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.
A client that predates the kind field sends only the URL, so an http(s) link
had to be guessed. Guessing "subscription" is right for every address a
provider hands out, but it took away the bare proxy link 3fd0e882 had added:
credentials, host, port and nothing else cannot be a subscription address, so
that one shape goes back to the server importer.
Also let the config loader ignore every -test.* flag instead of only -test.v,
so the packages that reach it can run their tests at all.
Three gaps the settings rollback left open:
- adding or deleting a custom inbound stored the new list and then reloaded the
core; a core that refused the list stayed stopped with the rejected inbound
stored, so every later start failed too;
- a settings save that flipped ip forwarding left the kernel flag on the new
value after the setting itself was rolled back, so the stored setting and the
host disagreed;
- the rollback reported "the previous ones are back" even when restoring the
setting or restarting the core had failed as well.
The session secret now retries persistence instead of accepting a failed store
for the life of the process, and an unreadable secret row is no longer
overwritten with a fresh one, which would have signed out every session.
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 signing secret was the hash of the subscription addresses, or of the
server hostnames when there was no subscription, so importing, editing or
deleting a server changed the secret and signed every session out mid-use.
Generate 32 random bytes on first use and keep them in the database.
UpdateSetting stored the new setting before asking the core to reload it. When
the core refused the new config, the controller stopped the core and left the
rejected setting in the database, so the proxy was down and the next save
reported success while nothing was running.
Snapshot the setting before storing it, and on a reload failure put it back and
restart the core with it. The response now carries INVALID_CONFIG and the
reason the core gave.
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.
The entry page names hashed assets that disappear on every upgrade. It
was served with "public, must-revalidate" and no max-age, which browsers
may treat as heuristically fresh, so a cached copy loaded a bundle that no
longer existed and the GUI came up blank until a hard refresh. no-cache
forces revalidation; the ETag keeps it a 304.
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.
UpdateSubscription snapshotted the whole subscription list before the
network fetch and wrote the stale struct back by index, reverting edits
made during the fetch; re-read the subscription afterwards and replace
only Servers, Status and Info. SelectServersFromSubscription disconnected
with clearOutbound=true per node, wiping every connection of the proxy
group and restarting the core once per node; it now removes only this
subscription's nodes in one replacement. The HTTP latency test bound its
per-node SOCKS inbounds on 0.0.0.0 without auth; bind loopback unless
PortSharing is on, and restore the previous core when the test core fails
to start. SetPorts skipped the API port and never range-checked; check all
six ports. Connect and ReplaceOutboundConnections treated an existing but
empty previous list as something to restore, which OverwriteConnects
turns into a no-op, so a failed selection stayed persisted; clear the
group in that case.
PRAGMA busy_timeout and foreign_keys ran once through the database/sql
pool, so only one pooled connection had them and concurrent writers failed
with SQLITE_BUSY; pass them in the DSN for both the modernc and the CGO
driver. BucketClear built its LIKE prefix from the outbound name without
escaping % and _, so clearing one outbound could wipe another's rows.
ListAppend read MAX(sort) in a separate statement, so two concurrent
appends got the same sort value; compute it inside the INSERT.
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.
Adding or deleting a custom inbound only wrote the database: the running
core kept its old inbounds until the next unrelated restart, and a port
that collided with the configured socks5/http/pac/vmess/api ports was
accepted and broke the next core start. Reject out-of-range and colliding
ports with a message naming the port, and regenerate the config when the
core is running.
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.
PutSetting decoded the request into a zero Setting and persisted the whole
struct, so the fields the settings dialog never sends (dnsCacheEnabled,
dnsPrefetch, dnsNegativeCache, the per-protocol backends) were saved as
false or empty on the first Save and the DNS cache silently switched off
with no control in the GUI to switch it back. Decode over the stored
setting so absent fields keep their value.
DeleteWhich walked cssRaw.Get() while removing entries from cssAfter,
which was the same slice header over the same backing array. After a
non-tail removal the next touch saw the shifted list with a stale
duplicate at the end: the same Which pointer was decremented twice or
Disconnect ran on it, and cssAfter[:i] with the old length panicked with
slice bounds out of range. Work on a copy and iterate that copy.
ListGet and ListGetAll rebuilt each subscription with fmt.Sprintf and no
escaping. A remark, status or provider info containing a double quote or
backslash produced invalid JSON, Bytes2SubscriptionRaw failed, and the
subscription disappeared from GetSubscriptions while GetLenSubscriptions
still counted it, shifting the IDs of every later subscription and the
Sub index of stored connections. Build the object with the JSON encoder;
the server rows are already JSON and are embedded as raw messages.
Import accepted which.TYPE == subscriptionServer for a modification but
then called configure.SetServer(ind), which replaces the standalone
server at that index; the subscription node itself stayed unchanged and
an unrelated server was overwritten. Write the node back through
SetSubscription with bounds checks on sub and index.
- time.Ticker.Reset panics on a non-positive duration; a stored auto-update
interval of 0 crashed every start (pre_update.go) and every settings
save. Route both tickers through configure.IntervalHours, which falls
back to one hour.
- The auto-updater indexes a startup snapshot; a subscription deleted
while it runs panicked out of range in a goroutine and took the daemon
down. UpdateSubscription now refuses an index that no longer exists.
- ResolveSubscriptionWithClient applied its 30 s timeout floor to a copy
it never used, accepted HTTP error pages as an empty node list, and
returned zero nodes without error, so UpdateSubscription replaced the
stored list with nothing on a provider 403/5xx. Use the copy, reject
status >= 400 and empty results.
- PutOutbound wrote an error response and then fell through to the
success response, producing two JSON bodies.
- TestHttpLatency passed nil entries (servers it could not locate) to
addHosts, which dereferenced them; skip them.
- ReqCache read the per-request mutex map after releasing the lock that
guards writes to it (a fatal concurrent map access under load).
- The websocket writer ran one goroutine per message box on a single
gorilla connection, which forbids concurrent writes; serialize them.
Connect stored the requested Which with AddConnect before generating the
core config. A request whose body did not bind to a valid selection (empty
_type, out-of-range id) was persisted anyway; UpdateV2RayConfig then
failed with "LocateServerRaw: invalid TYPE", and because the deferred
restore ran only while the core was running, and only when the group had
a previous list, the bad entry stayed in the database and every later
connect and core start failed with the same error.
Locate the server first and refuse anything that cannot be found, and on
failure restore the previous list (or clear the group when there was
none) regardless of whether the core runs.
Import guessed from the URL scheme. Commit 3fd0e882 added http and https
to the server prefixes so that http proxy nodes were not stored as
subscriptions, and from then on every http(s) subscription address was
parsed as a proxy node and failed with "ResolveURL failed: invalid
parameters".
POST /api/import now takes "kind": "server" or "subscription". Import is
split into ImportServer and ImportSubscription; the old scheme-guessing
Import remains for requests without kind, with http and https back on
the subscription side as before 3fd0e882. The v4 migration calls the
explicit functions since it knows which list each address came from.
The GUI side (a server link / subscription address toggle that sends
kind) is in the gui branch.
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.
Add 'http' and 'https' to supported prefixes in Import() so HTTP/HTTPS links are recognized as server links rather than subscriptions. Prevents single http://... nodes from being stored as subscriptions.
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.