hot_diff.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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. RemovedOutboundTags []string
  18. AddedOutbounds [][]byte
  19. RoutingConfig []byte // full new routing section; nil when unchanged
  20. }
  21. // UserOp is a per-user AlterInbound operation; User is nil for removals.
  22. type UserOp struct {
  23. Tag string
  24. Protocol string
  25. Email string
  26. User map[string]any
  27. }
  28. // Empty reports whether the diff contains no operations.
  29. func (d *HotDiff) Empty() bool {
  30. return len(d.RemovedInboundTags) == 0 &&
  31. len(d.AddedInbounds) == 0 &&
  32. len(d.RemovedUsers) == 0 &&
  33. len(d.AddedUsers) == 0 &&
  34. len(d.RemovedOutboundTags) == 0 &&
  35. len(d.AddedOutbounds) == 0 &&
  36. d.RoutingConfig == nil
  37. }
  38. // ComputeHotDiff compares two generated configs and returns the API operations
  39. // that transform a running instance from oldCfg to newCfg. ok is false when
  40. // the change touches anything that has no runtime reload API (log, dns,
  41. // policy, ...) and therefore requires a full process restart.
  42. func ComputeHotDiff(oldCfg, newCfg *Config) (*HotDiff, bool) {
  43. if oldCfg == nil || newCfg == nil {
  44. return nil, false
  45. }
  46. // Sections without a reload API must be semantically identical.
  47. // Comparison is whitespace-insensitive: a template save that merely
  48. // reformats the JSON (frontend textarea, API clients) must not be
  49. // mistaken for a real change that forces a restart.
  50. static := []struct {
  51. name string
  52. old, new json_util.RawMessage
  53. }{
  54. {"log", oldCfg.LogConfig, newCfg.LogConfig},
  55. {"dns", oldCfg.DNSConfig, newCfg.DNSConfig},
  56. {"transport", oldCfg.Transport, newCfg.Transport},
  57. {"policy", oldCfg.Policy, newCfg.Policy},
  58. {"api", oldCfg.API, newCfg.API},
  59. {"stats", oldCfg.Stats, newCfg.Stats},
  60. {"reverse", oldCfg.Reverse, newCfg.Reverse},
  61. {"fakedns", oldCfg.FakeDNS, newCfg.FakeDNS},
  62. {"observatory", oldCfg.Observatory, newCfg.Observatory},
  63. {"burstObservatory", oldCfg.BurstObservatory, newCfg.BurstObservatory},
  64. {"metrics", oldCfg.Metrics, newCfg.Metrics},
  65. {"geodata", oldCfg.Geodata, newCfg.Geodata},
  66. {"env", oldCfg.Env, newCfg.Env},
  67. }
  68. for _, section := range static {
  69. if !rawEqualNormalized(section.old, section.new) {
  70. logger.Debug("hot diff: section [", section.name, "] changed and has no reload API")
  71. return nil, false
  72. }
  73. }
  74. diff := &HotDiff{}
  75. if ok := diffInbounds(oldCfg, newCfg, diff); !ok {
  76. logger.Debug("hot diff: inbound change is not API-applicable")
  77. return nil, false
  78. }
  79. if ok := diffOutbounds(oldCfg, newCfg, diff); !ok {
  80. logger.Debug("hot diff: outbound change is not API-applicable (default outbound or tags)")
  81. return nil, false
  82. }
  83. if ok := diffRouting(oldCfg, newCfg, diff); !ok {
  84. logger.Debug("hot diff: routing change is not API-applicable (domainStrategy or section shape)")
  85. return nil, false
  86. }
  87. return diff, true
  88. }
  89. // diffInbounds fills diff with inbound removals/additions (a changed inbound
  90. // becomes remove+add). The api inbound carries the gRPC server the panel is
  91. // talking through, so any change touching it forces a restart.
  92. func diffInbounds(oldCfg, newCfg *Config, diff *HotDiff) bool {
  93. oldByTag, ok := inboundsByTag(oldCfg.InboundConfigs)
  94. if !ok {
  95. return false
  96. }
  97. newByTag, ok := inboundsByTag(newCfg.InboundConfigs)
  98. if !ok {
  99. return false
  100. }
  101. apiTag := apiTagFromConfig(newCfg.API)
  102. for i := range oldCfg.InboundConfigs {
  103. oldIb := &oldCfg.InboundConfigs[i]
  104. newIb, exists := newByTag[oldIb.Tag]
  105. if exists && inboundEqualNormalized(oldIb, newIb) {
  106. continue
  107. }
  108. if oldIb.Tag == apiTag || oldIb.Tag == "api" {
  109. return false
  110. }
  111. if exists && (inboundHasReverseClient(oldIb) || inboundHasReverseClient(newIb)) {
  112. logger.Debug("hot diff: inbound [", oldIb.Tag, "] carries a reverse-tagged client, forcing a full restart instead of a hot swap")
  113. return false
  114. }
  115. if exists && diffInboundUsers(oldIb, newIb, diff) {
  116. continue
  117. }
  118. diff.RemovedInboundTags = append(diff.RemovedInboundTags, oldIb.Tag)
  119. if exists {
  120. raw, err := json.Marshal(newIb)
  121. if err != nil {
  122. return false
  123. }
  124. diff.AddedInbounds = append(diff.AddedInbounds, raw)
  125. }
  126. }
  127. for i := range newCfg.InboundConfigs {
  128. newIb := &newCfg.InboundConfigs[i]
  129. if _, exists := oldByTag[newIb.Tag]; exists {
  130. continue
  131. }
  132. if newIb.Tag == apiTag || newIb.Tag == "api" {
  133. return false
  134. }
  135. raw, err := json.Marshal(newIb)
  136. if err != nil {
  137. return false
  138. }
  139. diff.AddedInbounds = append(diff.AddedInbounds, raw)
  140. }
  141. return true
  142. }
  143. var userDiffableProtocols = map[string]struct{}{"vless": {}, "vmess": {}, "trojan": {}}
  144. // diffInboundUsers emits per-user AlterInbound ops when two same-tag inbounds
  145. // differ only in settings.clients, so the handler (and its listener) survives.
  146. func diffInboundUsers(oldIb, newIb *InboundConfig, diff *HotDiff) bool {
  147. if oldIb.Port != newIb.Port || oldIb.Protocol != newIb.Protocol || oldIb.Tag != newIb.Tag {
  148. return false
  149. }
  150. if _, ok := userDiffableProtocols[oldIb.Protocol]; !ok {
  151. return false
  152. }
  153. if !rawEqualNormalized(oldIb.Listen, newIb.Listen) ||
  154. !rawEqualNormalized(oldIb.StreamSettings, newIb.StreamSettings) ||
  155. !rawEqualNormalized(oldIb.Sniffing, newIb.Sniffing) {
  156. return false
  157. }
  158. oldClients, oldRest, ok := splitSettingsClients(oldIb.Settings)
  159. if !ok {
  160. return false
  161. }
  162. newClients, newRest, ok := splitSettingsClients(newIb.Settings)
  163. if !ok {
  164. return false
  165. }
  166. if !bytes.Equal(oldRest, newRest) {
  167. return false
  168. }
  169. for email, oldC := range oldClients {
  170. newC, exists := newClients[email]
  171. if exists && bytes.Equal(oldC.norm, newC.norm) {
  172. continue
  173. }
  174. diff.RemovedUsers = append(diff.RemovedUsers, UserOp{Tag: oldIb.Tag, Protocol: oldIb.Protocol, Email: email})
  175. if exists {
  176. diff.AddedUsers = append(diff.AddedUsers, UserOp{Tag: oldIb.Tag, Protocol: oldIb.Protocol, Email: email, User: newC.user})
  177. }
  178. }
  179. for email, newC := range newClients {
  180. if _, exists := oldClients[email]; !exists {
  181. diff.AddedUsers = append(diff.AddedUsers, UserOp{Tag: oldIb.Tag, Protocol: oldIb.Protocol, Email: email, User: newC.user})
  182. }
  183. }
  184. return true
  185. }
  186. type clientEntry struct {
  187. user map[string]any
  188. norm []byte
  189. }
  190. // splitSettingsClients indexes settings.clients by email and returns the rest of
  191. // the settings in canonical form; ok is false when a client has no unique email.
  192. func splitSettingsClients(raw json_util.RawMessage) (map[string]clientEntry, []byte, bool) {
  193. if len(raw) == 0 {
  194. return nil, nil, false
  195. }
  196. settings := map[string]any{}
  197. decoder := json.NewDecoder(bytes.NewReader(raw))
  198. decoder.UseNumber()
  199. if err := decoder.Decode(&settings); err != nil {
  200. return nil, nil, false
  201. }
  202. clientsRaw, hasClients := settings["clients"].([]any)
  203. if !hasClients {
  204. return nil, nil, false
  205. }
  206. clients := make(map[string]clientEntry, len(clientsRaw))
  207. for _, c := range clientsRaw {
  208. obj, ok := c.(map[string]any)
  209. if !ok {
  210. return nil, nil, false
  211. }
  212. email, _ := obj["email"].(string)
  213. if email == "" {
  214. return nil, nil, false
  215. }
  216. if _, dup := clients[email]; dup {
  217. return nil, nil, false
  218. }
  219. norm, err := json.Marshal(obj)
  220. if err != nil {
  221. return nil, nil, false
  222. }
  223. clients[email] = clientEntry{user: obj, norm: norm}
  224. }
  225. delete(settings, "clients")
  226. rest, err := json.Marshal(settings)
  227. if err != nil {
  228. return nil, nil, false
  229. }
  230. return clients, rest, true
  231. }
  232. func inboundHasReverseClient(ib *InboundConfig) bool {
  233. if ib == nil {
  234. return false
  235. }
  236. var settings struct {
  237. Clients []struct {
  238. Reverse json.RawMessage `json:"reverse"`
  239. } `json:"clients"`
  240. }
  241. if err := json.Unmarshal(ib.Settings, &settings); err != nil {
  242. return false
  243. }
  244. for _, c := range settings.Clients {
  245. if len(c.Reverse) == 0 {
  246. continue
  247. }
  248. var tag any
  249. if err := json.Unmarshal(c.Reverse, &tag); err != nil || tag == nil {
  250. continue
  251. }
  252. return true
  253. }
  254. return false
  255. }
  256. // diffOutbounds fills diff with outbound removals/additions keyed by tag.
  257. // The first outbound is xray's default handler and the API can only append,
  258. // so any change to its identity or content forces a restart. Reordering of
  259. // the remaining outbounds is ignored — routing addresses them by tag.
  260. func diffOutbounds(oldCfg, newCfg *Config, diff *HotDiff) bool {
  261. oldOut, ok := parseOutbounds(oldCfg.OutboundConfigs)
  262. if !ok {
  263. return false
  264. }
  265. newOut, ok := parseOutbounds(newCfg.OutboundConfigs)
  266. if !ok {
  267. return false
  268. }
  269. if (len(oldOut) == 0) != (len(newOut) == 0) {
  270. return false
  271. }
  272. if len(oldOut) > 0 {
  273. if oldOut[0].tag != newOut[0].tag || !bytes.Equal(oldOut[0].norm, newOut[0].norm) {
  274. return false
  275. }
  276. }
  277. oldByTag := make(map[string]outboundEntry, len(oldOut))
  278. for _, e := range oldOut {
  279. oldByTag[e.tag] = e
  280. }
  281. newByTag := make(map[string]outboundEntry, len(newOut))
  282. for _, e := range newOut {
  283. newByTag[e.tag] = e
  284. }
  285. for _, oldE := range oldOut {
  286. newE, exists := newByTag[oldE.tag]
  287. if exists && bytes.Equal(oldE.norm, newE.norm) {
  288. continue
  289. }
  290. diff.RemovedOutboundTags = append(diff.RemovedOutboundTags, oldE.tag)
  291. if exists {
  292. diff.AddedOutbounds = append(diff.AddedOutbounds, newE.raw)
  293. }
  294. }
  295. for _, newE := range newOut {
  296. if _, exists := oldByTag[newE.tag]; !exists {
  297. diff.AddedOutbounds = append(diff.AddedOutbounds, newE.raw)
  298. }
  299. }
  300. return true
  301. }
  302. // diffRouting decides whether the routing change is limited to rules and
  303. // balancers — the only parts RoutingService.AddRule can replace at runtime.
  304. // domainStrategy/domainMatcher and any other key in the section are fixed at
  305. // process start.
  306. func diffRouting(oldCfg, newCfg *Config, diff *HotDiff) bool {
  307. if bytes.Equal(oldCfg.RouterConfig, newCfg.RouterConfig) {
  308. return true
  309. }
  310. // No routing section at start likely means no router feature (and no
  311. // RoutingService) in the running instance — only a restart can add it.
  312. if len(oldCfg.RouterConfig) == 0 || len(newCfg.RouterConfig) == 0 {
  313. return false
  314. }
  315. oldRest, ok := routingWithoutReloadable(oldCfg.RouterConfig)
  316. if !ok {
  317. return false
  318. }
  319. newRest, ok := routingWithoutReloadable(newCfg.RouterConfig)
  320. if !ok {
  321. return false
  322. }
  323. if !bytes.Equal(oldRest, newRest) {
  324. return false
  325. }
  326. diff.RoutingConfig = newCfg.RouterConfig
  327. return true
  328. }
  329. // routingWithoutReloadable returns the routing section normalized with the
  330. // runtime-reloadable keys removed, for comparing the restart-only remainder.
  331. func routingWithoutReloadable(raw []byte) ([]byte, bool) {
  332. parsed := map[string]any{}
  333. if len(raw) > 0 {
  334. decoder := json.NewDecoder(bytes.NewReader(raw))
  335. decoder.UseNumber()
  336. if err := decoder.Decode(&parsed); err != nil {
  337. return nil, false
  338. }
  339. }
  340. delete(parsed, "rules")
  341. delete(parsed, "balancers")
  342. out, err := json.Marshal(parsed)
  343. if err != nil {
  344. return nil, false
  345. }
  346. return out, true
  347. }
  348. // inboundEqualNormalized compares two inbounds ignoring JSON formatting in
  349. // their raw sections, so a reformatted template does not read as a changed
  350. // inbound.
  351. func inboundEqualNormalized(a, b *InboundConfig) bool {
  352. return a.Port == b.Port &&
  353. a.Protocol == b.Protocol &&
  354. a.Tag == b.Tag &&
  355. rawEqualNormalized(a.Listen, b.Listen) &&
  356. rawEqualNormalized(a.Settings, b.Settings) &&
  357. rawEqualNormalized(a.StreamSettings, b.StreamSettings) &&
  358. rawEqualNormalized(a.Sniffing, b.Sniffing)
  359. }
  360. // rawEqualNormalized reports whether two raw JSON values are semantically
  361. // equal: whitespace, object key order and an explicit `null` versus an
  362. // absent section are all ignored. UI editors rebuild objects on save (new
  363. // key order) and emit `null` for switched-off sections — none of that is a
  364. // reason to restart the core. Number precision is preserved via json.Number,
  365. // so genuinely different values never compare equal. Unparsable values only
  366. // compare equal byte-for-byte.
  367. func rawEqualNormalized(a, b json_util.RawMessage) bool {
  368. if bytes.Equal(a, b) {
  369. return true
  370. }
  371. na, ok := canonicalJSON(a)
  372. if !ok {
  373. return false
  374. }
  375. nb, ok := canonicalJSON(b)
  376. if !ok {
  377. return false
  378. }
  379. return bytes.Equal(na, nb)
  380. }
  381. // canonicalJSON renders a JSON value in canonical form: sorted object keys,
  382. // no insignificant whitespace, exact number digits (json.Number). Empty
  383. // input and JSON null both canonicalize to nil.
  384. func canonicalJSON(raw json_util.RawMessage) ([]byte, bool) {
  385. if len(raw) == 0 {
  386. return nil, true
  387. }
  388. decoder := json.NewDecoder(bytes.NewReader(raw))
  389. decoder.UseNumber()
  390. var value any
  391. if err := decoder.Decode(&value); err != nil {
  392. return nil, false
  393. }
  394. if value == nil {
  395. return nil, true
  396. }
  397. out, err := json.Marshal(value)
  398. if err != nil {
  399. return nil, false
  400. }
  401. return out, true
  402. }
  403. // inboundsByTag indexes inbounds by tag; ok is false when a tag is empty or
  404. // duplicated, since such handlers can't be addressed through the API.
  405. func inboundsByTag(inbounds []InboundConfig) (map[string]*InboundConfig, bool) {
  406. byTag := make(map[string]*InboundConfig, len(inbounds))
  407. for i := range inbounds {
  408. tag := inbounds[i].Tag
  409. if tag == "" {
  410. return nil, false
  411. }
  412. if _, dup := byTag[tag]; dup {
  413. return nil, false
  414. }
  415. byTag[tag] = &inbounds[i]
  416. }
  417. return byTag, true
  418. }
  419. type outboundEntry struct {
  420. tag string
  421. raw []byte // original JSON, used for AddOutbound
  422. norm []byte // canonical JSON, used for change detection
  423. }
  424. // parseOutbounds splits the outbounds array into per-entry raw/normalized
  425. // JSON. ok is false when the array is unparsable or an entry has an empty or
  426. // duplicate tag — those can't be addressed through the API.
  427. func parseOutbounds(raw json_util.RawMessage) ([]outboundEntry, bool) {
  428. if len(raw) == 0 {
  429. return nil, true
  430. }
  431. var elems []json.RawMessage
  432. if err := json.Unmarshal(raw, &elems); err != nil {
  433. return nil, false
  434. }
  435. entries := make([]outboundEntry, 0, len(elems))
  436. seen := make(map[string]struct{}, len(elems))
  437. for _, elem := range elems {
  438. var meta struct {
  439. Tag string `json:"tag"`
  440. }
  441. if err := json.Unmarshal(elem, &meta); err != nil {
  442. return nil, false
  443. }
  444. if meta.Tag == "" {
  445. return nil, false
  446. }
  447. if _, dup := seen[meta.Tag]; dup {
  448. return nil, false
  449. }
  450. seen[meta.Tag] = struct{}{}
  451. norm, ok := canonicalJSON(json_util.RawMessage(elem))
  452. if !ok {
  453. return nil, false
  454. }
  455. entries = append(entries, outboundEntry{tag: meta.Tag, raw: elem, norm: norm})
  456. }
  457. return entries, true
  458. }
  459. // apiTagFromConfig extracts api.tag from the api section, defaulting to "api".
  460. func apiTagFromConfig(api json_util.RawMessage) string {
  461. var parsed struct {
  462. Tag string `json:"tag"`
  463. }
  464. if len(api) > 0 && json.Unmarshal(api, &parsed) == nil && parsed.Tag != "" {
  465. return parsed.Tag
  466. }
  467. return "api"
  468. }