3x-ui/internal/xray/hot_diff.go

517 lines
15 KiB
Go
Raw Normal View History

package xray
import (
"bytes"
"encoding/json"
"github.com/mhsanaei/3x-ui/v3/internal/logger"
"github.com/mhsanaei/3x-ui/v3/internal/util/json_util"
)
// HotDiff describes the gRPC API operations needed to bring a running Xray
// instance from one generated config to another without restarting the
// process. It only covers the sections Xray can reload at runtime: inbounds,
// outbounds and routing rules/balancers.
type HotDiff struct {
RemovedInboundTags []string
AddedInbounds [][]byte
RemovedUsers []UserOp
AddedUsers []UserOp
RemovedOutboundTags []string
AddedOutbounds [][]byte
RoutingConfig []byte // full new routing section; nil when unchanged
}
// UserOp is a per-user AlterInbound operation; User is nil for removals.
type UserOp struct {
Tag string
Protocol string
Email string
User map[string]any
}
// Empty reports whether the diff contains no operations.
func (d *HotDiff) Empty() bool {
return len(d.RemovedInboundTags) == 0 &&
len(d.AddedInbounds) == 0 &&
len(d.RemovedUsers) == 0 &&
len(d.AddedUsers) == 0 &&
len(d.RemovedOutboundTags) == 0 &&
len(d.AddedOutbounds) == 0 &&
d.RoutingConfig == nil
}
// ComputeHotDiff compares two generated configs and returns the API operations
// that transform a running instance from oldCfg to newCfg. ok is false when
// the change touches anything that has no runtime reload API (log, dns,
// policy, ...) and therefore requires a full process restart.
func ComputeHotDiff(oldCfg, newCfg *Config) (*HotDiff, bool) {
if oldCfg == nil || newCfg == nil {
return nil, false
}
// Sections without a reload API must be semantically identical.
// Comparison is whitespace-insensitive: a template save that merely
// reformats the JSON (frontend textarea, API clients) must not be
// mistaken for a real change that forces a restart.
static := []struct {
name string
old, new json_util.RawMessage
}{
{"log", oldCfg.LogConfig, newCfg.LogConfig},
{"dns", oldCfg.DNSConfig, newCfg.DNSConfig},
{"transport", oldCfg.Transport, newCfg.Transport},
{"policy", oldCfg.Policy, newCfg.Policy},
{"api", oldCfg.API, newCfg.API},
{"stats", oldCfg.Stats, newCfg.Stats},
{"reverse", oldCfg.Reverse, newCfg.Reverse},
{"fakedns", oldCfg.FakeDNS, newCfg.FakeDNS},
{"observatory", oldCfg.Observatory, newCfg.Observatory},
{"burstObservatory", oldCfg.BurstObservatory, newCfg.BurstObservatory},
{"metrics", oldCfg.Metrics, newCfg.Metrics},
{"geodata", oldCfg.Geodata, newCfg.Geodata},
feat(xray): update xray-core to v26.7.11 and adapt panel Bump xtls/xray-core to 50231eaf (v26.7.11) and the three binary pins (DockerInit.sh, release.yml x2) in lockstep. Adapt the panel to the upstream changes: - Shadowsocks "none"/"plain" and VMess "none"/"zero" were removed from the core. A migration rewrites stored none/plain SS methods to a supported cipher and none/zero VMess security to "auto" (on both the clients column and inbound settings JSON); the SS build-time heal does the same so a row injected after boot cannot brick startup. The removed values are dropped from every frontend option list, schema and adapter, and coerced to "auto" at the Go link/sub/Clash emit sites and both link importers. Fix the CipherType_NONE sentinel that no longer compiles. - Unencrypted vless/trojan outbounds to a public address are now refused by the core. Validate outbounds through the vendored config loader when saving the xray template and when storing/merging outbound subscriptions, so one such outbound cannot keep the core from starting. - New TCP finalmask type "xmc" (Minecraft mimicry): add it to the sub link allowlist, the frontend enum and the FinalMask form (hostname, usernames, required password), and document it. - streamSettings gained a "method" alias for "network"; canonicalize it to "network" at inbound save time and in the form adapters/schema so a method-keyed config keeps its transport. - New root "env" config key is passed through xray.Config, compared in Equals, and forces a restart in the hot diff. - REALITY now defaults minClientVer to 26.3.27; update the form placeholder.
2026-07-11 15:30:47 -07:00
{"env", oldCfg.Env, newCfg.Env},
}
for _, section := range static {
if !rawEqualNormalized(section.old, section.new) {
logger.Debug("hot diff: section [", section.name, "] changed and has no reload API")
return nil, false
}
}
diff := &HotDiff{}
if ok := diffInbounds(oldCfg, newCfg, diff); !ok {
logger.Debug("hot diff: inbound change is not API-applicable")
return nil, false
}
if ok := diffOutbounds(oldCfg, newCfg, diff); !ok {
logger.Debug("hot diff: outbound change is not API-applicable (default outbound or tags)")
return nil, false
}
if ok := diffRouting(oldCfg, newCfg, diff); !ok {
logger.Debug("hot diff: routing change is not API-applicable (domainStrategy or section shape)")
return nil, false
}
return diff, true
}
// diffInbounds fills diff with inbound removals/additions (a changed inbound
// becomes remove+add). The api inbound carries the gRPC server the panel is
// talking through, so any change touching it forces a restart.
func diffInbounds(oldCfg, newCfg *Config, diff *HotDiff) bool {
oldByTag, ok := inboundsByTag(oldCfg.InboundConfigs)
if !ok {
return false
}
newByTag, ok := inboundsByTag(newCfg.InboundConfigs)
if !ok {
return false
}
apiTag := apiTagFromConfig(newCfg.API)
for i := range oldCfg.InboundConfigs {
oldIb := &oldCfg.InboundConfigs[i]
newIb, exists := newByTag[oldIb.Tag]
if exists && inboundEqualNormalized(oldIb, newIb) {
continue
}
if oldIb.Tag == apiTag || oldIb.Tag == "api" {
return false
}
if exists && (inboundHasReverseClient(oldIb) || inboundHasReverseClient(newIb)) {
logger.Debug("hot diff: inbound [", oldIb.Tag, "] carries a reverse-tagged client, forcing a full restart instead of a hot swap")
return false
}
if exists && diffInboundUsers(oldIb, newIb, diff) {
continue
}
Bug-label issue sweep: 16 fixes (#6083) * fix(xray): block private-range egress in default freedom finalRules (#6037) With domainStrategy AsIs the router never resolves domains, so a domain with a private A record (e.g. 127-0-0-1.nip.io) sails past the geoip:private routing block and freedom's allow-all finalRules let it reach loopback services such as the xray gRPC API and metrics listener. Prepend a block rule for geoip:private to the default template and add the FreedomFinalRulesPrivateEgressBlock seeder so existing installs still carrying the stock allow-only (or legacy private-only-allow) finalRules are upgraded in place; customized rules are left untouched. * fix(sub): version-gate unencrypted-outbound drops in outbound subscriptions (#6033) Commit d38c912d taught CheckXrayConfig to keep unencrypted vless/trojan outbounds when the running core predates the v26.7.11 rejection, but filterOutboundsRejectedByCore still consulted the embedded validator unconditionally, so outbound subscriptions kept silently dropping those outbounds even on downgraded cores. Apply the same shouldSkipLegacyUnencryptedOutboundRejection gate when filtering fetched subscription outbounds. * fix(xray): resolve geodata assets before building outbound configs (#5928) Saving routing or template settings validates each outbound through the embedded config loader, and a freedom outbound whose finalRules reference geoip:private opens geoip.dat during that build. Unlike ApplyRoutingConfig, ValidateOutboundConfig and AddOutbound never pointed the in-process loader at the bin folder, so xray-core resolved the file relative to the panel executable and saving failed with 'stat /usr/local/x-ui/geoip.dat: no such file or directory'. Call ensureXrayAssetLocation before both build paths. * fix(api): use a real i18n key in the client get handler (#5911) The client fetch endpoint localized its error prefix with the bare key 'get', which exists in no translation file, so every lookup of a deleted client's email logged 'message "get" not found in language ...' noise alongside the expected record-not-found warning. Reuse the same pages.inbounds.toasts.obtain key the sibling list handler uses. * fix(sub): carry host record Host header and path into Clash/JSON output (#5944) The raw-link path overrides the host/path share params from a Host record via applyEndpointHostPath, but the Clash and JSON renderers read the transport settings object, which applyHostStreamOverrides never touched — so a Host record's WebSocket Host header (and path) silently vanished from Clash/Mihomo and JSON subscriptions whenever the inbound's own ws settings left them empty. Inject hostHeader/path into the ws/httpupgrade/xhttp settings of the per-host stream, mirroring the raw-link override. * fix(metrics): accept Unicode outbound tags in the observatory (#5972) The observatory validator whitelisted ASCII word characters, so any outbound whose tag carries a flag emoji or other non-ASCII text was silently dropped from the metrics snapshot, delay history, and health notifications. The history store is an in-process map, so the strict charset bought nothing. Validate tags as non-empty, bounded, control-character-free UTF-8 instead, keeping spaces and emoji while still rejecting garbage input on the query path. * fix(database): default sqlite to WAL to stop background-job lock storms (#6057, #6068) With journal_mode=DELETE every write serializes the whole database and blocks readers, so under normal multi-job load (traffic sampling, node sync, mtproto reconcile) transactions regularly outwaited the 10s busy timeout and jobs failed with 'database is locked'. Move to WAL by default: readers no longer block writers and vice versa, which removes the observed contention while writer-writer access still serializes safely. The single-file-at-rest property is preserved where it matters — Checkpoint() now issues wal_checkpoint(TRUNCATE), so panel and Telegram backups read a complete main file, and sqlite folds the WAL back into the db on clean shutdown. XUI_DB_JOURNAL_MODE=DELETE restores the previous behavior for setups that copy the live file directly. * fix(database): strip finalmask.tcp from REALITY inbounds on upgrade (#6038) validateFinalMaskRealityCombo blocks saving finalmask.tcp together with REALITY because that combination crashes Xray-core 26.7.11 on the first connection (XTLS/Xray-core#6453), but it only runs on add/update. An inbound saved before the validator existed sailed through the upgrade untouched and took the core down at boot. Add the InboundRealityFinalmaskTcpStrip seeder: one-time scan that removes finalmask.tcp from REALITY inbounds (other finalmask transports survive), so upgraded panels start cleanly. * fix(xray): stop deleting hand-written direct routing rules on save (#6056) The DNS allow-rule sync recognized 'its' rules purely by shape (type=field, ip, port, outboundTag=direct, nothing else), so any manual rule of that shape — e.g. routing a LAN CIDR to a NAS port over direct — was silently stripped on every settings save. Mark managed rules with ruleTag=xui-dns-allow (round-tripped untouched by both xray-core and the Routing tab editor) and only strip rules that carry the tag. Untagged legacy managed rules are adopted when their exact ip-set/port matches a currently configured private DNS endpoint; anything else is left alone. A stale pre-tag managed rule whose DNS server was removed now lingers until deleted manually — the safe side of the trade against eating user rules. * fix(clients): resolve email lookups through client_inbounds after a move (#6059) GetClientInboundByEmail trusted the client_traffics.inbound_id pointer whenever that inbound still existed, but a client moved between inbounds leaves the row pointing at its old (still existing) inbound. The lookup then searched the wrong inbound's clients and failed with 'Client Not Found In Inbound For Email', which broke the Telegram bot's link and QR generation for moved clients. When the pointed-at inbound no longer carries the email, re-resolve through the authoritative client_inbounds link to the inbound that actually hosts the client. * fix(nodes): replicate inbound fallbacks to nodes (#5963) Fallbacks live in the inbound_fallbacks table and were only merged into settings by the master's local config builder; the runtime inbound pushed to nodes rebuilt settings without them, and the reconcile job additionally fingerprinted the raw DB row, so fallback edits neither reached nodes nor triggered a re-push. Inject settings.fallbacks in buildRuntimeInboundForAPI (mirroring the local builder, gated on inboundCanHostFallbacks) and make ReconcileNode push and fingerprint that same runtime-built payload, aligning the interactive and reconcile paths. * fix(database): survive PostgreSQL outages without a runaway restart loop (#6023) A PostgreSQL that was down or still starting made InitDB fail instantly; the process exited with a generic startup error and systemd restarted it every 5s forever, flooding the journal. Retry the initial postgres connection with backoff (~70s total) and log the real driver error on every attempt, and cap the systemd units with StartLimitIntervalSec/StartLimitBurst so a persistently unreachable database stops the unit instead of looping indefinitely. * fix(xray): force a full restart when REALITY stream settings change (#6010) A changed inbound is normally hot-swapped over gRPC as RemoveInbound + AddInbound, but xray-core does not reliably rebuild a REALITY listener's authenticator on a runtime re-add — key or shortId edits appeared applied yet clients kept authenticating against the old parameters until someone restarted the core manually, on nodes in particular. Treat any non-client change to an inbound that uses (or starts using) REALITY as not hot-appliable so the panel restarts the core instead. Client-only edits on REALITY inbounds keep flowing through the per-user AlterInbound path and still avoid restarts. * feat(sub): allow insecure TLS for outbound subscription fetches (#6067) An outbound subscription served over HTTPS with a self-signed or private-CA certificate could never be fetched: the fetch client had no TLS options, so refreshes died with 'x509: certificate signed by unknown authority' and there was nothing the admin could toggle. Add a per-subscription 'Allow insecure' switch (persisted as allow_insecure, default off) that sets InsecureSkipVerify on the fetch transport — including when the fetch is routed through the panel egress proxy. The SSRF-guarded dialer and redirect re-validation stay in force either way. * fix(reality): send PROXY protocol header in the target scanner when xver is set (#6082) The REALITY target scanner always probed with a plain TLS handshake, so a target fronted by an Nginx listener that requires the PROXY protocol (matching the inbound's xver>=1) reset the connection and the panel reported a false 'TLS handshake failed'. Thread the inbound's xver into the scan request and, when it is >=1, lead with the matching PROXY protocol header (v1 for xver 1, binary v2 for xver 2) built from the dialed connection's own address pair. Batch candidate scans against public sites are unaffected (xver 0). * fix(frontend): default sockopt fields when editing a stored inbound (#5956) Opening an existing inbound ran rawInboundToFormValues over the raw DB row, and only xhttpSettings was re-parsed through its Zod schema to fill defaults. A sockopt object saved before the TProxy control existed has no tproxy key, so the Select rendered blank; picking Off didn't help because the wire normalizer drops tproxy=off, recreating the missing key on the next edit. Re-parse streamSettings.sockopt through SockoptStreamSettingsSchema on load, mirroring the xhttpSettings handling, so absent keys (tproxy, tcpcongestion, …) get their schema defaults every time the form opens.
2026-07-23 06:34:42 -07:00
if exists && (inboundUsesReality(oldIb) || inboundUsesReality(newIb)) {
logger.Debug("hot diff: inbound [", oldIb.Tag, "] REALITY configuration changed; a gRPC remove+add does not reliably rebuild the REALITY authenticator, forcing a full restart")
return false
}
diff.RemovedInboundTags = append(diff.RemovedInboundTags, oldIb.Tag)
if exists {
raw, err := json.Marshal(newIb)
if err != nil {
return false
}
diff.AddedInbounds = append(diff.AddedInbounds, raw)
}
}
for i := range newCfg.InboundConfigs {
newIb := &newCfg.InboundConfigs[i]
if _, exists := oldByTag[newIb.Tag]; exists {
continue
}
if newIb.Tag == apiTag || newIb.Tag == "api" {
return false
}
raw, err := json.Marshal(newIb)
if err != nil {
return false
}
diff.AddedInbounds = append(diff.AddedInbounds, raw)
}
return true
}
var userDiffableProtocols = map[string]struct{}{"vless": {}, "vmess": {}, "trojan": {}}
// diffInboundUsers emits per-user AlterInbound ops when two same-tag inbounds
// differ only in settings.clients, so the handler (and its listener) survives.
func diffInboundUsers(oldIb, newIb *InboundConfig, diff *HotDiff) bool {
if oldIb.Port != newIb.Port || oldIb.Protocol != newIb.Protocol || oldIb.Tag != newIb.Tag {
return false
}
if _, ok := userDiffableProtocols[oldIb.Protocol]; !ok {
return false
}
if !rawEqualNormalized(oldIb.Listen, newIb.Listen) ||
!rawEqualNormalized(oldIb.StreamSettings, newIb.StreamSettings) ||
!rawEqualNormalized(oldIb.Sniffing, newIb.Sniffing) {
return false
}
oldClients, oldRest, ok := splitSettingsClients(oldIb.Settings)
if !ok {
return false
}
newClients, newRest, ok := splitSettingsClients(newIb.Settings)
if !ok {
return false
}
if !bytes.Equal(oldRest, newRest) {
return false
}
for email, oldC := range oldClients {
newC, exists := newClients[email]
if exists && bytes.Equal(oldC.norm, newC.norm) {
continue
}
diff.RemovedUsers = append(diff.RemovedUsers, UserOp{Tag: oldIb.Tag, Protocol: oldIb.Protocol, Email: email})
if exists {
diff.AddedUsers = append(diff.AddedUsers, UserOp{Tag: oldIb.Tag, Protocol: oldIb.Protocol, Email: email, User: newC.user})
}
}
for email, newC := range newClients {
if _, exists := oldClients[email]; !exists {
diff.AddedUsers = append(diff.AddedUsers, UserOp{Tag: oldIb.Tag, Protocol: oldIb.Protocol, Email: email, User: newC.user})
}
}
return true
}
type clientEntry struct {
user map[string]any
norm []byte
}
// splitSettingsClients indexes settings.clients by email and returns the rest of
// the settings in canonical form; ok is false when a client has no unique email.
func splitSettingsClients(raw json_util.RawMessage) (map[string]clientEntry, []byte, bool) {
if len(raw) == 0 {
return nil, nil, false
}
settings := map[string]any{}
decoder := json.NewDecoder(bytes.NewReader(raw))
decoder.UseNumber()
if err := decoder.Decode(&settings); err != nil {
return nil, nil, false
}
clientsRaw, hasClients := settings["clients"].([]any)
if !hasClients {
return nil, nil, false
}
clients := make(map[string]clientEntry, len(clientsRaw))
for _, c := range clientsRaw {
obj, ok := c.(map[string]any)
if !ok {
return nil, nil, false
}
email, _ := obj["email"].(string)
if email == "" {
return nil, nil, false
}
if _, dup := clients[email]; dup {
return nil, nil, false
}
norm, err := json.Marshal(obj)
if err != nil {
return nil, nil, false
}
clients[email] = clientEntry{user: obj, norm: norm}
}
delete(settings, "clients")
rest, err := json.Marshal(settings)
if err != nil {
return nil, nil, false
}
return clients, rest, true
}
Bug-label issue sweep: 16 fixes (#6083) * fix(xray): block private-range egress in default freedom finalRules (#6037) With domainStrategy AsIs the router never resolves domains, so a domain with a private A record (e.g. 127-0-0-1.nip.io) sails past the geoip:private routing block and freedom's allow-all finalRules let it reach loopback services such as the xray gRPC API and metrics listener. Prepend a block rule for geoip:private to the default template and add the FreedomFinalRulesPrivateEgressBlock seeder so existing installs still carrying the stock allow-only (or legacy private-only-allow) finalRules are upgraded in place; customized rules are left untouched. * fix(sub): version-gate unencrypted-outbound drops in outbound subscriptions (#6033) Commit d38c912d taught CheckXrayConfig to keep unencrypted vless/trojan outbounds when the running core predates the v26.7.11 rejection, but filterOutboundsRejectedByCore still consulted the embedded validator unconditionally, so outbound subscriptions kept silently dropping those outbounds even on downgraded cores. Apply the same shouldSkipLegacyUnencryptedOutboundRejection gate when filtering fetched subscription outbounds. * fix(xray): resolve geodata assets before building outbound configs (#5928) Saving routing or template settings validates each outbound through the embedded config loader, and a freedom outbound whose finalRules reference geoip:private opens geoip.dat during that build. Unlike ApplyRoutingConfig, ValidateOutboundConfig and AddOutbound never pointed the in-process loader at the bin folder, so xray-core resolved the file relative to the panel executable and saving failed with 'stat /usr/local/x-ui/geoip.dat: no such file or directory'. Call ensureXrayAssetLocation before both build paths. * fix(api): use a real i18n key in the client get handler (#5911) The client fetch endpoint localized its error prefix with the bare key 'get', which exists in no translation file, so every lookup of a deleted client's email logged 'message "get" not found in language ...' noise alongside the expected record-not-found warning. Reuse the same pages.inbounds.toasts.obtain key the sibling list handler uses. * fix(sub): carry host record Host header and path into Clash/JSON output (#5944) The raw-link path overrides the host/path share params from a Host record via applyEndpointHostPath, but the Clash and JSON renderers read the transport settings object, which applyHostStreamOverrides never touched — so a Host record's WebSocket Host header (and path) silently vanished from Clash/Mihomo and JSON subscriptions whenever the inbound's own ws settings left them empty. Inject hostHeader/path into the ws/httpupgrade/xhttp settings of the per-host stream, mirroring the raw-link override. * fix(metrics): accept Unicode outbound tags in the observatory (#5972) The observatory validator whitelisted ASCII word characters, so any outbound whose tag carries a flag emoji or other non-ASCII text was silently dropped from the metrics snapshot, delay history, and health notifications. The history store is an in-process map, so the strict charset bought nothing. Validate tags as non-empty, bounded, control-character-free UTF-8 instead, keeping spaces and emoji while still rejecting garbage input on the query path. * fix(database): default sqlite to WAL to stop background-job lock storms (#6057, #6068) With journal_mode=DELETE every write serializes the whole database and blocks readers, so under normal multi-job load (traffic sampling, node sync, mtproto reconcile) transactions regularly outwaited the 10s busy timeout and jobs failed with 'database is locked'. Move to WAL by default: readers no longer block writers and vice versa, which removes the observed contention while writer-writer access still serializes safely. The single-file-at-rest property is preserved where it matters — Checkpoint() now issues wal_checkpoint(TRUNCATE), so panel and Telegram backups read a complete main file, and sqlite folds the WAL back into the db on clean shutdown. XUI_DB_JOURNAL_MODE=DELETE restores the previous behavior for setups that copy the live file directly. * fix(database): strip finalmask.tcp from REALITY inbounds on upgrade (#6038) validateFinalMaskRealityCombo blocks saving finalmask.tcp together with REALITY because that combination crashes Xray-core 26.7.11 on the first connection (XTLS/Xray-core#6453), but it only runs on add/update. An inbound saved before the validator existed sailed through the upgrade untouched and took the core down at boot. Add the InboundRealityFinalmaskTcpStrip seeder: one-time scan that removes finalmask.tcp from REALITY inbounds (other finalmask transports survive), so upgraded panels start cleanly. * fix(xray): stop deleting hand-written direct routing rules on save (#6056) The DNS allow-rule sync recognized 'its' rules purely by shape (type=field, ip, port, outboundTag=direct, nothing else), so any manual rule of that shape — e.g. routing a LAN CIDR to a NAS port over direct — was silently stripped on every settings save. Mark managed rules with ruleTag=xui-dns-allow (round-tripped untouched by both xray-core and the Routing tab editor) and only strip rules that carry the tag. Untagged legacy managed rules are adopted when their exact ip-set/port matches a currently configured private DNS endpoint; anything else is left alone. A stale pre-tag managed rule whose DNS server was removed now lingers until deleted manually — the safe side of the trade against eating user rules. * fix(clients): resolve email lookups through client_inbounds after a move (#6059) GetClientInboundByEmail trusted the client_traffics.inbound_id pointer whenever that inbound still existed, but a client moved between inbounds leaves the row pointing at its old (still existing) inbound. The lookup then searched the wrong inbound's clients and failed with 'Client Not Found In Inbound For Email', which broke the Telegram bot's link and QR generation for moved clients. When the pointed-at inbound no longer carries the email, re-resolve through the authoritative client_inbounds link to the inbound that actually hosts the client. * fix(nodes): replicate inbound fallbacks to nodes (#5963) Fallbacks live in the inbound_fallbacks table and were only merged into settings by the master's local config builder; the runtime inbound pushed to nodes rebuilt settings without them, and the reconcile job additionally fingerprinted the raw DB row, so fallback edits neither reached nodes nor triggered a re-push. Inject settings.fallbacks in buildRuntimeInboundForAPI (mirroring the local builder, gated on inboundCanHostFallbacks) and make ReconcileNode push and fingerprint that same runtime-built payload, aligning the interactive and reconcile paths. * fix(database): survive PostgreSQL outages without a runaway restart loop (#6023) A PostgreSQL that was down or still starting made InitDB fail instantly; the process exited with a generic startup error and systemd restarted it every 5s forever, flooding the journal. Retry the initial postgres connection with backoff (~70s total) and log the real driver error on every attempt, and cap the systemd units with StartLimitIntervalSec/StartLimitBurst so a persistently unreachable database stops the unit instead of looping indefinitely. * fix(xray): force a full restart when REALITY stream settings change (#6010) A changed inbound is normally hot-swapped over gRPC as RemoveInbound + AddInbound, but xray-core does not reliably rebuild a REALITY listener's authenticator on a runtime re-add — key or shortId edits appeared applied yet clients kept authenticating against the old parameters until someone restarted the core manually, on nodes in particular. Treat any non-client change to an inbound that uses (or starts using) REALITY as not hot-appliable so the panel restarts the core instead. Client-only edits on REALITY inbounds keep flowing through the per-user AlterInbound path and still avoid restarts. * feat(sub): allow insecure TLS for outbound subscription fetches (#6067) An outbound subscription served over HTTPS with a self-signed or private-CA certificate could never be fetched: the fetch client had no TLS options, so refreshes died with 'x509: certificate signed by unknown authority' and there was nothing the admin could toggle. Add a per-subscription 'Allow insecure' switch (persisted as allow_insecure, default off) that sets InsecureSkipVerify on the fetch transport — including when the fetch is routed through the panel egress proxy. The SSRF-guarded dialer and redirect re-validation stay in force either way. * fix(reality): send PROXY protocol header in the target scanner when xver is set (#6082) The REALITY target scanner always probed with a plain TLS handshake, so a target fronted by an Nginx listener that requires the PROXY protocol (matching the inbound's xver>=1) reset the connection and the panel reported a false 'TLS handshake failed'. Thread the inbound's xver into the scan request and, when it is >=1, lead with the matching PROXY protocol header (v1 for xver 1, binary v2 for xver 2) built from the dialed connection's own address pair. Batch candidate scans against public sites are unaffected (xver 0). * fix(frontend): default sockopt fields when editing a stored inbound (#5956) Opening an existing inbound ran rawInboundToFormValues over the raw DB row, and only xhttpSettings was re-parsed through its Zod schema to fill defaults. A sockopt object saved before the TProxy control existed has no tproxy key, so the Select rendered blank; picking Off didn't help because the wire normalizer drops tproxy=off, recreating the missing key on the next edit. Re-parse streamSettings.sockopt through SockoptStreamSettingsSchema on load, mirroring the xhttpSettings handling, so absent keys (tproxy, tcpcongestion, …) get their schema defaults every time the form opens.
2026-07-23 06:34:42 -07:00
func inboundUsesReality(ib *InboundConfig) bool {
if ib == nil || len(ib.StreamSettings) == 0 {
return false
}
var stream struct {
Security string `json:"security"`
}
if err := json.Unmarshal(ib.StreamSettings, &stream); err != nil {
return false
}
return stream.Security == "reality"
}
func inboundHasReverseClient(ib *InboundConfig) bool {
if ib == nil {
return false
}
var settings struct {
Clients []struct {
Reverse json.RawMessage `json:"reverse"`
} `json:"clients"`
}
if err := json.Unmarshal(ib.Settings, &settings); err != nil {
return false
}
for _, c := range settings.Clients {
if len(c.Reverse) == 0 {
continue
}
var tag any
if err := json.Unmarshal(c.Reverse, &tag); err != nil || tag == nil {
continue
}
return true
}
return false
}
// diffOutbounds fills diff with outbound removals/additions keyed by tag.
// The first outbound is xray's default handler and the API can only append,
// so any change to its identity or content forces a restart. Reordering of
// the remaining outbounds is ignored — routing addresses them by tag.
func diffOutbounds(oldCfg, newCfg *Config, diff *HotDiff) bool {
oldOut, ok := parseOutbounds(oldCfg.OutboundConfigs)
if !ok {
return false
}
newOut, ok := parseOutbounds(newCfg.OutboundConfigs)
if !ok {
return false
}
if (len(oldOut) == 0) != (len(newOut) == 0) {
return false
}
if len(oldOut) > 0 {
if oldOut[0].tag != newOut[0].tag || !bytes.Equal(oldOut[0].norm, newOut[0].norm) {
return false
}
}
oldByTag := make(map[string]outboundEntry, len(oldOut))
for _, e := range oldOut {
oldByTag[e.tag] = e
}
newByTag := make(map[string]outboundEntry, len(newOut))
for _, e := range newOut {
newByTag[e.tag] = e
}
for _, oldE := range oldOut {
newE, exists := newByTag[oldE.tag]
if exists && bytes.Equal(oldE.norm, newE.norm) {
continue
}
diff.RemovedOutboundTags = append(diff.RemovedOutboundTags, oldE.tag)
if exists {
diff.AddedOutbounds = append(diff.AddedOutbounds, newE.raw)
}
}
for _, newE := range newOut {
if _, exists := oldByTag[newE.tag]; !exists {
diff.AddedOutbounds = append(diff.AddedOutbounds, newE.raw)
}
}
return true
}
// diffRouting decides whether the routing change is limited to rules and
// balancers — the only parts RoutingService.AddRule can replace at runtime.
// domainStrategy/domainMatcher and any other key in the section are fixed at
// process start.
func diffRouting(oldCfg, newCfg *Config, diff *HotDiff) bool {
if bytes.Equal(oldCfg.RouterConfig, newCfg.RouterConfig) {
return true
}
// No routing section at start likely means no router feature (and no
// RoutingService) in the running instance — only a restart can add it.
if len(oldCfg.RouterConfig) == 0 || len(newCfg.RouterConfig) == 0 {
return false
}
oldRest, ok := routingWithoutReloadable(oldCfg.RouterConfig)
if !ok {
return false
}
newRest, ok := routingWithoutReloadable(newCfg.RouterConfig)
if !ok {
return false
}
if !bytes.Equal(oldRest, newRest) {
return false
}
diff.RoutingConfig = newCfg.RouterConfig
return true
}
// routingWithoutReloadable returns the routing section normalized with the
// runtime-reloadable keys removed, for comparing the restart-only remainder.
func routingWithoutReloadable(raw []byte) ([]byte, bool) {
parsed := map[string]any{}
if len(raw) > 0 {
decoder := json.NewDecoder(bytes.NewReader(raw))
decoder.UseNumber()
if err := decoder.Decode(&parsed); err != nil {
return nil, false
}
}
delete(parsed, "rules")
delete(parsed, "balancers")
out, err := json.Marshal(parsed)
if err != nil {
return nil, false
}
return out, true
}
// inboundEqualNormalized compares two inbounds ignoring JSON formatting in
// their raw sections, so a reformatted template does not read as a changed
// inbound.
func inboundEqualNormalized(a, b *InboundConfig) bool {
return a.Port == b.Port &&
a.Protocol == b.Protocol &&
a.Tag == b.Tag &&
rawEqualNormalized(a.Listen, b.Listen) &&
rawEqualNormalized(a.Settings, b.Settings) &&
rawEqualNormalized(a.StreamSettings, b.StreamSettings) &&
rawEqualNormalized(a.Sniffing, b.Sniffing)
}
// rawEqualNormalized reports whether two raw JSON values are semantically
// equal: whitespace, object key order and an explicit `null` versus an
// absent section are all ignored. UI editors rebuild objects on save (new
// key order) and emit `null` for switched-off sections — none of that is a
// reason to restart the core. Number precision is preserved via json.Number,
// so genuinely different values never compare equal. Unparsable values only
// compare equal byte-for-byte.
func rawEqualNormalized(a, b json_util.RawMessage) bool {
if bytes.Equal(a, b) {
return true
}
na, ok := canonicalJSON(a)
if !ok {
return false
}
nb, ok := canonicalJSON(b)
if !ok {
return false
}
return bytes.Equal(na, nb)
}
// canonicalJSON renders a JSON value in canonical form: sorted object keys,
// no insignificant whitespace, exact number digits (json.Number). Empty
// input and JSON null both canonicalize to nil.
func canonicalJSON(raw json_util.RawMessage) ([]byte, bool) {
if len(raw) == 0 {
return nil, true
}
decoder := json.NewDecoder(bytes.NewReader(raw))
decoder.UseNumber()
var value any
if err := decoder.Decode(&value); err != nil {
return nil, false
}
if value == nil {
return nil, true
}
out, err := json.Marshal(value)
if err != nil {
return nil, false
}
return out, true
}
// inboundsByTag indexes inbounds by tag; ok is false when a tag is empty or
// duplicated, since such handlers can't be addressed through the API.
func inboundsByTag(inbounds []InboundConfig) (map[string]*InboundConfig, bool) {
byTag := make(map[string]*InboundConfig, len(inbounds))
for i := range inbounds {
tag := inbounds[i].Tag
if tag == "" {
return nil, false
}
if _, dup := byTag[tag]; dup {
return nil, false
}
byTag[tag] = &inbounds[i]
}
return byTag, true
}
type outboundEntry struct {
tag string
raw []byte // original JSON, used for AddOutbound
norm []byte // canonical JSON, used for change detection
}
// parseOutbounds splits the outbounds array into per-entry raw/normalized
// JSON. ok is false when the array is unparsable or an entry has an empty or
// duplicate tag — those can't be addressed through the API.
func parseOutbounds(raw json_util.RawMessage) ([]outboundEntry, bool) {
if len(raw) == 0 {
return nil, true
}
var elems []json.RawMessage
if err := json.Unmarshal(raw, &elems); err != nil {
return nil, false
}
entries := make([]outboundEntry, 0, len(elems))
seen := make(map[string]struct{}, len(elems))
for _, elem := range elems {
var meta struct {
Tag string `json:"tag"`
}
if err := json.Unmarshal(elem, &meta); err != nil {
return nil, false
}
if meta.Tag == "" {
return nil, false
}
if _, dup := seen[meta.Tag]; dup {
return nil, false
}
seen[meta.Tag] = struct{}{}
norm, ok := canonicalJSON(json_util.RawMessage(elem))
if !ok {
return nil, false
}
entries = append(entries, outboundEntry{tag: meta.Tag, raw: elem, norm: norm})
}
return entries, true
}
// apiTagFromConfig extracts api.tag from the api section, defaulting to "api".
func apiTagFromConfig(api json_util.RawMessage) string {
var parsed struct {
Tag string `json:"tag"`
}
if len(api) > 0 && json.Unmarshal(api, &parsed) == nil && parsed.Tag != "" {
return parsed.Tag
}
return "api"
}