hot_diff.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. package xray
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  6. "github.com/mhsanaei/3x-ui/v3/internal/util/json_util"
  7. )
  8. // HotDiff describes the gRPC API operations needed to bring a running Xray
  9. // instance from one generated config to another without restarting the
  10. // process. It only covers the sections Xray can reload at runtime: inbounds,
  11. // outbounds and routing rules/balancers.
  12. type HotDiff struct {
  13. RemovedInboundTags []string
  14. AddedInbounds [][]byte
  15. RemovedUsers []UserOp
  16. AddedUsers []UserOp
  17. // DroppedClients are emails an inbound that survives the change stopped
  18. // serving, including the protocols diffInboundUsers will not diff.
  19. DroppedClients []UserOp
  20. RemovedOutboundTags []string
  21. AddedOutbounds [][]byte
  22. RoutingConfig []byte // full new routing section; nil when unchanged
  23. }
  24. // UserOp is a per-user AlterInbound operation; User is nil for removals.
  25. type UserOp struct {
  26. Tag string
  27. Protocol string
  28. Email string
  29. User map[string]any
  30. }
  31. // DropsUsers reports users removed without being re-added under the same tag:
  32. // a disable or a delete, where an edit re-adds the email with new values.
  33. func (d *HotDiff) DropsUsers() bool {
  34. if len(d.DroppedClients) > 0 {
  35. return true
  36. }
  37. if len(d.RemovedUsers) == 0 {
  38. return false
  39. }
  40. readded := make(map[string]struct{}, len(d.AddedUsers))
  41. for _, u := range d.AddedUsers {
  42. readded[u.Tag+"\x00"+u.Email] = struct{}{}
  43. }
  44. for _, u := range d.RemovedUsers {
  45. if _, ok := readded[u.Tag+"\x00"+u.Email]; !ok {
  46. return true
  47. }
  48. }
  49. return false
  50. }
  51. // Empty reports whether the diff contains no operations.
  52. func (d *HotDiff) Empty() bool {
  53. return len(d.RemovedInboundTags) == 0 &&
  54. len(d.AddedInbounds) == 0 &&
  55. len(d.RemovedUsers) == 0 &&
  56. len(d.AddedUsers) == 0 &&
  57. len(d.RemovedOutboundTags) == 0 &&
  58. len(d.AddedOutbounds) == 0 &&
  59. d.RoutingConfig == nil
  60. }
  61. // ComputeHotDiff compares two generated configs and returns the API operations
  62. // that transform a running instance from oldCfg to newCfg. ok is false when
  63. // the change touches anything that has no runtime reload API (log, dns,
  64. // policy, ...) and therefore requires a full process restart.
  65. func ComputeHotDiff(oldCfg, newCfg *Config) (*HotDiff, bool) {
  66. if oldCfg == nil || newCfg == nil {
  67. return nil, false
  68. }
  69. // Sections without a reload API must be semantically identical.
  70. // Comparison is whitespace-insensitive: a template save that merely
  71. // reformats the JSON (frontend textarea, API clients) must not be
  72. // mistaken for a real change that forces a restart.
  73. static := []struct {
  74. name string
  75. old, new json_util.RawMessage
  76. }{
  77. {"log", oldCfg.LogConfig, newCfg.LogConfig},
  78. {"dns", oldCfg.DNSConfig, newCfg.DNSConfig},
  79. {"transport", oldCfg.Transport, newCfg.Transport},
  80. {"policy", oldCfg.Policy, newCfg.Policy},
  81. {"api", oldCfg.API, newCfg.API},
  82. {"stats", oldCfg.Stats, newCfg.Stats},
  83. {"reverse", oldCfg.Reverse, newCfg.Reverse},
  84. {"fakedns", oldCfg.FakeDNS, newCfg.FakeDNS},
  85. {"observatory", oldCfg.Observatory, newCfg.Observatory},
  86. {"burstObservatory", oldCfg.BurstObservatory, newCfg.BurstObservatory},
  87. {"metrics", oldCfg.Metrics, newCfg.Metrics},
  88. {"geodata", oldCfg.Geodata, newCfg.Geodata},
  89. {"env", oldCfg.Env, newCfg.Env},
  90. }
  91. for _, section := range static {
  92. if !rawEqualNormalized(section.old, section.new) {
  93. logger.Debug("hot diff: section [", section.name, "] changed and has no reload API")
  94. return nil, false
  95. }
  96. }
  97. diff := &HotDiff{}
  98. if ok := diffInbounds(oldCfg, newCfg, diff); !ok {
  99. logger.Debug("hot diff: inbound change is not API-applicable")
  100. return nil, false
  101. }
  102. if ok := diffOutbounds(oldCfg, newCfg, diff); !ok {
  103. logger.Debug("hot diff: outbound change is not API-applicable (default outbound or tags)")
  104. return nil, false
  105. }
  106. if ok := diffRouting(oldCfg, newCfg, diff); !ok {
  107. logger.Debug("hot diff: routing change is not API-applicable (domainStrategy or section shape)")
  108. return nil, false
  109. }
  110. return diff, true
  111. }
  112. // diffInbounds fills diff with inbound removals/additions (a changed inbound
  113. // becomes remove+add). The api inbound carries the gRPC server the panel is
  114. // talking through, so any change touching it forces a restart.
  115. func diffInbounds(oldCfg, newCfg *Config, diff *HotDiff) bool {
  116. oldByTag, ok := inboundsByTag(oldCfg.InboundConfigs)
  117. if !ok {
  118. return false
  119. }
  120. newByTag, ok := inboundsByTag(newCfg.InboundConfigs)
  121. if !ok {
  122. return false
  123. }
  124. apiTag := apiTagFromConfig(newCfg.API)
  125. for i := range oldCfg.InboundConfigs {
  126. oldIb := &oldCfg.InboundConfigs[i]
  127. newIb, exists := newByTag[oldIb.Tag]
  128. if exists && inboundEqualNormalized(oldIb, newIb) {
  129. continue
  130. }
  131. if oldIb.Tag == apiTag || oldIb.Tag == "api" {
  132. return false
  133. }
  134. if exists && (inboundHasReverseClient(oldIb) || inboundHasReverseClient(newIb)) {
  135. logger.Debug("hot diff: inbound [", oldIb.Tag, "] carries a reverse-tagged client, forcing a full restart instead of a hot swap")
  136. return false
  137. }
  138. if exists {
  139. diff.DroppedClients = append(diff.DroppedClients, droppedClients(oldIb, newIb)...)
  140. }
  141. if exists && diffInboundUsers(oldIb, newIb, diff) {
  142. continue
  143. }
  144. if exists && (inboundUsesReality(oldIb) || inboundUsesReality(newIb)) {
  145. 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")
  146. return false
  147. }
  148. if exists && (inboundUsesTproxy(oldIb) || inboundUsesTproxy(newIb)) {
  149. logger.Debug("hot diff: inbound [", oldIb.Tag, "] is a TPROXY target; a gRPC add reports success but does not reliably bind a working listener, forcing a full restart instead of a hot swap")
  150. return false
  151. }
  152. if exists && (inboundUsesSocksAccounts(oldIb) || inboundUsesSocksAccounts(newIb)) {
  153. logger.Debug("hot diff: inbound [", oldIb.Tag, "] is a password-auth SOCKS5 inbound (e.g. internal/amneziawgnet's per-peer relay); a gRPC remove+add reports success but was observed in production to silently drop an account, forcing a full restart instead of a hot swap")
  154. return false
  155. }
  156. diff.RemovedInboundTags = append(diff.RemovedInboundTags, oldIb.Tag)
  157. if exists {
  158. raw, err := json.Marshal(newIb)
  159. if err != nil {
  160. return false
  161. }
  162. diff.AddedInbounds = append(diff.AddedInbounds, raw)
  163. }
  164. }
  165. for i := range newCfg.InboundConfigs {
  166. newIb := &newCfg.InboundConfigs[i]
  167. if _, exists := oldByTag[newIb.Tag]; exists {
  168. continue
  169. }
  170. if newIb.Tag == apiTag || newIb.Tag == "api" {
  171. return false
  172. }
  173. if inboundUsesTproxy(newIb) {
  174. logger.Debug("hot diff: new inbound [", newIb.Tag, "] is a TPROXY target (e.g. internal/amneziawg's Xray egress bridge); a gRPC add reports success but does not reliably bind a working listener, forcing a full restart instead of a hot add")
  175. return false
  176. }
  177. if inboundUsesSocksAccounts(newIb) {
  178. logger.Debug("hot diff: new inbound [", newIb.Tag, "] is a password-auth SOCKS5 inbound (e.g. internal/amneziawgnet's per-peer relay); forcing a full restart instead of a hot add, same reasoning as the existing-inbound case above")
  179. return false
  180. }
  181. raw, err := json.Marshal(newIb)
  182. if err != nil {
  183. return false
  184. }
  185. diff.AddedInbounds = append(diff.AddedInbounds, raw)
  186. }
  187. return true
  188. }
  189. // droppedClients lists the emails an inbound present in both configs stopped
  190. // serving, whatever its protocol: settings.clients is the shape they all share.
  191. func droppedClients(oldIb, newIb *InboundConfig) []UserOp {
  192. oldClients, _, ok := splitSettingsClients(oldIb.Settings)
  193. if !ok {
  194. return nil
  195. }
  196. newClients, _, ok := splitSettingsClients(newIb.Settings)
  197. if !ok {
  198. return nil
  199. }
  200. var dropped []UserOp
  201. for email := range oldClients {
  202. if _, still := newClients[email]; !still {
  203. dropped = append(dropped, UserOp{Tag: newIb.Tag, Protocol: newIb.Protocol, Email: email})
  204. }
  205. }
  206. return dropped
  207. }
  208. // InboundUserOps returns the per-user ops that bring a running inbound from oldIb
  209. // to newIb; ok is false when only rebuilding its handler can apply the change.
  210. func InboundUserOps(oldIb, newIb *InboundConfig) (*HotDiff, bool) {
  211. diff := &HotDiff{}
  212. if inboundEqualNormalized(oldIb, newIb) {
  213. return diff, true
  214. }
  215. if !diffInboundUsers(oldIb, newIb, diff) {
  216. return nil, false
  217. }
  218. return diff, true
  219. }
  220. var userDiffableProtocols = map[string]struct{}{"vless": {}, "vmess": {}, "trojan": {}, "hysteria": {}, "masque": {}}
  221. // diffInboundUsers emits per-user AlterInbound ops when two same-tag inbounds
  222. // differ only in settings.clients, so the handler (and its listener) survives.
  223. func diffInboundUsers(oldIb, newIb *InboundConfig, diff *HotDiff) bool {
  224. if oldIb.Port != newIb.Port || oldIb.Protocol != newIb.Protocol || oldIb.Tag != newIb.Tag {
  225. return false
  226. }
  227. if _, ok := userDiffableProtocols[oldIb.Protocol]; !ok {
  228. return false
  229. }
  230. if !rawEqualNormalized(oldIb.Listen, newIb.Listen) ||
  231. !rawEqualNormalized(oldIb.StreamSettings, newIb.StreamSettings) ||
  232. !rawEqualNormalized(oldIb.Sniffing, newIb.Sniffing) {
  233. return false
  234. }
  235. oldClients, oldRest, ok := splitSettingsClients(oldIb.Settings)
  236. if !ok {
  237. return false
  238. }
  239. newClients, newRest, ok := splitSettingsClients(newIb.Settings)
  240. if !ok {
  241. return false
  242. }
  243. if !bytes.Equal(oldRest, newRest) {
  244. return false
  245. }
  246. for email, oldC := range oldClients {
  247. newC, exists := newClients[email]
  248. if exists && bytes.Equal(oldC.norm, newC.norm) {
  249. continue
  250. }
  251. diff.RemovedUsers = append(diff.RemovedUsers, UserOp{Tag: oldIb.Tag, Protocol: oldIb.Protocol, Email: email})
  252. if exists {
  253. diff.AddedUsers = append(diff.AddedUsers, UserOp{Tag: oldIb.Tag, Protocol: oldIb.Protocol, Email: email, User: newC.user})
  254. }
  255. }
  256. for email, newC := range newClients {
  257. if _, exists := oldClients[email]; !exists {
  258. diff.AddedUsers = append(diff.AddedUsers, UserOp{Tag: oldIb.Tag, Protocol: oldIb.Protocol, Email: email, User: newC.user})
  259. }
  260. }
  261. return true
  262. }
  263. type clientEntry struct {
  264. user map[string]any
  265. norm []byte
  266. }
  267. // splitSettingsClients indexes settings.clients by email and returns the rest of
  268. // the settings in canonical form; ok is false when a client has no unique email.
  269. func splitSettingsClients(raw json_util.RawMessage) (map[string]clientEntry, []byte, bool) {
  270. if len(raw) == 0 {
  271. return nil, nil, false
  272. }
  273. settings := map[string]any{}
  274. decoder := json.NewDecoder(bytes.NewReader(raw))
  275. decoder.UseNumber()
  276. if err := decoder.Decode(&settings); err != nil {
  277. return nil, nil, false
  278. }
  279. clientsRaw, hasClients := settings["clients"].([]any)
  280. if !hasClients {
  281. return nil, nil, false
  282. }
  283. clients := make(map[string]clientEntry, len(clientsRaw))
  284. for _, c := range clientsRaw {
  285. obj, ok := c.(map[string]any)
  286. if !ok {
  287. return nil, nil, false
  288. }
  289. email, _ := obj["email"].(string)
  290. if email == "" {
  291. return nil, nil, false
  292. }
  293. if _, dup := clients[email]; dup {
  294. return nil, nil, false
  295. }
  296. norm, err := json.Marshal(obj)
  297. if err != nil {
  298. return nil, nil, false
  299. }
  300. clients[email] = clientEntry{user: obj, norm: norm}
  301. }
  302. delete(settings, "clients")
  303. rest, err := json.Marshal(settings)
  304. if err != nil {
  305. return nil, nil, false
  306. }
  307. return clients, rest, true
  308. }
  309. func inboundUsesReality(ib *InboundConfig) bool {
  310. if ib == nil || len(ib.StreamSettings) == 0 {
  311. return false
  312. }
  313. var stream struct {
  314. Security string `json:"security"`
  315. }
  316. if err := json.Unmarshal(ib.StreamSettings, &stream); err != nil {
  317. return false
  318. }
  319. return stream.Security == "reality"
  320. }
  321. // inboundUsesTproxy: a sockopt.tproxy inbound (the tunnel protocol's TProxy
  322. // mode) hot-adds over gRPC "successfully" but binds no listener — restart.
  323. func inboundUsesTproxy(ib *InboundConfig) bool {
  324. if ib == nil || len(ib.StreamSettings) == 0 {
  325. return false
  326. }
  327. var stream struct {
  328. Sockopt struct {
  329. Tproxy string `json:"tproxy"`
  330. } `json:"sockopt"`
  331. }
  332. if err := json.Unmarshal(ib.StreamSettings, &stream); err != nil {
  333. return false
  334. }
  335. return stream.Sockopt.Tproxy != "" && stream.Sockopt.Tproxy != "off"
  336. }
  337. // inboundUsesSocksAccounts reports whether an inbound is a password-auth
  338. // SOCKS5 inbound with one or more named accounts -- the shape
  339. // internal/amneziawgnet's per-inbound relay (internal/web/service/xray.go's
  340. // injectAmneziawgnetSocks) is the only generator of in this fork; every
  341. // other SOCKS5 bridge this fork builds (panel egress, per-node egress,
  342. // mtproto egress) uses "noauth" with no per-account identity at all, so this
  343. // check can't accidentally rope in one of those lower-churn bridges.
  344. //
  345. // Real production incident, not a theoretical concern: a single client
  346. // edit under an AmneziaWG inbound left this inbound's settings unchanged in
  347. // every way relevant to accounts.user was already correct in the freshly
  348. // regenerated config, yet the account for a peer whose email contained
  349. // non-ASCII characters silently vanished from the running Xray process
  350. // after a gRPC remove+add hot swap -- while a full process restart (reading
  351. // the same JSON straight from disk) always produced the correct account
  352. // list. socks isn't in userDiffableProtocols (that only covers vless/vmess/
  353. // trojan, which use a wholly different clients+email shape, not
  354. // accounts+user), so without this check any settings drift on this inbound
  355. // -- even one unrelated to the account list itself -- falls through to the
  356. // generic remove+add path and can reproduce the same silent drop. Forcing a
  357. // full restart here is the same defensive choice already made above for
  358. // REALITY and TPROXY.
  359. func inboundUsesSocksAccounts(ib *InboundConfig) bool {
  360. if ib == nil || ib.Protocol != "socks" || len(ib.Settings) == 0 {
  361. return false
  362. }
  363. var settings struct {
  364. Auth string `json:"auth"`
  365. }
  366. if err := json.Unmarshal(ib.Settings, &settings); err != nil {
  367. return false
  368. }
  369. return settings.Auth == "password"
  370. }
  371. func inboundHasReverseClient(ib *InboundConfig) bool {
  372. if ib == nil {
  373. return false
  374. }
  375. var settings struct {
  376. Clients []struct {
  377. Reverse json.RawMessage `json:"reverse"`
  378. } `json:"clients"`
  379. }
  380. if err := json.Unmarshal(ib.Settings, &settings); err != nil {
  381. return false
  382. }
  383. for _, c := range settings.Clients {
  384. if len(c.Reverse) == 0 {
  385. continue
  386. }
  387. var tag any
  388. if err := json.Unmarshal(c.Reverse, &tag); err != nil || tag == nil {
  389. continue
  390. }
  391. return true
  392. }
  393. return false
  394. }
  395. // diffOutbounds fills diff with outbound removals/additions keyed by tag.
  396. // The first outbound is xray's default handler and the API can only append,
  397. // so any change to its identity or content forces a restart. Reordering of
  398. // the remaining outbounds is ignored — routing addresses them by tag.
  399. func diffOutbounds(oldCfg, newCfg *Config, diff *HotDiff) bool {
  400. oldOut, ok := parseOutbounds(oldCfg.OutboundConfigs)
  401. if !ok {
  402. return false
  403. }
  404. newOut, ok := parseOutbounds(newCfg.OutboundConfigs)
  405. if !ok {
  406. return false
  407. }
  408. if (len(oldOut) == 0) != (len(newOut) == 0) {
  409. return false
  410. }
  411. if len(oldOut) > 0 {
  412. if oldOut[0].tag != newOut[0].tag || !bytes.Equal(oldOut[0].norm, newOut[0].norm) {
  413. return false
  414. }
  415. }
  416. oldByTag := make(map[string]outboundEntry, len(oldOut))
  417. for _, e := range oldOut {
  418. oldByTag[e.tag] = e
  419. }
  420. newByTag := make(map[string]outboundEntry, len(newOut))
  421. for _, e := range newOut {
  422. newByTag[e.tag] = e
  423. }
  424. for _, oldE := range oldOut {
  425. newE, exists := newByTag[oldE.tag]
  426. if exists && bytes.Equal(oldE.norm, newE.norm) {
  427. continue
  428. }
  429. diff.RemovedOutboundTags = append(diff.RemovedOutboundTags, oldE.tag)
  430. if exists {
  431. diff.AddedOutbounds = append(diff.AddedOutbounds, newE.raw)
  432. }
  433. }
  434. for _, newE := range newOut {
  435. if _, exists := oldByTag[newE.tag]; !exists {
  436. diff.AddedOutbounds = append(diff.AddedOutbounds, newE.raw)
  437. }
  438. }
  439. return true
  440. }
  441. // diffRouting decides whether the routing change is limited to rules and
  442. // balancers — the only parts RoutingService.AddRule can replace at runtime.
  443. // domainStrategy/domainMatcher and any other key in the section are fixed at
  444. // process start.
  445. func diffRouting(oldCfg, newCfg *Config, diff *HotDiff) bool {
  446. if bytes.Equal(oldCfg.RouterConfig, newCfg.RouterConfig) {
  447. return true
  448. }
  449. // No routing section at start likely means no router feature (and no
  450. // RoutingService) in the running instance — only a restart can add it.
  451. if len(oldCfg.RouterConfig) == 0 || len(newCfg.RouterConfig) == 0 {
  452. return false
  453. }
  454. oldRest, ok := routingWithoutReloadable(oldCfg.RouterConfig)
  455. if !ok {
  456. return false
  457. }
  458. newRest, ok := routingWithoutReloadable(newCfg.RouterConfig)
  459. if !ok {
  460. return false
  461. }
  462. if !bytes.Equal(oldRest, newRest) {
  463. return false
  464. }
  465. diff.RoutingConfig = newCfg.RouterConfig
  466. return true
  467. }
  468. // routingWithoutReloadable returns the routing section normalized with the
  469. // runtime-reloadable keys removed, for comparing the restart-only remainder.
  470. func routingWithoutReloadable(raw []byte) ([]byte, bool) {
  471. parsed := map[string]any{}
  472. if len(raw) > 0 {
  473. decoder := json.NewDecoder(bytes.NewReader(raw))
  474. decoder.UseNumber()
  475. if err := decoder.Decode(&parsed); err != nil {
  476. return nil, false
  477. }
  478. }
  479. delete(parsed, "rules")
  480. delete(parsed, "balancers")
  481. out, err := json.Marshal(parsed)
  482. if err != nil {
  483. return nil, false
  484. }
  485. return out, true
  486. }
  487. // inboundEqualNormalized compares two inbounds ignoring JSON formatting in
  488. // their raw sections, so a reformatted template does not read as a changed
  489. // inbound.
  490. func inboundEqualNormalized(a, b *InboundConfig) bool {
  491. return a.Port == b.Port &&
  492. a.Protocol == b.Protocol &&
  493. a.Tag == b.Tag &&
  494. rawEqualNormalized(a.Listen, b.Listen) &&
  495. rawEqualNormalized(a.Settings, b.Settings) &&
  496. rawEqualNormalized(a.StreamSettings, b.StreamSettings) &&
  497. rawEqualNormalized(a.Sniffing, b.Sniffing)
  498. }
  499. // rawEqualNormalized reports whether two raw JSON values are semantically
  500. // equal: whitespace, object key order and an explicit `null` versus an
  501. // absent section are all ignored. UI editors rebuild objects on save (new
  502. // key order) and emit `null` for switched-off sections — none of that is a
  503. // reason to restart the core. Number precision is preserved via json.Number,
  504. // so genuinely different values never compare equal. Unparsable values only
  505. // compare equal byte-for-byte.
  506. func rawEqualNormalized(a, b json_util.RawMessage) bool {
  507. if bytes.Equal(a, b) {
  508. return true
  509. }
  510. na, ok := canonicalJSON(a)
  511. if !ok {
  512. return false
  513. }
  514. nb, ok := canonicalJSON(b)
  515. if !ok {
  516. return false
  517. }
  518. return bytes.Equal(na, nb)
  519. }
  520. // canonicalJSON renders a JSON value in canonical form: sorted object keys,
  521. // no insignificant whitespace, exact number digits (json.Number). Empty
  522. // input and JSON null both canonicalize to nil.
  523. func canonicalJSON(raw json_util.RawMessage) ([]byte, bool) {
  524. if len(raw) == 0 {
  525. return nil, true
  526. }
  527. decoder := json.NewDecoder(bytes.NewReader(raw))
  528. decoder.UseNumber()
  529. var value any
  530. if err := decoder.Decode(&value); err != nil {
  531. return nil, false
  532. }
  533. if value == nil {
  534. return nil, true
  535. }
  536. out, err := json.Marshal(value)
  537. if err != nil {
  538. return nil, false
  539. }
  540. return out, true
  541. }
  542. // inboundsByTag indexes inbounds by tag; ok is false when a tag is empty or
  543. // duplicated, since such handlers can't be addressed through the API.
  544. func inboundsByTag(inbounds []InboundConfig) (map[string]*InboundConfig, bool) {
  545. byTag := make(map[string]*InboundConfig, len(inbounds))
  546. for i := range inbounds {
  547. tag := inbounds[i].Tag
  548. if tag == "" {
  549. return nil, false
  550. }
  551. if _, dup := byTag[tag]; dup {
  552. return nil, false
  553. }
  554. byTag[tag] = &inbounds[i]
  555. }
  556. return byTag, true
  557. }
  558. type outboundEntry struct {
  559. tag string
  560. raw []byte // original JSON, used for AddOutbound
  561. norm []byte // canonical JSON, used for change detection
  562. }
  563. // parseOutbounds splits the outbounds array into per-entry raw/normalized
  564. // JSON. ok is false when the array is unparsable or an entry has an empty or
  565. // duplicate tag — those can't be addressed through the API.
  566. func parseOutbounds(raw json_util.RawMessage) ([]outboundEntry, bool) {
  567. if len(raw) == 0 {
  568. return nil, true
  569. }
  570. var elems []json.RawMessage
  571. if err := json.Unmarshal(raw, &elems); err != nil {
  572. return nil, false
  573. }
  574. entries := make([]outboundEntry, 0, len(elems))
  575. seen := make(map[string]struct{}, len(elems))
  576. for _, elem := range elems {
  577. var meta struct {
  578. Tag string `json:"tag"`
  579. }
  580. if err := json.Unmarshal(elem, &meta); err != nil {
  581. return nil, false
  582. }
  583. if meta.Tag == "" {
  584. return nil, false
  585. }
  586. if _, dup := seen[meta.Tag]; dup {
  587. return nil, false
  588. }
  589. seen[meta.Tag] = struct{}{}
  590. norm, ok := canonicalJSON(json_util.RawMessage(elem))
  591. if !ok {
  592. return nil, false
  593. }
  594. entries = append(entries, outboundEntry{tag: meta.Tag, raw: elem, norm: norm})
  595. }
  596. return entries, true
  597. }
  598. // apiTagFromConfig extracts api.tag from the api section, defaulting to "api".
  599. func apiTagFromConfig(api json_util.RawMessage) string {
  600. var parsed struct {
  601. Tag string `json:"tag"`
  602. }
  603. if len(api) > 0 && json.Unmarshal(api, &parsed) == nil && parsed.Tag != "" {
  604. return parsed.Tag
  605. }
  606. return "api"
  607. }