1019 Commits
Author SHA1 Message Date
Markson Hon 62114510d5 Merge pull request #1961 from Zakkaus/clash-subscription
feat(subscription): import Clash/mihomo YAML subscriptions
2026-09-18 07:20:01 +08:00
Zakk 5f51d588df refactor(connect): drop the dead v2fly-only branch
checkSupport stopped returning that error when the load-balancing restriction
was removed, so the branch that cleared the connections could not run.
2026-09-18 06:42:00 +10:00
Zakk bb1f79bb87 fix(api): stop reporting results as failures
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.
2026-09-18 06:38:52 +10:00
Zakk dc8520a2ec fix(asset): say why a download failed when there was no reply at all
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.
2026-09-18 06:14:55 +10:00
Zakk fac66e45c7 style(router): drop a stray blank line 2026-09-18 06:03:53 +10:00
Zakk d56c89ef4d fix(core): kill an orphaned core that still holds the ports, name the right binary
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.
2026-09-18 05:57:08 +10:00
Zakk 86e01d6176 feat(inbound): let a custom inbound require a username and password
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.
2026-09-18 05:57:08 +10:00
Zakk bd0f389854 fix(dns): restore /etc/resolv.conf instead of leaving a hijacked one
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.
2026-09-18 05:57:08 +10:00
Zakk e8a57cb629 test(gopeed): stop the package's tests from failing everywhere
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.
2026-09-18 05:34:00 +10:00
Zakk 59a23f9c87 fix(transparent): tear the rules down once per shutdown
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.
2026-09-18 05:34:00 +10:00
Zakk fc6a8ae71c fix(core): link the dat files into the directory the core is given
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.
2026-09-18 05:34:00 +10:00
Zakk a46a33475b fix(serverObj): export share links with unpadded base64
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.
2026-09-18 05:22:30 +10:00
Zakk 1ea77f236a fix(import): keep bare http proxy links importable without a kind field
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.
2026-09-18 05:11:17 +10:00
Zakk 280710a319 fix(service): roll back custom inbounds, ip forwarding and report what was restored
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.
2026-09-18 05:09:36 +10:00
Zakk 6e09c172db fix(transparent): restore the redirect ingress wildcard, trim whitelist IPs, keep DNS readiness advisory
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.
2026-09-18 05:07:03 +10:00
Zakk fcfc7c7864 fix(serverObj): reject an http or socks link with no server address
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.
2026-09-18 05:05:34 +10:00
Zakk b48dc5efca fix(clash): keep the Reality spider path and the uTLS fingerprint
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.
2026-09-18 05:03:59 +10:00
Zakk fea9effeb4 fix(jwt): persist a random session secret
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.
2026-09-18 04:54:20 +10:00
Zakk 0005649661 fix(setting): keep the working setting and the core when a save is rejected
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.
2026-09-18 04:54:19 +10:00
Zakk aaeeb9307b feat(api): attach a machine-readable errorCode and params to FAIL responses
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.
2026-09-18 03:52:59 +10:00
Zakk a935c35304 fix(router): serve index.html with Cache-Control: no-cache
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.
2026-09-18 03:06:43 +10:00
Zakk ac79c92d6c fix(service): make API error messages say what was rejected and why
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.
2026-09-18 02:53:32 +10:00
Zakk a4c0a5a37c fix(transparent): validate rule inputs, real DNS readiness probe, rule cleanup
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.
2026-09-18 02:53:32 +10:00
Zakk 4ec09ea381 fix(service): subscription update, auto-select, latency test and port checks
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.
2026-09-18 02:53:32 +10:00
Zakk ba9d464c90 fix(db): apply pragmas per connection, escape LIKE, compute sort in the insert
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.
2026-09-18 02:53:32 +10:00
Zakk c95e20696a fix(serverObj): decode userinfo once and keep gRPC options in VLESS links
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.
2026-09-18 02:53:32 +10:00
Zakk ea21c45bae fix(controller): validate custom inbound ports and reload the core after changes
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.
2026-09-18 02:53:31 +10:00
Zakk fc9907a6bf fix(serverObj): read the parameters the GUI emits for tuic and trojan links
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.
2026-09-18 02:53:31 +10:00
Zakk 5991e557fd fix(setting): keep stored values for fields the client omits
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.
2026-09-18 02:53:31 +10:00
Zakk a2dca405c0 fix(touch): copy the connected list before editing it during deletion
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.
2026-09-18 02:53:31 +10:00
Zakk c81c5a19e1 fix(db): marshal subscription rows instead of formatting JSON by hand
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.
2026-09-18 02:53:31 +10:00
Zakk 1d219d5794 fix(import): edit a subscription node inside its subscription
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.
2026-09-18 02:53:31 +10:00
Zakk 262c56009e fix(service): guard crashes and silent data loss found in the sweep
- 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.
2026-09-18 02:53:31 +10:00
Zakk 06b8525ba9 chore: drop the debug println from main
It wrote to stderr before logging was set up, outside the log package and
its file/format options.
2026-09-18 02:53:31 +10:00
Zakk c5c169682e fix(connect): validate the selection before storing it and roll back on failure
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.
2026-09-18 02:53:31 +10:00
Zakk 9bb5ffbaef feat(import): let the client say whether it imports a server or a subscription
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.
2026-09-18 02:53:30 +10:00
Zakk b98b1b00e4 fix(serverObj): default the port of http proxy links and reject paths
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.
2026-09-18 02:53:30 +10:00
Zakk cc795ace2e feat(subscription): import Clash/mihomo YAML subscriptions
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.
2026-09-18 01:24:03 +10:00
Markson GuGa Beyond 9b0465e57b fix: use u.User.Password() instead of u.User.String() in TUIC URL parsing
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.
2026-09-16 18:25:39 +08:00
Markson Pigeonzilla Plus 3fd0e88222 fix(import): treat http(s) links as server links instead of subscriptions
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.
2026-09-12 17:34:06 +08:00
xuweizhi 8e943af4cb fix(dns): resolve proxy server domains via a direct upstream
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.
2026-08-26 19:39:22 +08:00
xuweizhi 22856c189a fix(iptables): add protocol to DNS_REDIRECT redirect rules
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.
2026-08-26 19:39:17 +08:00
xuweizhi ea96763911 fix(db): use subscription id instead of index+1 to fetch servers in ListGet 2026-08-19 20:25:31 +08:00
Markson Hon 6c27cc2c1d Merge pull request #1933 from xAlokyx/agent/reduce-geoip-parser-memory
fix: reduce GeoIP parser memory usage
2026-08-18 21:34:52 +08:00
Markson Hon 15b45924b8 Merge pull request #1934 from zhangthree78/fix/dns-loop-memory-blowup
fix: prevent DNS redirect loop causing unbounded memory growth and DNS failure on proxy stop
2026-08-18 21:21:33 +08:00
zhangthree78 734792cfc2 fix: complete per-query log gating, clean residual DNS rules on stop, dedupe marked client
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/...
2026-08-17 00:49:48 +08:00
zhangthree78 525654ec9b fix: prevent DNS redirect loop causing unbounded memory growth
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.
2026-08-16 23:59:43 +08:00
ALOKY bea993880c test incremental GeoIP parsing
Cover early exit, fake-IP filtering, IPv6 output, and malformed data.

Signed-off-by: ALOKY <ajm1055@uomustansiriyah.edu.iq>
2026-08-16 15:35:44 +03:00
ALOKY 43b6e55b67 reduce GeoIP parser memory usage
Decode one GeoIP entry at a time and cache successful results.

Signed-off-by: ALOKY <ajm1055@uomustansiriyah.edu.iq>
2026-08-16 15:34:30 +03:00
Codex contributor 8d11cdb6ca fix: preserve core state across graceful restarts 2026-08-14 18:57:12 +08:00