65 Commits
Author SHA1 Message Date
Zakk 74277851bb fix(dns): the service, the module's bootstrap and the hijacked resolv.conf follow the DNS rules' direct upstreams
Node hostnames, upstream hostnames and the service's own lookups (subscriptions,
latency tests) were resolved by hard-coded public resolvers (223.5.5.5, 119.29.29.29,
...) whatever the DNS rules said; the second nameserver written into the hijacked
/etc/resolv.conf was hard-coded too. directDnsServers() now collects the plain
udp/tcp IP upstreams of the rules with the direct outbound, and

- resolv.PreferredServers hands them to the service's resolver before its public list
- the module's bootstrap_dns is the system's resolvers plus those upstreams
- the upstream for node hostnames is the first of them
- HijackResolv writes the first port-53 one as the second nameserver, and so does the
  restore when no backup exists

getSystemDnsServers reads the backup while resolv.conf is hijacked, so a restart
no longer hands the module its own listener as bootstrap.
2026-09-20 23:23:08 +10:00
Zakk cc60098633 feat(dns): DNS over HTTPS upstreams, direct and through the proxy; DNS over TLS keeps its server name
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.
2026-09-20 18:53:48 +10:00
Zakk c1e65ca44a fix(dns): refuse DoH and DoQ upstreams on save instead of failing every query
The DNS form's placeholder offered https://dns.google/dns-query, the
service turned https:// into protocol "https" and quic:// into "quic",
and the DNS module handed those to a miekg/dns client, which speaks udp,
tcp and tcp-tls only. Saving succeeded and every query on that rule then
failed, visible only in the log.

CheckDnsUpstream in kernel/v2ray accepts an address, tcp://, udp:// and
tls:// (DNS over TLS, which the module does support) and rejects https://
and quic:// with a message that names the alternatives; PutDnsRules
returns it as a 400 before anything is stored. The placeholder in the six
locales shows the supported forms and the docs say which schemes work.

Verified on the VM: https:// and quic:// rules come back BAD_REQUEST with
the message, tls://1.1.1.1 saves and the module logs
addr=1.1.1.1:853 protocol=tcp-tls; the previous rules restore unchanged.
2026-09-20 18:44:58 +10:00
Zakk 17e6c48dff fix(service): a user without a session keeps its assets in the configuration directory
The core's asset directory defaulted to v2raya/ under the XDG runtime
directory, and the lookup created the links there with xdg.RuntimeFile.
A service user has no session, so /run/user/<uid> does not exist and the
user cannot create it; the first lookup failed with "could not create any
of the following paths: /run/user/1001/v2raya" and the start died, while
geoip.dat and geosite.dat sat in /usr/share/v2raya. That is every
OpenRC v2raya-user.<user> instance and any lite start outside a desktop
session. When the runtime directory cannot be made, the configuration
directory, which the process owns, holds the links instead.

Verified on the Gentoo VM: /etc/init.d/v2raya-user.tuser starts, reports
lite and links /usr/share/v2raya/*.dat into ~/.config/v2raya.
2026-09-20 16:08:25 +10:00
Zakk 61df71b0a4 fix(serverObj): two link shapes from the discussions
A VLESS or VMess link with type=raw — xray's new name for the tcp
transport — was rejected with "unexpected transport type: raw"
(discussion #1999). A vmess JSON whose port, aid or v is a number was
dropped as "not a JSON object"; v2rayN writes strings but most other
exporters write numbers, and one public subscription lost 152 of its
1625 nodes to it (#1957).
2026-09-20 09:59:30 +10:00
Zakk 2d16a92bbb fix(service): the findings of a cold read of the refactor and the scan fixes
Deleting nodes stored the renumbered connections, the subscriptions and
the servers in three commits; they are one transaction. Without a
catch-all DNS rule the module keeps its own fallback, as every earlier
release did. The login body is capped at 4 KiB, since it is now read
before the one-at-a-time semaphore. The apply-config error names a
failed restore, so every handler's message says whether the previous
value came back. The Windows system proxy reuses a snapshot pending
from an earlier run instead of refusing to start.
2026-09-20 09:59:29 +10:00
Zakk 6d744139d4 fix(windows): the system proxy restores every user profile to its own settings
When elevated, saveProxyState captured the first readable profile's
proxy values and stopped, then the restore wrote those values into
every profile: users with different proxy settings got the first
user's, or none. The snapshot now holds one entry per SID (the current
user under "" when not elevated); restore writes each profile its own
values, a profile written at setup but not captured is left with the
proxy disabled, and a snapshot from an earlier release (one flat
profile) still restores the way it did.
2026-09-20 09:59:29 +10:00
Zakk b1ca0c6edc fix(service): every state-changing handler takes the mutation turn; a truncated link cannot panic the parser
PostImport, PutPorts, PutDnsRules, PutRoutingA, PutGFWList,
DeleteGFWList, PutDomainsExcluded, PutTproxyWhiteIpGroups, PostOutbound
and PutOutbound wrote the store and regenerated the core outside the
mutation turn, so two of them could interleave core restarts with each
other or with a latency test. They take it like the rest.

ParseSSURL and ParseVmessURL sliced past the end of a link shorter than
its scheme prefix ("ss:", "vmess:x"), a panic reachable from a
subscription line.
2026-09-20 09:59:29 +10:00
Zakk 9cae52b9d1 feat!: ShadowsocksR is no longer supported
The core has no ShadowsocksR outbound and the plugin that once served
one was removed in May, so every SSR node has been dead since. Instead
of keeping a protocol that cannot connect: an ssr:// link is refused at
import with "ShadowsocksR is not supported" and the Clash converter
skips ssr entries. A node stored by an earlier release still decodes so
it keeps its place in the list and its group ordinal; it shows as
"SSR (unsupported)", cannot be configured and can be deleted. Both
READMEs list the protocols the current core actually speaks. The GUI
side of the removal is in the GUI change that follows.
2026-09-20 09:59:29 +10:00
Zakk ad509ce51b fix(service): the confirmed findings of four independent backend scans
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.
2026-09-20 09:59:29 +10:00
Zakk 21948e1fd7 fix(serverObj): HTTP proxy nodes use the core's http outbound; SSR nodes say they are unsupported
Commit 0baefc45 (2026-05-03) removed the plugin layer under
service/pkg/plugin and the code that started a plugin per node, but
left the HTTP and ShadowsocksR node types producing what that layer
consumed: a socks outbound to 127.0.0.1:<plugin port> plus a plugin
chain nothing reads. Every http/https proxy node and every SSR node
imported since then connected to a closed local port.

HTTP and HTTPS nodes now produce the core's native http outbound with
the credentials and, for https, TLS to the server name; they no longer
ask for a plugin port. The core has no ShadowsocksR outbound, so an SSR
node's configuration returns an "unsupported" error the latency test
and the automatic selection already understand; the node still parses,
displays and exports so nothing is lost from the store.
2026-09-20 09:59:29 +10:00
Zakk ccfc5ca096 refactor(service): one apply-config path, NodeRef as a node's identity, typed SQLite stores
Three structural changes that share files, so one commit:

Settings, ports, DNS rules and custom inbounds each carried their own
copy of "store the new value, regenerate the core config, put the old
value back when that fails", and the outbound setting path had no
restore at all. ApplyCoreConfig takes a snapshot function and a store
function and does the sequence once for all five callers; the outbound
setting path restores like the others, and the error names which of
the three steps failed.

configure.Which was the persisted discriminator, the key that locates a
node, and the response row with its latency, link and selected flag at
once. NodeRef {type, id, sub, outbound} is the identity used by the
locator, EqualTo, the connected lists and the group operations; Which
embeds it and keeps the status fields. The JSON stays byte for byte
what it was (a test marshals a fixture before and after), stored
connected lists decode unchanged, and deduplication keys by identity
instead of by the whole row.

db.List* dispatched on "bucket/key" string literals to reach the
servers and subscriptions tables. The bodies are now Servers* and
Subscriptions* functions that configure calls directly; the List*
wrappers remain for the migration.
2026-09-20 09:59:29 +10:00
Zakk f07adaaa8f fix(service): a core that exits during shutdown is not a crash
systemd sends the whole cgroup SIGTERM, so the core died before the
service and was recorded as a crash; the next boot then refused to
restore the proxy ("exited abnormally the last time", discussion
#1922). The signal handler marks the manager as shutting down before
anything else, a core exit in that state keeps the running flag, and
the units use KillMode=mixed so only the service receives the signal.
2026-09-20 09:17:58 +10:00
Zakk d537477a1c fix(service): the findings of a cold read of the upgrade and crash-recovery changes
A SQLite file that an earlier release's migration left empty next to an
intact bolt.db was taken as authoritative; a file without the system
settings a completed migration writes is discarded and the migration
runs again. A database migrated by that earlier release holds its
groups and outbound settings in the two tables the runtime never read;
opening it copies them into the keys it reads, for outbounds that have
none yet.

A start whose host-state recovery failed refused to run, and a start
that rolled back after its own stop tore the host state down a second
time; recovery is logged and retried at the next start, and a rollback
that stopped its process only clears the marker. A system-proxy
snapshot pending from an earlier run blocked every later system-proxy
start; it is reused as the original instead (Linux and macOS here; the
Windows side follows with its per-profile snapshot).

An empty /etc/resolv.conf was backed up as an empty file, which the
restore rejects as truncated; it is written as a marker and restored as
empty. db.Close resets the once so a reopen works.
2026-09-20 09:17:58 +10:00
Zakk 58acf7d40f fix(service): a start that never commits leaves nothing behind on the host
Start persisted running=false, stopped the old core, published the new
process and unlocked, installed the firewall rules, DNS hijack, TUN
routes or system proxy, and only then persisted running=true. A crash in
that window made the next start skip the core and clean only TUN
residue, so redirect rules, a hijacked resolver or the system proxy kept
pointing at a dead listener.

Before it installs anything, Start now stores a host-state marker (the
transparent type, API port and TUN teardown settings) and clears it once
the start commits or is rolled back; startup and the next Start tear
that state down when they find the marker. Every host mutation and the
final commit check that the process they started is still the manager's
current one, so a core that exits during afterStart fails the start
instead of leaving the UI and the store saying running. The system-proxy
implementations persist the user's original proxy settings when they
capture them and restore from that copy when the in-memory one is gone.
A recovery that fails is logged and retried at the next start; it never
blocks the service.
2026-09-20 09:17:11 +10:00
Zakk ae8e5a5047 chore: drop what nothing reaches
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/.
2026-09-20 09:17:11 +10:00
Zakk 90825094f8 fix(service): hook deadline, gated inbound writes, cleanup on a failed bind, atomic resolv backup
The core hooks ran under exec.Command with no deadline while Start held
the manager's lock, so a hook that never returned left the proxy stopped
and every status read blocked. They now run with the startup timeout as
their deadline in their own process group.

The custom-inbound POST and DELETE handlers did not take the mutation
turn; two concurrent additions read the same list and the last write
won. They take it like every other state-changing handler.

A failed HTTP bind ended in log.Fatal before the deferred cleanup, so
the core and the transparent-proxy rules stayed behind; run() now
returns the error through the same cleanup the shutdown path uses.

The resolv.conf backup was written in place; a crash mid-write left a
truncated file that the next start restored as the original. It is
written to a temporary file, synced and renamed, and an empty backup is
ignored on restore.
2026-09-20 09:17:11 +10:00
Zakk 723630f4fd fix(service): stop the API producers of a template the core never ran
SetAPI starts the traffic and observatory producers together with the
template, and only a running process closes them. A start that failed
before the process existed — the config write, the inbound port check or
the missing GFWList — returned without closing the template, and the
latency test returned early on port exhaustion the same way. Each such
failure left goroutines dialling a port nothing listens on and logging a
warning every second for the rest of the service's life.

NewProcess closes the template on every error path, the GFWList check
closes it before returning, and the latency test closes its template
until the process manager owns it.
2026-09-20 00:32:37 +10:00
Zakk 8e948dbf2d perf(service): locate connected servers with one read of the lists
Which.LocateServerRaw read and parsed every stored node for each lookup,
so a loop over n whiches cost n reads: the latency test, the config
generation for a group, the touch and the subscription update each
scaled with the square of the node count. A Locator reads each list on
first use and resolves every which of the loop against it; the single
lookups keep LocateServerRaw. Resolving 1000 subscription nodes drops
from 1.1 s to 1.6 ms (BenchmarkLocateAll vs BenchmarkLocatorAll).
2026-09-20 00:24:54 +10:00
Zakk 86eaaee6b5 feat(service): traffic frames on the message socket
The core's StatsService is registered and enabled in the template;
a producer reads the inbound counters every second and publishes
{up, down, upTotal, downTotal} as a traffic frame, which the GUI's
dashboard plots. A GUI that does not know the frame type ignores it.
2026-09-19 23:17:05 +10:00
Zakk 868497a0e9 feat(service): a group may route through one selected member
An outbound group with several members is balanced by the observatory
(least ping). The group's setting now also names one member's share
link as Selected: the core template then keeps only that member, the
touch flags it on the connected entry, and PUT /outboundSelection sets
or clears it. A selection that matches no member is ignored, so a node
removed or renamed by a subscription update returns the group to
balancing instead of breaking it.
2026-09-19 23:17:05 +10:00
Zakk d66c3927a5 fix(server): requests that change state apply or restore; requests that fetch have deadlines
PUT /dnsRules regenerates the running core's config and restores the
previous rules when that fails; SetPorts restores the previous ports
when the restart fails. The HTTP latency test drops subscription
entries as intended. The remote GFWList version request has a deadline
and its cache a one-hour TTL. CheckUpdate picks the index of the running
architecture and closes the body on every path.
2026-09-19 22:04:11 +10:00
Zakk 7c482856c8 fix(kernel): races and leaks around the core process and the observatory
Running() reads the process under the manager's lock; the early-exit
flag is atomic; a second Close no longer waits on the reaped process; an
empty log chunk no longer panics. The observatory producer rejects tags
it cannot map instead of attributing them to the first node, paces every
path so an unknown tag cannot spin it, closes an unavailable connection
before dropping it and cancels each dial context at once. Balancer
outbounds get their serverInfoMap entry on success, not only on failure.
The resolv hijacker is serialised between the start path and the
connectivity monitor.
2026-09-19 22:04:03 +10:00
Zakk e05e672fe5 build: drop the tinytun build tag and ship Wintun from its own package
The binaries workflow, the PR workflow and build.ps1 no longer pass
-tags tinytun; there is nothing behind the tag. The Windows installer
takes wintun.dll from the official 0.14.1 package, pinned by hash, one
DLL per architecture, and deletes a tinytun.exe an earlier installer left
in the application's bin directory. The README states what the built-in
TUN does and its known limitation on Windows and macOS.
2026-09-19 10:34:56 +10:00
Zakk 2d95891aed feat(service): tun routes and system DNS on Windows and macOS
Neither platform has a socket mark, so the physical default route is left
in place and two /1 routes per family are added on the TUN instead; the
core's sockets and the DNS module's upstreams are bound to the physical
interface, which the template reads from the default route before the
TUN routes exist.

Windows points the adapter's DNS at the TUN gateway address with the
lowest interface metric; queries sent there enter the TUN and the core
relays them to the DNS module. macOS needs two things more. A socket
bound to en0 with IP_BOUND_IF looks routes up in en0's scope, and once
the /1 routes exist the only match is theirs, so the lookup fails with
ENETUNREACH: a scoped copy of the physical default route
(route add -ifscope en0 default <gw>) gives bound sockets a way out. And
mDNSResponder scopes its queries to the service's interface, dropping a
reply that arrives through the utun, so the system resolver is pointed at
loopback and the DNS module gets a 127.0.0.1:53 listener in tun mode.
The routes use the gateway form, as xray's own tun does. The kernel
assigns the utun unit and the service finds the device by its address;
the previous resolvers of every network service are kept for stop.

Both were exercised in milestone C: a Windows Server 2025 VM and an
arm64 MacBook. Applications that query a LAN resolver directly still
bypass the TUN on these platforms in this phase; that is documented as a
known limitation.
2026-09-19 10:34:56 +10:00
Zakk 1dd2bf28ad feat(service): the tun transparent proxy is the core's own device
transparentType=tun no longer starts the TinyTun process. The template
emits a tun-mips inbound tagged transparent — device name, address, MTU,
the DNS module's address as the relay target, the user's exclusion list
plus v2rayA and the core by name and v2rayA by PID — and the service does
what the operating system needs once the core has the device up.

On Linux that is one table and four policy rules: table 2020 holds the
default route into tun0; marked packets (0x80: the core's sockets, the
direct outbound, the DNS module's upstreams) look up main in full and
leave through the physical interface, or fail with ENETUNREACH when main
has no route for their family rather than fall into the TUN; unmarked
packets take main with its default route suppressed, so LAN and static
routes stay physical, and everything else goes to table 2020. The main
table is never edited, so stopping restores egress by itself. A rule in
our preference range or a route in our table that is not ours is reported
and left alone; our own leftovers from a crash are removed first. Every
command that succeeded is recorded and undone in reverse on stop.

Three things the TinyTun path never hit are now on tun's path, so they
are fixed here: the DNS module is generated in tun mode (TinyTun did DNS
itself); its 127.2.0.17:53 listener is only added when port 53 is free,
instead of making the core exit on a host running another resolver; its
primary listener stays on loopback unless port sharing is on or the user
chose an address, and the DNS REDIRECT rules and their cleanup follow the
module's port instead of a hard-coded 52353, and a ::1 listener is added
when IPv6 is supported, because ip6tables REDIRECT delivers an
application's IPv6 query to ::1 which the IPv4 listener never saw. The
tun branch no longer
skips those rules: they are what catches queries to a LAN resolver, which
the routing keeps off the TUN.

The connectivity monitor probes the core's API port; the TinyTun socks
loop-back port it used is gone. Removed with TinyTun: --tinytun-bin, the
tunProcessBackend (eBPF) and tunBypassInterfaces settings (connected and
static routes bypass the TUN unconditionally now), the /networkInterfaces
endpoint that only served the latter, and the build tag. The version
endpoint reports tunSupported instead of tinytunSupported.

Tests cover the generated inbound and DNS module, the listen-address
rules, the redirect port, and — with V2RAYA_CORE_BIN set — that the
generated document loads in the real core. Windows and macOS route
handling follows in a separate commit; until then those builds report
the TUN as unsupported.
2026-09-19 10:34:55 +10:00
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 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 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 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 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 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 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 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 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 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
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
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