hot_diff.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  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. var userDiffableProtocols = map[string]struct{}{"vless": {}, "vmess": {}, "trojan": {}}
  209. // diffInboundUsers emits per-user AlterInbound ops when two same-tag inbounds
  210. // differ only in settings.clients, so the handler (and its listener) survives.
  211. func diffInboundUsers(oldIb, newIb *InboundConfig, diff *HotDiff) bool {
  212. if oldIb.Port != newIb.Port || oldIb.Protocol != newIb.Protocol || oldIb.Tag != newIb.Tag {
  213. return false
  214. }
  215. if _, ok := userDiffableProtocols[oldIb.Protocol]; !ok {
  216. return false
  217. }
  218. if !rawEqualNormalized(oldIb.Listen, newIb.Listen) ||
  219. !rawEqualNormalized(oldIb.StreamSettings, newIb.StreamSettings) ||
  220. !rawEqualNormalized(oldIb.Sniffing, newIb.Sniffing) {
  221. return false
  222. }
  223. oldClients, oldRest, ok := splitSettingsClients(oldIb.Settings)
  224. if !ok {
  225. return false
  226. }
  227. newClients, newRest, ok := splitSettingsClients(newIb.Settings)
  228. if !ok {
  229. return false
  230. }
  231. if !bytes.Equal(oldRest, newRest) {
  232. return false
  233. }
  234. for email, oldC := range oldClients {
  235. newC, exists := newClients[email]
  236. if exists && bytes.Equal(oldC.norm, newC.norm) {
  237. continue
  238. }
  239. diff.RemovedUsers = append(diff.RemovedUsers, UserOp{Tag: oldIb.Tag, Protocol: oldIb.Protocol, Email: email})
  240. if exists {
  241. diff.AddedUsers = append(diff.AddedUsers, UserOp{Tag: oldIb.Tag, Protocol: oldIb.Protocol, Email: email, User: newC.user})
  242. }
  243. }
  244. for email, newC := range newClients {
  245. if _, exists := oldClients[email]; !exists {
  246. diff.AddedUsers = append(diff.AddedUsers, UserOp{Tag: oldIb.Tag, Protocol: oldIb.Protocol, Email: email, User: newC.user})
  247. }
  248. }
  249. return true
  250. }
  251. type clientEntry struct {
  252. user map[string]any
  253. norm []byte
  254. }
  255. // splitSettingsClients indexes settings.clients by email and returns the rest of
  256. // the settings in canonical form; ok is false when a client has no unique email.
  257. func splitSettingsClients(raw json_util.RawMessage) (map[string]clientEntry, []byte, bool) {
  258. if len(raw) == 0 {
  259. return nil, nil, false
  260. }
  261. settings := map[string]any{}
  262. decoder := json.NewDecoder(bytes.NewReader(raw))
  263. decoder.UseNumber()
  264. if err := decoder.Decode(&settings); err != nil {
  265. return nil, nil, false
  266. }
  267. clientsRaw, hasClients := settings["clients"].([]any)
  268. if !hasClients {
  269. return nil, nil, false
  270. }
  271. clients := make(map[string]clientEntry, len(clientsRaw))
  272. for _, c := range clientsRaw {
  273. obj, ok := c.(map[string]any)
  274. if !ok {
  275. return nil, nil, false
  276. }
  277. email, _ := obj["email"].(string)
  278. if email == "" {
  279. return nil, nil, false
  280. }
  281. if _, dup := clients[email]; dup {
  282. return nil, nil, false
  283. }
  284. norm, err := json.Marshal(obj)
  285. if err != nil {
  286. return nil, nil, false
  287. }
  288. clients[email] = clientEntry{user: obj, norm: norm}
  289. }
  290. delete(settings, "clients")
  291. rest, err := json.Marshal(settings)
  292. if err != nil {
  293. return nil, nil, false
  294. }
  295. return clients, rest, true
  296. }
  297. func inboundUsesReality(ib *InboundConfig) bool {
  298. if ib == nil || len(ib.StreamSettings) == 0 {
  299. return false
  300. }
  301. var stream struct {
  302. Security string `json:"security"`
  303. }
  304. if err := json.Unmarshal(ib.StreamSettings, &stream); err != nil {
  305. return false
  306. }
  307. return stream.Security == "reality"
  308. }
  309. // inboundUsesTproxy: a sockopt.tproxy inbound (the tunnel protocol's TProxy
  310. // mode) hot-adds over gRPC "successfully" but binds no listener — restart.
  311. func inboundUsesTproxy(ib *InboundConfig) bool {
  312. if ib == nil || len(ib.StreamSettings) == 0 {
  313. return false
  314. }
  315. var stream struct {
  316. Sockopt struct {
  317. Tproxy string `json:"tproxy"`
  318. } `json:"sockopt"`
  319. }
  320. if err := json.Unmarshal(ib.StreamSettings, &stream); err != nil {
  321. return false
  322. }
  323. return stream.Sockopt.Tproxy != "" && stream.Sockopt.Tproxy != "off"
  324. }
  325. // inboundUsesSocksAccounts reports whether an inbound is a password-auth
  326. // SOCKS5 inbound with one or more named accounts -- the shape
  327. // internal/amneziawgnet's per-inbound relay (internal/web/service/xray.go's
  328. // injectAmneziawgnetSocks) is the only generator of in this fork; every
  329. // other SOCKS5 bridge this fork builds (panel egress, per-node egress,
  330. // mtproto egress) uses "noauth" with no per-account identity at all, so this
  331. // check can't accidentally rope in one of those lower-churn bridges.
  332. //
  333. // Real production incident, not a theoretical concern: a single client
  334. // edit under an AmneziaWG inbound left this inbound's settings unchanged in
  335. // every way relevant to accounts.user was already correct in the freshly
  336. // regenerated config, yet the account for a peer whose email contained
  337. // non-ASCII characters silently vanished from the running Xray process
  338. // after a gRPC remove+add hot swap -- while a full process restart (reading
  339. // the same JSON straight from disk) always produced the correct account
  340. // list. socks isn't in userDiffableProtocols (that only covers vless/vmess/
  341. // trojan, which use a wholly different clients+email shape, not
  342. // accounts+user), so without this check any settings drift on this inbound
  343. // -- even one unrelated to the account list itself -- falls through to the
  344. // generic remove+add path and can reproduce the same silent drop. Forcing a
  345. // full restart here is the same defensive choice already made above for
  346. // REALITY and TPROXY.
  347. func inboundUsesSocksAccounts(ib *InboundConfig) bool {
  348. if ib == nil || ib.Protocol != "socks" || len(ib.Settings) == 0 {
  349. return false
  350. }
  351. var settings struct {
  352. Auth string `json:"auth"`
  353. }
  354. if err := json.Unmarshal(ib.Settings, &settings); err != nil {
  355. return false
  356. }
  357. return settings.Auth == "password"
  358. }
  359. func inboundHasReverseClient(ib *InboundConfig) bool {
  360. if ib == nil {
  361. return false
  362. }
  363. var settings struct {
  364. Clients []struct {
  365. Reverse json.RawMessage `json:"reverse"`
  366. } `json:"clients"`
  367. }
  368. if err := json.Unmarshal(ib.Settings, &settings); err != nil {
  369. return false
  370. }
  371. for _, c := range settings.Clients {
  372. if len(c.Reverse) == 0 {
  373. continue
  374. }
  375. var tag any
  376. if err := json.Unmarshal(c.Reverse, &tag); err != nil || tag == nil {
  377. continue
  378. }
  379. return true
  380. }
  381. return false
  382. }
  383. // diffOutbounds fills diff with outbound removals/additions keyed by tag.
  384. // The first outbound is xray's default handler and the API can only append,
  385. // so any change to its identity or content forces a restart. Reordering of
  386. // the remaining outbounds is ignored — routing addresses them by tag.
  387. func diffOutbounds(oldCfg, newCfg *Config, diff *HotDiff) bool {
  388. oldOut, ok := parseOutbounds(oldCfg.OutboundConfigs)
  389. if !ok {
  390. return false
  391. }
  392. newOut, ok := parseOutbounds(newCfg.OutboundConfigs)
  393. if !ok {
  394. return false
  395. }
  396. if (len(oldOut) == 0) != (len(newOut) == 0) {
  397. return false
  398. }
  399. if len(oldOut) > 0 {
  400. if oldOut[0].tag != newOut[0].tag || !bytes.Equal(oldOut[0].norm, newOut[0].norm) {
  401. return false
  402. }
  403. }
  404. oldByTag := make(map[string]outboundEntry, len(oldOut))
  405. for _, e := range oldOut {
  406. oldByTag[e.tag] = e
  407. }
  408. newByTag := make(map[string]outboundEntry, len(newOut))
  409. for _, e := range newOut {
  410. newByTag[e.tag] = e
  411. }
  412. for _, oldE := range oldOut {
  413. newE, exists := newByTag[oldE.tag]
  414. if exists && bytes.Equal(oldE.norm, newE.norm) {
  415. continue
  416. }
  417. diff.RemovedOutboundTags = append(diff.RemovedOutboundTags, oldE.tag)
  418. if exists {
  419. diff.AddedOutbounds = append(diff.AddedOutbounds, newE.raw)
  420. }
  421. }
  422. for _, newE := range newOut {
  423. if _, exists := oldByTag[newE.tag]; !exists {
  424. diff.AddedOutbounds = append(diff.AddedOutbounds, newE.raw)
  425. }
  426. }
  427. return true
  428. }
  429. // diffRouting decides whether the routing change is limited to rules and
  430. // balancers — the only parts RoutingService.AddRule can replace at runtime.
  431. // domainStrategy/domainMatcher and any other key in the section are fixed at
  432. // process start.
  433. func diffRouting(oldCfg, newCfg *Config, diff *HotDiff) bool {
  434. if bytes.Equal(oldCfg.RouterConfig, newCfg.RouterConfig) {
  435. return true
  436. }
  437. // No routing section at start likely means no router feature (and no
  438. // RoutingService) in the running instance — only a restart can add it.
  439. if len(oldCfg.RouterConfig) == 0 || len(newCfg.RouterConfig) == 0 {
  440. return false
  441. }
  442. oldRest, ok := routingWithoutReloadable(oldCfg.RouterConfig)
  443. if !ok {
  444. return false
  445. }
  446. newRest, ok := routingWithoutReloadable(newCfg.RouterConfig)
  447. if !ok {
  448. return false
  449. }
  450. if !bytes.Equal(oldRest, newRest) {
  451. return false
  452. }
  453. diff.RoutingConfig = newCfg.RouterConfig
  454. return true
  455. }
  456. // routingWithoutReloadable returns the routing section normalized with the
  457. // runtime-reloadable keys removed, for comparing the restart-only remainder.
  458. func routingWithoutReloadable(raw []byte) ([]byte, bool) {
  459. parsed := map[string]any{}
  460. if len(raw) > 0 {
  461. decoder := json.NewDecoder(bytes.NewReader(raw))
  462. decoder.UseNumber()
  463. if err := decoder.Decode(&parsed); err != nil {
  464. return nil, false
  465. }
  466. }
  467. delete(parsed, "rules")
  468. delete(parsed, "balancers")
  469. out, err := json.Marshal(parsed)
  470. if err != nil {
  471. return nil, false
  472. }
  473. return out, true
  474. }
  475. // inboundEqualNormalized compares two inbounds ignoring JSON formatting in
  476. // their raw sections, so a reformatted template does not read as a changed
  477. // inbound.
  478. func inboundEqualNormalized(a, b *InboundConfig) bool {
  479. return a.Port == b.Port &&
  480. a.Protocol == b.Protocol &&
  481. a.Tag == b.Tag &&
  482. rawEqualNormalized(a.Listen, b.Listen) &&
  483. rawEqualNormalized(a.Settings, b.Settings) &&
  484. rawEqualNormalized(a.StreamSettings, b.StreamSettings) &&
  485. rawEqualNormalized(a.Sniffing, b.Sniffing)
  486. }
  487. // rawEqualNormalized reports whether two raw JSON values are semantically
  488. // equal: whitespace, object key order and an explicit `null` versus an
  489. // absent section are all ignored. UI editors rebuild objects on save (new
  490. // key order) and emit `null` for switched-off sections — none of that is a
  491. // reason to restart the core. Number precision is preserved via json.Number,
  492. // so genuinely different values never compare equal. Unparsable values only
  493. // compare equal byte-for-byte.
  494. func rawEqualNormalized(a, b json_util.RawMessage) bool {
  495. if bytes.Equal(a, b) {
  496. return true
  497. }
  498. na, ok := canonicalJSON(a)
  499. if !ok {
  500. return false
  501. }
  502. nb, ok := canonicalJSON(b)
  503. if !ok {
  504. return false
  505. }
  506. return bytes.Equal(na, nb)
  507. }
  508. // canonicalJSON renders a JSON value in canonical form: sorted object keys,
  509. // no insignificant whitespace, exact number digits (json.Number). Empty
  510. // input and JSON null both canonicalize to nil.
  511. func canonicalJSON(raw json_util.RawMessage) ([]byte, bool) {
  512. if len(raw) == 0 {
  513. return nil, true
  514. }
  515. decoder := json.NewDecoder(bytes.NewReader(raw))
  516. decoder.UseNumber()
  517. var value any
  518. if err := decoder.Decode(&value); err != nil {
  519. return nil, false
  520. }
  521. if value == nil {
  522. return nil, true
  523. }
  524. out, err := json.Marshal(value)
  525. if err != nil {
  526. return nil, false
  527. }
  528. return out, true
  529. }
  530. // inboundsByTag indexes inbounds by tag; ok is false when a tag is empty or
  531. // duplicated, since such handlers can't be addressed through the API.
  532. func inboundsByTag(inbounds []InboundConfig) (map[string]*InboundConfig, bool) {
  533. byTag := make(map[string]*InboundConfig, len(inbounds))
  534. for i := range inbounds {
  535. tag := inbounds[i].Tag
  536. if tag == "" {
  537. return nil, false
  538. }
  539. if _, dup := byTag[tag]; dup {
  540. return nil, false
  541. }
  542. byTag[tag] = &inbounds[i]
  543. }
  544. return byTag, true
  545. }
  546. type outboundEntry struct {
  547. tag string
  548. raw []byte // original JSON, used for AddOutbound
  549. norm []byte // canonical JSON, used for change detection
  550. }
  551. // parseOutbounds splits the outbounds array into per-entry raw/normalized
  552. // JSON. ok is false when the array is unparsable or an entry has an empty or
  553. // duplicate tag — those can't be addressed through the API.
  554. func parseOutbounds(raw json_util.RawMessage) ([]outboundEntry, bool) {
  555. if len(raw) == 0 {
  556. return nil, true
  557. }
  558. var elems []json.RawMessage
  559. if err := json.Unmarshal(raw, &elems); err != nil {
  560. return nil, false
  561. }
  562. entries := make([]outboundEntry, 0, len(elems))
  563. seen := make(map[string]struct{}, len(elems))
  564. for _, elem := range elems {
  565. var meta struct {
  566. Tag string `json:"tag"`
  567. }
  568. if err := json.Unmarshal(elem, &meta); err != nil {
  569. return nil, false
  570. }
  571. if meta.Tag == "" {
  572. return nil, false
  573. }
  574. if _, dup := seen[meta.Tag]; dup {
  575. return nil, false
  576. }
  577. seen[meta.Tag] = struct{}{}
  578. norm, ok := canonicalJSON(json_util.RawMessage(elem))
  579. if !ok {
  580. return nil, false
  581. }
  582. entries = append(entries, outboundEntry{tag: meta.Tag, raw: elem, norm: norm})
  583. }
  584. return entries, true
  585. }
  586. // apiTagFromConfig extracts api.tag from the api section, defaulting to "api".
  587. func apiTagFromConfig(api json_util.RawMessage) string {
  588. var parsed struct {
  589. Tag string `json:"tag"`
  590. }
  591. if len(api) > 0 && json.Unmarshal(api, &parsed) == nil && parsed.Tag != "" {
  592. return parsed.Tag
  593. }
  594. return "api"
  595. }