inbound_node.go 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629
  1. package service
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "sort"
  7. "strings"
  8. "sync"
  9. "time"
  10. "github.com/mhsanaei/3x-ui/v3/internal/database"
  11. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  12. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  13. "github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
  14. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  15. "gorm.io/gorm"
  16. "gorm.io/gorm/clause"
  17. )
  18. var reportedRemoteTagConflict sync.Map
  19. var reportedForeignClientClaim sync.Map
  20. // nodeBulkPushThreshold caps how many per-client RPCs a single operation will
  21. // stream to a remote node. Above it, the panel marks the node dirty instead and
  22. // lets one ReconcileNode push converge the whole inbound — far cheaper than M
  23. // sequential round-trips. Small ops stay on the live per-client path.
  24. const nodeBulkPushThreshold = 32
  25. func (s *InboundService) runtimeFor(ib *model.Inbound) (runtime.Runtime, error) {
  26. mgr := runtime.GetManager()
  27. if mgr == nil {
  28. return nil, fmt.Errorf("runtime manager not initialised")
  29. }
  30. return mgr.RuntimeFor(ib.NodeID)
  31. }
  32. func (s *InboundService) nodePushPlan(ib *model.Inbound) (runtime.Runtime, bool, bool, error) {
  33. if ib.NodeID == nil {
  34. rt, err := s.runtimeFor(ib)
  35. if err != nil {
  36. return nil, false, false, nil
  37. }
  38. return rt, true, false, nil
  39. }
  40. nodeSvc := NodeService{}
  41. enabled, status, _, _, err := nodeSvc.NodeSyncState(*ib.NodeID)
  42. if err != nil {
  43. return nil, false, false, err
  44. }
  45. if !enabled || status == "offline" {
  46. return nil, false, true, nil
  47. }
  48. rt, err := s.runtimeFor(ib)
  49. if err != nil {
  50. return nil, false, true, nil
  51. }
  52. return rt, true, false, nil
  53. }
  54. func (s *InboundService) NodeIsPending(nodeID *int) bool {
  55. if nodeID == nil {
  56. return false
  57. }
  58. return (&NodeService{}).IsNodePending(*nodeID)
  59. }
  60. func (s *InboundService) AnyNodePending(inboundIds []int) bool {
  61. if len(inboundIds) == 0 {
  62. return false
  63. }
  64. nodeSvc := NodeService{}
  65. for _, id := range inboundIds {
  66. ib, err := s.GetInbound(id)
  67. if err != nil || ib.NodeID == nil {
  68. continue
  69. }
  70. if nodeSvc.IsNodePending(*ib.NodeID) {
  71. return true
  72. }
  73. }
  74. return false
  75. }
  76. // ReconcileNode pushes every inbound and sweeps undesired remote tags even when
  77. // individual operations fail, returning the failures joined: one inbound the
  78. // node rejects (e.g. a legacy protocol failing validation, #5685) must not
  79. // stall the rest of the node's config — or, via syncOne, its traffic sync.
  80. func (s *InboundService) ReconcileNode(ctx context.Context, rt *runtime.Remote, n *model.Node) error {
  81. if rt == nil || n == nil || n.Id <= 0 {
  82. return nil
  83. }
  84. nodeID := n.Id
  85. db := database.GetDB()
  86. var inbounds []*model.Inbound
  87. if err := db.Model(model.Inbound{}).Where("node_id = ?", nodeID).Find(&inbounds).Error; err != nil {
  88. return err
  89. }
  90. remoteInbounds, err := rt.ListInboundOptions(ctx)
  91. if err != nil {
  92. return err
  93. }
  94. remoteTags := make([]string, 0, len(remoteInbounds))
  95. remoteTagSet := make(map[string]struct{}, len(remoteTags))
  96. for _, remoteIb := range remoteInbounds {
  97. remoteTags = append(remoteTags, remoteIb.Tag)
  98. remoteTagSet[remoteIb.Tag] = struct{}{}
  99. }
  100. prefix := nodeTagPrefix(&nodeID)
  101. desiredTags := make(map[string]struct{}, len(inbounds)*2)
  102. var errs []error
  103. for _, ib := range inbounds {
  104. desiredTags[ib.Tag] = struct{}{}
  105. // existsOnNode: does the node already report this inbound under any of the
  106. // tag forms it may be stored as? If so, an unchanged push can be skipped.
  107. _, existsOnNode := remoteTagSet[ib.Tag]
  108. if prefix != "" {
  109. if stripped, found := strings.CutPrefix(ib.Tag, prefix); found {
  110. desiredTags[stripped] = struct{}{}
  111. if _, ok := remoteTagSet[stripped]; ok {
  112. existsOnNode = true
  113. }
  114. } else {
  115. desiredTags[prefix+ib.Tag] = struct{}{}
  116. if _, ok := remoteTagSet[prefix+ib.Tag]; ok {
  117. existsOnNode = true
  118. }
  119. }
  120. }
  121. runtimeIb := ib
  122. if built, bErr := s.buildInboundForNodePush(db, ib); bErr == nil {
  123. runtimeIb = built
  124. }
  125. if !existsOnNode && n.Guid != "" && ib.OriginNodeGuid == n.Guid {
  126. var compatible []runtime.RemoteInboundOption
  127. for _, remoteIb := range remoteInbounds {
  128. if remoteIb.Port == runtimeIb.Port &&
  129. remoteIb.Protocol == runtimeIb.Protocol &&
  130. strings.TrimSpace(remoteIb.Listen) == strings.TrimSpace(runtimeIb.Listen) {
  131. compatible = append(compatible, remoteIb)
  132. }
  133. }
  134. switch len(compatible) {
  135. case 1:
  136. alias := compatible[0]
  137. desiredTags[alias.Tag] = struct{}{}
  138. rt.AdoptInboundAlias(runtimeIb, alias)
  139. existsOnNode = true
  140. logger.Infof("adopted compatible inbound %q on node %s as %q", alias.Tag, n.Name, ib.Tag)
  141. case 0:
  142. // No compatible occupant: keep the normal create path, which
  143. // leaves a real port/protocol drift loud.
  144. default:
  145. for _, candidate := range compatible {
  146. desiredTags[candidate.Tag] = struct{}{}
  147. }
  148. errs = append(errs, fmt.Errorf("reconcile inbound %q: ambiguous compatible remote inbounds", ib.Tag))
  149. continue
  150. }
  151. }
  152. if _, err := rt.ReconcileInbound(ctx, runtimeIb, existsOnNode); err != nil {
  153. errs = append(errs, fmt.Errorf("reconcile inbound %q: %w", ib.Tag, err))
  154. }
  155. }
  156. // Before the first clean sync adopts the node's inbounds, "absent locally"
  157. // means "not imported yet" — sweeping now would wipe the node at onboarding.
  158. if n.InboundsAdoptedAt == 0 {
  159. return errors.Join(errs...)
  160. }
  161. // In "selected" sync mode the panel only manages the selected tags: the
  162. // rest were never imported, so their absence from the local DB must not
  163. // delete them from the node. Only a selected tag missing locally (the
  164. // panel deleted it while the node was unreachable) may be swept.
  165. var selected map[string]struct{}
  166. if n.InboundSyncMode == "selected" {
  167. selected = make(map[string]struct{}, len(n.InboundTags))
  168. for _, tag := range n.InboundTags {
  169. selected[tag] = struct{}{}
  170. }
  171. }
  172. for _, tag := range remoteTags {
  173. if _, want := desiredTags[tag]; want {
  174. continue
  175. }
  176. if selected != nil {
  177. if _, managed := selected[tag]; !managed {
  178. continue
  179. }
  180. }
  181. if err := rt.DelInbound(ctx, &model.Inbound{Tag: tag}); err != nil {
  182. errs = append(errs, fmt.Errorf("reconcile delete %q: %w", tag, err))
  183. }
  184. }
  185. return errors.Join(errs...)
  186. }
  187. const resetGracePeriodMs int64 = 30000
  188. // onlineGracePeriodMs must comfortably exceed the 5s traffic-poll interval —
  189. // Xray's stats counters often report a zero delta for an active session across
  190. // a single poll, so a 5s grace would still drop the client on the next tick.
  191. // ~4 polls of slack keeps idle-but-connected clients visible without lingering
  192. // long after a real disconnect.
  193. const onlineGracePeriodMs int64 = 20000
  194. type nodeTrafficCounter struct {
  195. Up int64
  196. Down int64
  197. }
  198. func (s *InboundService) upsertNodeBaseline(tx *gorm.DB, nodeID int, email string, up, down int64) error {
  199. return tx.Clauses(clause.OnConflict{
  200. Columns: []clause.Column{{Name: "node_id"}, {Name: "email"}},
  201. DoUpdates: clause.AssignmentColumns([]string{"up", "down"}),
  202. }).Create(&model.NodeClientTraffic{NodeId: nodeID, Email: email, Up: up, Down: down}).Error
  203. }
  204. // mergeActivationExpiry: master absolute wins; node may only activate when
  205. // master is unset/duration. Node auto-renew goes through nodeClientRenewed.
  206. func mergeActivationExpiry(existing, node int64) int64 {
  207. if existing > 0 {
  208. return existing
  209. }
  210. return node
  211. }
  212. // masterLimitsAllowClient reports whether the master's own deadline and quota
  213. // (including this tick's deltas) still permit the client.
  214. func masterLimitsAllowClient(master *xray.ClientTraffic, now, deltaUp, deltaDown int64) bool {
  215. if master == nil {
  216. return false
  217. }
  218. if master.ExpiryTime > 0 && master.ExpiryTime <= now {
  219. return false
  220. }
  221. if master.Total > 0 && master.Up+deltaUp+master.Down+deltaDown >= master.Total {
  222. return false
  223. }
  224. return true
  225. }
  226. // nodeDisableIsStale reports an enable=false the node decided against limits the
  227. // master has since changed, so it must not latch back (#6228 / #4917).
  228. func nodeDisableIsStale(master *xray.ClientTraffic, node xray.ClientTraffic, now, deltaUp, deltaDown int64) bool {
  229. if master == nil {
  230. return false
  231. }
  232. // Matching limits mean the node judged the client on the master's own terms:
  233. // that verdict is genuine and still latches, as #4917 requires.
  234. if node.ExpiryTime == master.ExpiryTime && node.Total == master.Total {
  235. return false
  236. }
  237. return masterLimitsAllowClient(master, now, deltaUp, deltaDown)
  238. }
  239. func clampTrafficCounter(v int64) int64 {
  240. if v > database.TrafficMax {
  241. return database.TrafficMax
  242. }
  243. if v < 0 {
  244. return 0
  245. }
  246. return v
  247. }
  248. // applyMasterClientLifecycle overlays the already-merged master row onto a
  249. // node-reported client for SyncInbound (#6228).
  250. func applyMasterClientLifecycle(c *model.Client, master *xray.ClientTraffic, cs *xray.ClientTraffic) {
  251. if master == nil {
  252. // No central row to speak for the client: the node's own latch is all
  253. // there is, and it may only disable.
  254. if cs != nil && !cs.Enable {
  255. c.Enable = false
  256. }
  257. return
  258. }
  259. c.ExpiryTime = mergeActivationExpiry(master.ExpiryTime, c.ExpiryTime)
  260. c.Enable = master.Enable
  261. }
  262. // nodeClientRenewed reports a node-side auto-renew: an absolute deadline moved
  263. // forward, evidenced by a renewal-count bump or a drop below the stored baseline.
  264. func nodeClientRenewed(existing *xray.ClientTraffic, cs xray.ClientTraffic, canon, base nodeTrafficCounter) bool {
  265. if (cs.Reset <= 0 && cs.ResetDay <= 0) || cs.ExpiryTime <= 0 || existing.ExpiryTime <= 0 {
  266. return false
  267. }
  268. if cs.ExpiryTime <= existing.ExpiryTime {
  269. return false
  270. }
  271. // A client that used no traffic in the period never dips, so the renewal
  272. // counter is the only evidence autoRenewClients leaves behind (#6228).
  273. if cs.ResetCount > existing.ResetCount {
  274. return true
  275. }
  276. return canon.Up < base.Up || canon.Down < base.Down
  277. }
  278. // liftActivatedClientRecordExpiries copies a node-activated deadline from
  279. // client_traffics onto client records still holding the negative duration (#5714).
  280. func liftActivatedClientRecordExpiries(tx *gorm.DB) error {
  281. return tx.Exec(
  282. `UPDATE clients
  283. SET expiry_time = (SELECT ct.expiry_time FROM client_traffics ct WHERE ct.email = clients.email AND ct.expiry_time > 0 LIMIT 1)
  284. WHERE clients.expiry_time < 0
  285. AND EXISTS (SELECT 1 FROM client_traffics ct WHERE ct.email = clients.email AND ct.expiry_time > 0)`,
  286. ).Error
  287. }
  288. // SnapshotHasUnadoptedInbounds reports whether the snapshot carries a tag with
  289. // no central row yet, i.e. the next merge would adopt a new inbound.
  290. func (s *InboundService) SnapshotHasUnadoptedInbounds(nodeID int, snap *runtime.TrafficSnapshot) (bool, error) {
  291. if snap == nil || len(snap.Inbounds) == 0 {
  292. return false, nil
  293. }
  294. var tags []string
  295. if err := database.GetDB().Model(model.Inbound{}).
  296. Where("node_id = ?", nodeID).
  297. Pluck("tag", &tags).Error; err != nil {
  298. return false, err
  299. }
  300. prefix := nodeTagPrefix(&nodeID)
  301. known := make(map[string]struct{}, len(tags)*2)
  302. for _, tag := range tags {
  303. known[tag] = struct{}{}
  304. if prefix != "" {
  305. if stripped, found := strings.CutPrefix(tag, prefix); found {
  306. known[stripped] = struct{}{}
  307. } else {
  308. known[prefix+tag] = struct{}{}
  309. }
  310. }
  311. }
  312. for _, ib := range snap.Inbounds {
  313. if ib == nil {
  314. continue
  315. }
  316. if _, ok := known[ib.Tag]; !ok {
  317. return true, nil
  318. }
  319. }
  320. return false, nil
  321. }
  322. // SetRemoteTraffic merges a node snapshot. justPushed marks the tick whose
  323. // config push just landed, whose snapshot may still predate it (#6228).
  324. func (s *InboundService) SetRemoteTraffic(nodeID int, snap *runtime.TrafficSnapshot, dirty, justPushed bool) (bool, error) {
  325. var structuralChange bool
  326. err := submitTrafficWrite(func() error {
  327. var inner error
  328. structuralChange, inner = s.setRemoteTrafficLocked(nodeID, snap, dirty, justPushed)
  329. return inner
  330. })
  331. return structuralChange, err
  332. }
  333. // GetNodeInboundTrafficTotals returns the current cumulative up/down for every
  334. // node-hosted inbound, keyed by tag. The node sync diffs successive snapshots of
  335. // this to derive per-inbound speed for the dashboard — node inbounds have no
  336. // local Xray poll to produce live deltas the way local inbounds do.
  337. func (s *InboundService) GetNodeInboundTrafficTotals() (map[string][2]int64, error) {
  338. var rows []struct {
  339. Tag string
  340. Up int64
  341. Down int64
  342. }
  343. if err := database.GetDB().Table("inbounds").
  344. Select("tag, up, down").
  345. Where("node_id IS NOT NULL").
  346. Scan(&rows).Error; err != nil {
  347. return nil, err
  348. }
  349. out := make(map[string][2]int64, len(rows))
  350. for _, r := range rows {
  351. out[r.Tag] = [2]int64{r.Up, r.Down}
  352. }
  353. return out, nil
  354. }
  355. func adoptedWireChanged(c, snapIb *model.Inbound, adoptedSettings string) bool {
  356. return c.Settings != adoptedSettings ||
  357. c.Enable != snapIb.Enable ||
  358. c.Remark != snapIb.Remark ||
  359. c.SubSortIndex != normalizeSubSortIndex(snapIb.SubSortIndex) ||
  360. c.Listen != snapIb.Listen ||
  361. c.Port != snapIb.Port ||
  362. c.Protocol != snapIb.Protocol ||
  363. c.Total != snapIb.Total ||
  364. c.ExpiryTime != snapIb.ExpiryTime ||
  365. c.StreamSettings != snapIb.StreamSettings ||
  366. c.Sniffing != snapIb.Sniffing ||
  367. c.TrafficReset != snapIb.TrafficReset ||
  368. c.TrafficResetDay != normalizeTrafficResetDay(snapIb.TrafficResetDay)
  369. }
  370. // adoptedWireInbound is the central inbound as it reads after adopting the
  371. // node-reported wire fields — the payload the reconcile fingerprint must track.
  372. func adoptedWireInbound(c, snapIb *model.Inbound, adoptedSettings string) *model.Inbound {
  373. a := *c
  374. a.Enable = snapIb.Enable
  375. a.Remark = snapIb.Remark
  376. a.SubSortIndex = normalizeSubSortIndex(snapIb.SubSortIndex)
  377. a.Listen = snapIb.Listen
  378. a.Port = snapIb.Port
  379. a.Protocol = snapIb.Protocol
  380. a.Total = snapIb.Total
  381. a.ExpiryTime = snapIb.ExpiryTime
  382. a.Settings = adoptedSettings
  383. a.StreamSettings = snapIb.StreamSettings
  384. a.Sniffing = snapIb.Sniffing
  385. a.TrafficReset = snapIb.TrafficReset
  386. a.TrafficResetDay = normalizeTrafficResetDay(snapIb.TrafficResetDay)
  387. return &a
  388. }
  389. // clientEmailsOwnedElsewhere returns the emails attached only to inbounds of
  390. // other nodes: email is unique, so adopting one would overwrite a client this
  391. // node does not serve. Attached nowhere means soft-orphaned, hence adoptable.
  392. func clientEmailsOwnedElsewhere(tx *gorm.DB, nodeID int, emails []string) (map[string]struct{}, error) {
  393. attachedEmails := func(nodeScoped bool) ([]string, error) {
  394. q := tx.Table("clients").
  395. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  396. Joins("JOIN inbounds ON inbounds.id = client_inbounds.inbound_id").
  397. Where("clients.email IN ?", emails)
  398. if nodeScoped {
  399. q = q.Where("inbounds.node_id = ?", nodeID)
  400. }
  401. var rows []string
  402. err := q.Pluck("clients.email", &rows).Error
  403. return rows, err
  404. }
  405. attached, err := attachedEmails(false)
  406. if err != nil {
  407. return nil, err
  408. }
  409. if len(attached) == 0 {
  410. return nil, nil
  411. }
  412. owned, err := attachedEmails(true)
  413. if err != nil {
  414. return nil, err
  415. }
  416. ownedSet := make(map[string]struct{}, len(owned))
  417. for _, email := range owned {
  418. ownedSet[email] = struct{}{}
  419. }
  420. foreign := make(map[string]struct{})
  421. for _, email := range attached {
  422. if _, ok := ownedSet[email]; !ok {
  423. foreign[email] = struct{}{}
  424. }
  425. }
  426. return foreign, nil
  427. }
  428. func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.TrafficSnapshot, dirty, justPushed bool) (bool, error) {
  429. if snap == nil || nodeID <= 0 {
  430. return false, nil
  431. }
  432. db := database.GetDB()
  433. now := time.Now().UnixMilli()
  434. // originGuidFor attributes a synced inbound to the panel that physically
  435. // hosts it. A node's OWN inbounds report either an empty origin or — on
  436. // builds that set it locally — the node's own panelGuid; both resolve to
  437. // selfKey, which is the node's panelGuid unless that GUID is ambiguous
  438. // (shared with another node or the master, i.e. a cloned server), in which
  439. // case it falls back to the node-unique id so #4983 attribution doesn't
  440. // collapse two physical nodes into one bucket. Only a DIFFERENT, non-empty
  441. // origin (an inbound the node forwards from its own sub-node) is kept as-is,
  442. // so a chained Node1->Node2->Node3 still attributes Node3's inbounds to Node3.
  443. var nodeRow model.Node
  444. db.Select("guid", "config_dirty", "inbound_sync_mode", "inbound_tags").Where("id = ?", nodeID).First(&nodeRow)
  445. // Re-read inside the serialized writer: a client added while this snapshot
  446. // was in flight marks the node dirty after the caller sampled the flag.
  447. dirty = dirty || nodeRow.ConfigDirty
  448. // Adoption, record sync and sweeps still run on a just-pushed tick; only the
  449. // client lifecycle merge waits for a snapshot that reflects the push.
  450. lifecycleFrozen := dirty || justPushed
  451. nodeRow.Id = nodeID
  452. unmanagedTag := unmanagedTagPredicate(&nodeRow)
  453. selfKey := effectiveNodeKey(&model.Node{Id: nodeID, Guid: nodeRow.Guid})
  454. guidShared := nodeRow.Guid != "" && selfKey != nodeRow.Guid
  455. originGuidFor := func(snapIb *model.Inbound) string {
  456. if snapIb.OriginNodeGuid != "" && snapIb.OriginNodeGuid != nodeRow.Guid {
  457. return snapIb.OriginNodeGuid
  458. }
  459. return selfKey
  460. }
  461. var central []model.Inbound
  462. if err := db.Model(model.Inbound{}).
  463. Where("node_id = ?", nodeID).
  464. Find(&central).Error; err != nil {
  465. return false, err
  466. }
  467. // Index under the stored tag and its prefix-flipped form so a snap matches
  468. // whether the n<id>- prefix lives on the node side, the central side, or
  469. // neither — a mismatch must never spawn a duplicate central inbound.
  470. tagToCentral := make(map[string]*model.Inbound, len(central)*2)
  471. prefix := nodeTagPrefix(&nodeID)
  472. for i := range central {
  473. tagToCentral[central[i].Tag] = &central[i]
  474. if prefix != "" {
  475. if stripped, found := strings.CutPrefix(central[i].Tag, prefix); found {
  476. tagToCentral[stripped] = &central[i]
  477. } else {
  478. tagToCentral[prefix+central[i].Tag] = &central[i]
  479. }
  480. }
  481. }
  482. var centralClientStats []xray.ClientTraffic
  483. if len(central) > 0 {
  484. ids := make([]int, 0, len(central))
  485. for i := range central {
  486. ids = append(ids, central[i].Id)
  487. }
  488. if err := db.Model(xray.ClientTraffic{}).
  489. Where("inbound_id IN ?", ids).
  490. Find(&centralClientStats).Error; err != nil {
  491. return false, err
  492. }
  493. }
  494. type csKey struct {
  495. inboundID int
  496. email string
  497. }
  498. centralCS := make(map[csKey]*xray.ClientTraffic, len(centralClientStats))
  499. centralCSByEmail := make(map[string]*xray.ClientTraffic, len(centralClientStats))
  500. for i := range centralClientStats {
  501. centralCS[csKey{centralClientStats[i].InboundId, centralClientStats[i].Email}] = &centralClientStats[i]
  502. centralCSByEmail[centralClientStats[i].Email] = &centralClientStats[i]
  503. }
  504. nodeBaselines := make(map[string]nodeTrafficCounter)
  505. var baselineRows []model.NodeClientTraffic
  506. if err := db.Model(&model.NodeClientTraffic{}).
  507. Where("node_id = ?", nodeID).
  508. Find(&baselineRows).Error; err != nil {
  509. return false, err
  510. }
  511. for i := range baselineRows {
  512. nodeBaselines[baselineRows[i].Email] = nodeTrafficCounter{Up: baselineRows[i].Up, Down: baselineRows[i].Down}
  513. }
  514. var defaultUserId int
  515. if len(central) > 0 {
  516. defaultUserId = central[0].UserId
  517. } else {
  518. var u model.User
  519. if err := db.Model(model.User{}).Order("id asc").First(&u).Error; err == nil {
  520. defaultUserId = u.Id
  521. } else {
  522. defaultUserId = 1
  523. }
  524. }
  525. // Union of every email the snapshot still reports, across all inbounds.
  526. // The (node, email) baseline rows are keyed per node, not per inbound, so
  527. // the sweeps below must only drop one when the email left the node
  528. // entirely — an email whose stats moved to (or always lived under) a
  529. // sibling inbound still needs its baseline for the sibling's delta
  530. // computation (#5202).
  531. //
  532. // Xray counts traffic per email, not per inbound, so a multi-attached
  533. // client's shared counter is copied onto every inbound it's on. Fold each
  534. // email to its per-field max (nodeEmailTotals) so divergent copies can't make
  535. // the reset clamp re-add a lower sibling as fresh traffic (#5274).
  536. snapEmailsAll := make(map[string]struct{})
  537. nodeEmailTotals := make(map[string]nodeTrafficCounter)
  538. for _, snapIb := range snap.Inbounds {
  539. if snapIb == nil {
  540. continue
  541. }
  542. for i := range snapIb.ClientStats {
  543. email := snapIb.ClientStats[i].Email
  544. snapEmailsAll[email] = struct{}{}
  545. cur := nodeEmailTotals[email]
  546. if snapIb.ClientStats[i].Up > cur.Up {
  547. cur.Up = snapIb.ClientStats[i].Up
  548. }
  549. if snapIb.ClientStats[i].Down > cur.Down {
  550. cur.Down = snapIb.ClientStats[i].Down
  551. }
  552. nodeEmailTotals[email] = cur
  553. }
  554. }
  555. // Membership set for the rowExists checks below. Only the snapshot's emails
  556. // are ever probed, so scope the lookup to those instead of plucking the whole
  557. // client_traffics table (50k+ rows) on every node poll.
  558. existingEmails := make(map[string]struct{}, len(snapEmailsAll))
  559. if len(snapEmailsAll) > 0 {
  560. snapEmailList := make([]string, 0, len(snapEmailsAll))
  561. for email := range snapEmailsAll {
  562. snapEmailList = append(snapEmailList, email)
  563. }
  564. for _, batch := range chunkStrings(snapEmailList, sqliteMaxVars) {
  565. var found []string
  566. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Pluck("email", &found).Error; err != nil {
  567. return false, err
  568. }
  569. for _, e := range found {
  570. existingEmails[e] = struct{}{}
  571. }
  572. }
  573. }
  574. tx := db.Begin()
  575. committed := false
  576. defer func() {
  577. if !committed {
  578. tx.Rollback()
  579. }
  580. }()
  581. structuralChange := false
  582. lifecycleLifted := false
  583. var adoptedInbounds []*model.Inbound
  584. type pendingAdopt struct {
  585. central *model.Inbound
  586. snapIb *model.Inbound
  587. wireSettings string
  588. }
  589. var pendingAdopts []pendingAdopt
  590. newInboundIDs := make(map[int]struct{})
  591. snapTags := make(map[string]struct{}, len(snap.Inbounds))
  592. for _, snapIb := range snap.Inbounds {
  593. if snapIb == nil {
  594. continue
  595. }
  596. snapTags[snapIb.Tag] = struct{}{}
  597. // Record the prefix-flipped form too so the orphan sweep below keeps a
  598. // central inbound whether its tag carries the n<id>- prefix or not.
  599. if prefix != "" {
  600. if stripped, found := strings.CutPrefix(snapIb.Tag, prefix); found {
  601. snapTags[stripped] = struct{}{}
  602. } else {
  603. snapTags[prefix+snapIb.Tag] = struct{}{}
  604. }
  605. }
  606. c, ok := tagToCentral[snapIb.Tag]
  607. if !ok {
  608. origin := originGuidFor(snapIb)
  609. var compatible []*model.Inbound
  610. for i := range central {
  611. candidate := &central[i]
  612. if candidate.OriginNodeGuid == origin &&
  613. candidate.Port == snapIb.Port &&
  614. candidate.Protocol == snapIb.Protocol &&
  615. strings.TrimSpace(candidate.Listen) == strings.TrimSpace(snapIb.Listen) {
  616. compatible = append(compatible, candidate)
  617. }
  618. }
  619. switch len(compatible) {
  620. case 1:
  621. c, ok = compatible[0], true
  622. tagToCentral[snapIb.Tag] = c
  623. snapTags[c.Tag] = struct{}{}
  624. case 0:
  625. // A genuinely new inbound follows the normal adoption path.
  626. default:
  627. return false, fmt.Errorf("setRemoteTraffic: inbound %q has ambiguous compatible central aliases", snapIb.Tag)
  628. }
  629. }
  630. if !ok {
  631. if dirty {
  632. continue
  633. }
  634. // Try snap.Tag first; on collision fall back to the n<id>-
  635. // prefixed form so local+node can both own the same port.
  636. pickFreeTag := func() (string, error) {
  637. candidates := []string{snapIb.Tag}
  638. if prefix != "" && !strings.HasPrefix(snapIb.Tag, prefix) {
  639. candidates = append(candidates, prefix+snapIb.Tag)
  640. }
  641. for _, t := range candidates {
  642. var owner model.Inbound
  643. err := tx.Where("tag = ?", t).First(&owner).Error
  644. if errors.Is(err, gorm.ErrRecordNotFound) {
  645. return t, nil
  646. }
  647. if err != nil {
  648. return "", err
  649. }
  650. }
  651. return "", nil
  652. }
  653. chosenTag, err := pickFreeTag()
  654. if err != nil {
  655. logger.Warningf("setRemoteTraffic: check tag %q failed: %v", snapIb.Tag, err)
  656. continue
  657. }
  658. if chosenTag == "" {
  659. key := fmt.Sprintf("%d:%s", nodeID, snapIb.Tag)
  660. if _, seen := reportedRemoteTagConflict.LoadOrStore(key, struct{}{}); !seen {
  661. logger.Warningf(
  662. "setRemoteTraffic: tag %q from node %d collides with an existing inbound even after the n%d- prefix — skipping (rename one side to remove the duplicate)",
  663. snapIb.Tag, nodeID, nodeID,
  664. )
  665. }
  666. continue
  667. }
  668. reportedRemoteTagConflict.Delete(fmt.Sprintf("%d:%s", nodeID, snapIb.Tag))
  669. newIb := model.Inbound{
  670. UserId: defaultUserId,
  671. NodeID: &nodeID,
  672. OriginNodeGuid: originGuidFor(snapIb),
  673. Tag: chosenTag,
  674. Listen: snapIb.Listen,
  675. Port: snapIb.Port,
  676. Protocol: snapIb.Protocol,
  677. Settings: snapIb.Settings,
  678. StreamSettings: snapIb.StreamSettings,
  679. Sniffing: snapIb.Sniffing,
  680. TrafficReset: snapIb.TrafficReset,
  681. TrafficResetDay: normalizeTrafficResetDay(snapIb.TrafficResetDay),
  682. LastTrafficResetTime: snapIb.LastTrafficResetTime,
  683. Enable: snapIb.Enable,
  684. Remark: snapIb.Remark,
  685. SubSortIndex: normalizeSubSortIndex(snapIb.SubSortIndex),
  686. Total: snapIb.Total,
  687. ExpiryTime: snapIb.ExpiryTime,
  688. Up: snapIb.Up,
  689. Down: snapIb.Down,
  690. ShareAddrStrategy: "node",
  691. DisableFlow: snapIb.DisableFlow,
  692. }
  693. if err := tx.Create(&newIb).Error; err != nil {
  694. logger.Warningf("setRemoteTraffic: create central inbound for tag %q failed: %v", snapIb.Tag, err)
  695. continue
  696. }
  697. tagToCentral[snapIb.Tag] = &newIb
  698. if newIb.Tag != snapIb.Tag {
  699. tagToCentral[newIb.Tag] = &newIb
  700. }
  701. if rows := adoptedHostRows(snap.HostGroups, snapIb.Id, newIb.Id); len(rows) > 0 {
  702. if err := tx.Create(&rows).Error; err != nil {
  703. logger.Warningf("setRemoteTraffic: adopt host rows for tag %q failed: %v", newIb.Tag, err)
  704. }
  705. }
  706. newInboundIDs[newIb.Id] = struct{}{}
  707. structuralChange = true
  708. continue
  709. }
  710. inGrace := c.LastTrafficResetTime > 0 && now-c.LastTrafficResetTime < resetGracePeriodMs
  711. // Adopting the node's settings verbatim would re-add a client the master
  712. // deleted moments ago if this snapshot was fetched before the deletion
  713. // push landed — filter just-deleted emails out while their tombstone lives.
  714. adoptedSettings := snapIb.Settings
  715. if stripped, changed := stripTombstonedClients(adoptedSettings); changed {
  716. adoptedSettings = stripped
  717. }
  718. if deduped, changed := dedupeSettingsClients(adoptedSettings); changed {
  719. adoptedSettings = deduped
  720. }
  721. updates := map[string]any{}
  722. if !dirty {
  723. // Defer lifecycle lift until after client_traffics absorbs this tick's
  724. // deltas so quota stale-disable matches SQL (#6228).
  725. pendingAdopts = append(pendingAdopts, pendingAdopt{
  726. central: c, snapIb: snapIb, wireSettings: adoptedSettings,
  727. })
  728. updates["enable"] = snapIb.Enable
  729. updates["remark"] = snapIb.Remark
  730. updates["sub_sort_index"] = normalizeSubSortIndex(snapIb.SubSortIndex)
  731. updates["listen"] = snapIb.Listen
  732. updates["port"] = snapIb.Port
  733. updates["protocol"] = snapIb.Protocol
  734. updates["total"] = snapIb.Total
  735. updates["expiry_time"] = snapIb.ExpiryTime
  736. updates["stream_settings"] = snapIb.StreamSettings
  737. updates["sniffing"] = snapIb.Sniffing
  738. updates["traffic_reset"] = snapIb.TrafficReset
  739. updates["traffic_reset_day"] = normalizeTrafficResetDay(snapIb.TrafficResetDay)
  740. updates["last_traffic_reset_time"] = snapIb.LastTrafficResetTime
  741. }
  742. if !inGrace || (snapIb.Up+snapIb.Down) <= (c.Up+c.Down) {
  743. updates["up"] = snapIb.Up
  744. updates["down"] = snapIb.Down
  745. }
  746. // Physical-home attribution is independent of config-dirty state, so
  747. // keep it current even while the node has pending offline edits. Writes
  748. // once to backfill an existing row, then stays equal (#4983).
  749. if og := originGuidFor(snapIb); c.OriginNodeGuid != og {
  750. updates["origin_node_guid"] = og
  751. }
  752. if !dirty && (c.Remark != snapIb.Remark ||
  753. c.Listen != snapIb.Listen ||
  754. c.Port != snapIb.Port ||
  755. c.Total != snapIb.Total ||
  756. c.ExpiryTime != snapIb.ExpiryTime ||
  757. c.Enable != snapIb.Enable) {
  758. structuralChange = true
  759. }
  760. if len(updates) > 0 {
  761. if err := tx.Model(model.Inbound{}).
  762. Where("id = ?", c.Id).
  763. Updates(updates).Error; err != nil {
  764. return false, err
  765. }
  766. }
  767. }
  768. for _, c := range central {
  769. if dirty {
  770. continue
  771. }
  772. // A node inbound created disabled is never delivered, so its absence from
  773. // the snapshot is ambiguous rather than evidence of a node-side delete.
  774. if !c.Enable {
  775. continue
  776. }
  777. if len(snapTags) == 0 {
  778. // A node mid-restart or with a transient DB error can return an empty
  779. // inbound list with success=true. Treat "zero inbounds reported" as
  780. // "nothing to say", not "delete all my inbounds" — otherwise a blip
  781. // wipes the node's central inbounds and every client on them (and
  782. // resets traffic history on re-create). A real per-inbound deletion
  783. // still sweeps, because the node keeps reporting its other inbounds.
  784. continue
  785. }
  786. if _, kept := snapTags[c.Tag]; kept {
  787. continue
  788. }
  789. if unmanagedTag(c.Tag) {
  790. continue
  791. }
  792. // This drops the central inbound and its clients' traffic history, so say
  793. // so: silent removal is indistinguishable from an inbound never arriving.
  794. logger.Warningf("setRemoteTraffic: node %d no longer reports inbound %q (id %d, port %d) — removing it centrally", nodeID, c.Tag, c.Id, c.Port)
  795. var goneEmails []string
  796. if err := tx.Model(xray.ClientTraffic{}).
  797. Where("inbound_id = ?", c.Id).
  798. Pluck("email", &goneEmails).Error; err != nil {
  799. return false, err
  800. }
  801. if len(goneEmails) > 0 {
  802. // Baselines are per (node, email), not per inbound: keep them for
  803. // emails the snapshot still reports under a sibling inbound (#5202).
  804. baselineGone := make([]string, 0, len(goneEmails))
  805. for _, e := range goneEmails {
  806. if _, still := snapEmailsAll[e]; !still {
  807. baselineGone = append(baselineGone, e)
  808. }
  809. }
  810. // Chunk to avoid SQLite bind var limit when a node has many clients
  811. // removed (e.g. after API bulk delete or structural change on node inbound).
  812. for _, batch := range chunkStrings(baselineGone, sqliteMaxVars) {
  813. if err := tx.Where("node_id = ? AND email IN ?", nodeID, batch).
  814. Delete(&model.NodeClientTraffic{}).Error; err != nil {
  815. return false, err
  816. }
  817. }
  818. // The per-email row is the shared accumulator across every inbound
  819. // (and node) the email is attached to. Only drop it when this was the
  820. // email's last inbound — wiping it while a sibling still feeds it
  821. // loses the summed history, and the next node sync would re-seed the
  822. // row with that node's counter alone.
  823. sharedEmails, sErr := s.emailsUsedByOtherInbounds(goneEmails, c.Id)
  824. if sErr != nil {
  825. return false, sErr
  826. }
  827. delEmails := make([]string, 0, len(goneEmails))
  828. for _, e := range goneEmails {
  829. if !sharedEmails[strings.ToLower(strings.TrimSpace(e))] {
  830. delEmails = append(delEmails, e)
  831. }
  832. }
  833. for _, batch := range chunkStrings(delEmails, sqliteMaxVars) {
  834. if err := tx.Where("inbound_id = ? AND email IN ?", c.Id, batch).
  835. Delete(&xray.ClientTraffic{}).Error; err != nil {
  836. return false, err
  837. }
  838. }
  839. }
  840. if err := s.clientService.DetachInbound(tx, c.Id); err != nil {
  841. return false, err
  842. }
  843. if err := tx.Where("id = ?", c.Id).
  844. Delete(&model.Inbound{}).Error; err != nil {
  845. return false, err
  846. }
  847. delete(tagToCentral, c.Tag)
  848. structuralChange = true
  849. }
  850. for _, snapIb := range snap.Inbounds {
  851. if snapIb == nil {
  852. continue
  853. }
  854. c, ok := tagToCentral[snapIb.Tag]
  855. if !ok {
  856. continue
  857. }
  858. snapEmails := make(map[string]struct{}, len(snapIb.ClientStats))
  859. // Parsed once per inbound on the first renewal candidate, not per client.
  860. var snapExpiries map[string]int64
  861. for _, cs := range snapIb.ClientStats {
  862. snapEmails[cs.Email] = struct{}{}
  863. // Node-wide total, not this inbound's possibly-stale copy (#5274).
  864. canon := nodeEmailTotals[cs.Email]
  865. base, seen := nodeBaselines[cs.Email]
  866. var deltaUp, deltaDown int64
  867. if seen {
  868. if deltaUp = canon.Up - base.Up; deltaUp < 0 {
  869. deltaUp = 0
  870. }
  871. if deltaDown = canon.Down - base.Down; deltaDown < 0 {
  872. deltaDown = 0
  873. }
  874. }
  875. if _, rowExists := existingEmails[cs.Email]; !rowExists {
  876. if dirty {
  877. continue
  878. }
  879. _, isNewInbound := newInboundIDs[c.Id]
  880. // On a known inbound a missing row plus a live tombstone means the
  881. // master just deleted this client and the snapshot predates the
  882. // deletion push — recreating the row (at zero) would resurrect the
  883. // client. A freshly adopted inbound still gets its row (seeded at
  884. // zero) so adoption semantics stay intact.
  885. if !isNewInbound && isClientEmailTombstoned(cs.Email) {
  886. continue
  887. }
  888. var seedUp, seedDown int64
  889. if isNewInbound && !isClientEmailTombstoned(cs.Email) {
  890. seedUp, seedDown = canon.Up, canon.Down
  891. }
  892. row := &xray.ClientTraffic{
  893. InboundId: c.Id,
  894. Email: cs.Email,
  895. Enable: cs.Enable,
  896. Total: cs.Total,
  897. ExpiryTime: cs.ExpiryTime,
  898. Reset: cs.Reset,
  899. ResetDay: cs.ResetDay,
  900. Up: seedUp,
  901. Down: seedDown,
  902. LastOnline: cs.LastOnline,
  903. }
  904. if err := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "email"}}, DoNothing: true}).
  905. Create(row).Error; err != nil {
  906. return false, err
  907. }
  908. centralCS[csKey{c.Id, cs.Email}] = row
  909. centralCSByEmail[cs.Email] = row
  910. existingEmails[cs.Email] = struct{}{}
  911. structuralChange = true
  912. if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon.Up, canon.Down); err != nil {
  913. return false, err
  914. }
  915. nodeBaselines[cs.Email] = nodeTrafficCounter{Up: canon.Up, Down: canon.Down}
  916. continue
  917. }
  918. existing := centralCSByEmail[cs.Email]
  919. if existing != nil {
  920. expiryChanged := !lifecycleFrozen && existing.ExpiryTime != mergeActivationExpiry(existing.ExpiryTime, cs.ExpiryTime)
  921. // Only a real latch to disabled is structural; one-way merge never
  922. // re-enables from the node.
  923. enableChanged := !lifecycleFrozen && existing.Enable && !cs.Enable &&
  924. !nodeDisableIsStale(existing, cs, now, deltaUp, deltaDown)
  925. metaChanged := !lifecycleFrozen && (existing.Total != cs.Total || existing.Reset != cs.Reset)
  926. if enableChanged || metaChanged || expiryChanged {
  927. structuralChange = true
  928. }
  929. }
  930. renewed := !lifecycleFrozen && seen && existing != nil && nodeClientRenewed(existing, cs, canon, base)
  931. if renewed {
  932. // Reject when the node's own settings still carry the old absolute:
  933. // lagging ClientStats after a master shorten mimic a renew (#6228).
  934. if snapExpiries == nil {
  935. snapExpiries = settingsClientAbsoluteExpiries(snapIb.Settings)
  936. }
  937. if se, ok := snapExpiries[cs.Email]; ok && se <= existing.ExpiryTime {
  938. renewed = false
  939. }
  940. }
  941. if renewed {
  942. // A renewal starts a fresh quota window: adopt the node's counters
  943. // and enable state, drop stale pushes (mirrors autoRenewClients).
  944. if err := tx.Exec(
  945. fmt.Sprintf(
  946. `UPDATE client_traffics
  947. SET up = ?, down = ?, enable = ?, total = ?,
  948. expiry_time = ?, reset = ?, reset_day = ?, reset_count = ?, last_online = %s
  949. WHERE email = ?`,
  950. database.GreatestExpr("last_online", "?"),
  951. ),
  952. canon.Up, canon.Down, cs.Enable, cs.Total,
  953. cs.ExpiryTime, cs.Reset, cs.ResetDay, cs.ResetCount,
  954. cs.LastOnline, cs.Email,
  955. ).Error; err != nil {
  956. return false, err
  957. }
  958. if err := clearGlobalTraffic(tx, cs.Email); err != nil {
  959. return false, err
  960. }
  961. existing.Up = canon.Up
  962. existing.Down = canon.Down
  963. existing.Enable = cs.Enable
  964. existing.Total = cs.Total
  965. existing.ExpiryTime = cs.ExpiryTime
  966. existing.Reset = cs.Reset
  967. existing.ResetCount = cs.ResetCount
  968. structuralChange = true
  969. } else if lifecycleFrozen {
  970. // Push pending or just landed: only counters may move, the master
  971. // keeps expiry/enable/total/reset.
  972. if err := tx.Exec(
  973. fmt.Sprintf(
  974. `UPDATE client_traffics
  975. SET up = %s, down = %s, last_online = %s
  976. WHERE email = ?`,
  977. database.ClampedAddExpr("up"),
  978. database.ClampedAddExpr("down"),
  979. database.GreatestExpr("last_online", "?"),
  980. ),
  981. deltaUp, deltaDown, cs.LastOnline, cs.Email,
  982. ).Error; err != nil {
  983. return false, err
  984. }
  985. if existing != nil {
  986. existing.Up = clampTrafficCounter(existing.Up + deltaUp)
  987. existing.Down = clampTrafficCounter(existing.Down + deltaDown)
  988. }
  989. } else {
  990. enableExpr := database.ClientTrafficEnableMergeExpr()
  991. expiryExpr := database.ClientTrafficExpiryMergeExpr()
  992. if err := tx.Exec(
  993. fmt.Sprintf(
  994. `UPDATE client_traffics
  995. SET up = %s, down = %s, enable = %s, total = ?,
  996. expiry_time = %s,
  997. reset = ?, reset_day = ?, last_online = %s
  998. WHERE email = ?`,
  999. database.ClampedAddExpr("up"),
  1000. database.ClampedAddExpr("down"),
  1001. enableExpr,
  1002. expiryExpr,
  1003. database.GreatestExpr("last_online", "?"),
  1004. ),
  1005. deltaUp, deltaDown,
  1006. cs.Enable, cs.ExpiryTime, cs.Total, now, deltaUp, deltaDown,
  1007. cs.Total,
  1008. cs.ExpiryTime, cs.Reset, cs.ResetDay,
  1009. cs.LastOnline, cs.Email,
  1010. ).Error; err != nil {
  1011. return false, err
  1012. }
  1013. if existing != nil {
  1014. priorExpiry := existing.ExpiryTime
  1015. if !cs.Enable && !nodeDisableIsStale(existing, cs, now, deltaUp, deltaDown) {
  1016. existing.Enable = false
  1017. }
  1018. existing.ExpiryTime = mergeActivationExpiry(priorExpiry, cs.ExpiryTime)
  1019. existing.Up = clampTrafficCounter(existing.Up + deltaUp)
  1020. existing.Down = clampTrafficCounter(existing.Down + deltaDown)
  1021. existing.Total = cs.Total
  1022. existing.Reset = cs.Reset
  1023. }
  1024. }
  1025. // A dip plus a lagging longer expiry mimics nodeClientRenewed and would
  1026. // undo a master shorten once the freeze lifts (#6228).
  1027. if lifecycleFrozen && seen && (canon.Up < base.Up || canon.Down < base.Down) {
  1028. continue
  1029. }
  1030. if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon.Up, canon.Down); err != nil {
  1031. return false, err
  1032. }
  1033. nodeBaselines[cs.Email] = nodeTrafficCounter{Up: canon.Up, Down: canon.Down}
  1034. }
  1035. for k, existing := range centralCS {
  1036. if dirty {
  1037. continue
  1038. }
  1039. if k.inboundID != c.Id {
  1040. continue
  1041. }
  1042. if _, kept := snapEmails[k.email]; kept {
  1043. continue
  1044. }
  1045. // Gone from this inbound's stats but still reported by the node under
  1046. // a sibling inbound: both the shared accumulator row and the (node,
  1047. // email) baseline must survive, or the sibling's next delta would
  1048. // compute against nothing and freeze the counter (#5202).
  1049. if _, still := snapEmailsAll[k.email]; still {
  1050. continue
  1051. }
  1052. if err := tx.Where("node_id = ? AND email = ?", nodeID, existing.Email).
  1053. Delete(&model.NodeClientTraffic{}).Error; err != nil {
  1054. return false, err
  1055. }
  1056. // Same shared-accumulator rule as the inbound-removal sweep above:
  1057. // keep the row while another inbound still references the email.
  1058. stillUsed, uErr := s.emailUsedByOtherInbounds(existing.Email, c.Id)
  1059. if uErr != nil {
  1060. return false, uErr
  1061. }
  1062. // Usage, quota and expiry live on this row, so a client the orphan
  1063. // sweep will mark keeps it until the reaper confirms the removal.
  1064. if !stillUsed && !clientRecordExists(tx, existing.Email) {
  1065. if err := tx.Where("inbound_id = ? AND email = ?", c.Id, existing.Email).
  1066. Delete(&xray.ClientTraffic{}).Error; err != nil {
  1067. return false, err
  1068. }
  1069. }
  1070. structuralChange = true
  1071. }
  1072. }
  1073. type oldSet struct {
  1074. inboundID int
  1075. emails map[string]struct{}
  1076. }
  1077. var perInboundOld []oldSet
  1078. syncFailedInbounds := map[int]struct{}{}
  1079. for _, p := range pendingAdopts {
  1080. lifted, liftChanged := liftClientLifecycleInSettings(p.wireSettings, centralCSByEmail)
  1081. adoptedSettings := p.wireSettings
  1082. if liftChanged {
  1083. adoptedSettings = lifted
  1084. lifecycleLifted = true
  1085. }
  1086. if p.central.Settings != adoptedSettings {
  1087. if err := tx.Model(model.Inbound{}).
  1088. Where("id = ?", p.central.Id).
  1089. Update("settings", adoptedSettings).Error; err != nil {
  1090. return false, err
  1091. }
  1092. structuralChange = true
  1093. }
  1094. // The fingerprint stamps the un-lifted wire blob on purpose: a lift must
  1095. // leave reconcile a mismatch to re-push against.
  1096. if liftChanged || adoptedWireChanged(p.central, p.snapIb, p.wireSettings) {
  1097. adoptedInbounds = append(adoptedInbounds, adoptedWireInbound(p.central, p.snapIb, p.wireSettings))
  1098. }
  1099. }
  1100. for _, snapIb := range snap.Inbounds {
  1101. if snapIb == nil {
  1102. continue
  1103. }
  1104. c, ok := tagToCentral[snapIb.Tag]
  1105. if !ok {
  1106. continue
  1107. }
  1108. if dirty {
  1109. continue
  1110. }
  1111. var oldEmailsRows []string
  1112. if err := tx.Table("clients").
  1113. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  1114. Where("client_inbounds.inbound_id = ?", c.Id).
  1115. Pluck("email", &oldEmailsRows).Error; err == nil {
  1116. oldEmails := make(map[string]struct{}, len(oldEmailsRows))
  1117. for _, e := range oldEmailsRows {
  1118. if e != "" {
  1119. oldEmails[e] = struct{}{}
  1120. }
  1121. }
  1122. perInboundOld = append(perInboundOld, oldSet{inboundID: c.Id, emails: oldEmails})
  1123. }
  1124. clients, gcErr := s.GetClients(snapIb)
  1125. if gcErr != nil {
  1126. logger.Warningf("setRemoteTraffic: parse clients for tag %q failed: %v", snapIb.Tag, gcErr)
  1127. continue
  1128. }
  1129. csByEmail := make(map[string]xray.ClientTraffic, len(snapIb.ClientStats))
  1130. for _, cs := range snapIb.ClientStats {
  1131. csByEmail[cs.Email] = cs
  1132. }
  1133. filtered := clients[:0]
  1134. for i := range clients {
  1135. if isClientEmailTombstoned(clients[i].Email) {
  1136. continue
  1137. }
  1138. existing := centralCSByEmail[clients[i].Email]
  1139. var csPtr *xray.ClientTraffic
  1140. if cs, hit := csByEmail[clients[i].Email]; hit {
  1141. csCopy := cs
  1142. csPtr = &csCopy
  1143. }
  1144. applyMasterClientLifecycle(&clients[i], existing, csPtr)
  1145. filtered = append(filtered, clients[i])
  1146. }
  1147. localEmails := make([]string, 0, len(filtered))
  1148. for i := range filtered {
  1149. if filtered[i].Email != "" {
  1150. localEmails = append(localEmails, filtered[i].Email)
  1151. }
  1152. }
  1153. if len(localEmails) > 0 {
  1154. var localMeta []struct {
  1155. Email string
  1156. Comment string `gorm:"column:comment"`
  1157. }
  1158. if err := tx.Table("clients").
  1159. Select("email, comment").
  1160. Where("email IN ?", localEmails).
  1161. Find(&localMeta).Error; err == nil {
  1162. commentByEmail := make(map[string]string, len(localMeta))
  1163. for _, m := range localMeta {
  1164. commentByEmail[m.Email] = m.Comment
  1165. }
  1166. for i := range filtered {
  1167. if cmt, ok := commentByEmail[filtered[i].Email]; ok {
  1168. filtered[i].Comment = cmt
  1169. }
  1170. }
  1171. }
  1172. }
  1173. if len(localEmails) > 0 {
  1174. foreign, err := clientEmailsOwnedElsewhere(tx, nodeID, localEmails)
  1175. if err != nil {
  1176. return false, err
  1177. }
  1178. if len(foreign) > 0 {
  1179. kept := filtered[:0]
  1180. for i := range filtered {
  1181. if _, claimed := foreign[filtered[i].Email]; !claimed {
  1182. kept = append(kept, filtered[i])
  1183. continue
  1184. }
  1185. key := fmt.Sprintf("%d:%s", nodeID, filtered[i].Email)
  1186. if _, seen := reportedForeignClientClaim.LoadOrStore(key, struct{}{}); !seen {
  1187. logger.Warningf(
  1188. "setRemoteTraffic: node %d reported client %q, which is attached only to inbounds of another node — not adopting (rename one side to remove the duplicate email)",
  1189. nodeID, filtered[i].Email,
  1190. )
  1191. }
  1192. }
  1193. filtered = kept
  1194. }
  1195. }
  1196. if err := s.clientService.SyncInbound(tx, c.Id, filtered); err != nil {
  1197. logger.Warningf("setRemoteTraffic: sync clients for tag %q failed: %v", snapIb.Tag, err)
  1198. syncFailedInbounds[c.Id] = struct{}{}
  1199. }
  1200. }
  1201. for _, old := range perInboundOld {
  1202. // The sweep's premise is that links were just rebuilt from the snapshot,
  1203. // which is exactly what a failed SyncInbound violates.
  1204. if _, failed := syncFailedInbounds[old.inboundID]; failed {
  1205. continue
  1206. }
  1207. var stillAttached []string
  1208. if err := tx.Table("clients").
  1209. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  1210. Where("client_inbounds.inbound_id = ?", old.inboundID).
  1211. Pluck("email", &stillAttached).Error; err != nil {
  1212. continue
  1213. }
  1214. stillSet := make(map[string]struct{}, len(stillAttached))
  1215. for _, e := range stillAttached {
  1216. stillSet[e] = struct{}{}
  1217. }
  1218. for email := range old.emails {
  1219. if _, kept := stillSet[email]; kept {
  1220. continue
  1221. }
  1222. var attachmentCount int64
  1223. if err := tx.Table("client_inbounds").
  1224. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  1225. Where("clients.email = ?", email).
  1226. Count(&attachmentCount).Error; err != nil {
  1227. continue
  1228. }
  1229. if attachmentCount > 0 {
  1230. continue
  1231. }
  1232. // "Ended the merge unattached" is true for a real remote deletion and
  1233. // equally true for a bad merge, so record a strike instead of deleting.
  1234. if err := markSyncOrphan(tx, email, now); err != nil {
  1235. logger.Warningf("setRemoteTraffic: mark orphan %q failed: %v", email, err)
  1236. continue
  1237. }
  1238. structuralChange = true
  1239. }
  1240. }
  1241. if err := clearSyncOrphanMarks(tx); err != nil {
  1242. logger.Warning("setRemoteTraffic: clear orphan marks failed:", err)
  1243. }
  1244. if err := liftActivatedClientRecordExpiries(tx); err != nil {
  1245. logger.Warning("setRemoteTraffic: lift activated expiries failed:", err)
  1246. }
  1247. if err := tx.Commit().Error; err != nil {
  1248. return false, err
  1249. }
  1250. committed = true
  1251. if lifecycleLifted && !dirty {
  1252. var already model.Node
  1253. if err := database.GetDB().Select("config_dirty").Where("id = ?", nodeID).First(&already).Error; err == nil && already.ConfigDirty {
  1254. logger.Debugf("setRemoteTraffic: node %d lifecycle lift; already dirty", nodeID)
  1255. } else {
  1256. logger.Infof("setRemoteTraffic: node %d lifecycle lift; marking dirty for re-push", nodeID)
  1257. if err := (&NodeService{}).MarkNodeDirty(nodeID); err != nil {
  1258. logger.Warningf("setRemoteTraffic: mark node %d dirty after lifecycle lift failed: %v", nodeID, err)
  1259. }
  1260. }
  1261. }
  1262. if len(adoptedInbounds) > 0 {
  1263. if mgr := runtime.GetManager(); mgr != nil {
  1264. if rt, rtErr := mgr.RuntimeFor(&nodeID); rtErr == nil {
  1265. if rem, ok := rt.(*runtime.Remote); ok {
  1266. for _, ib := range adoptedInbounds {
  1267. rem.RecordAdoptedInbound(ib)
  1268. }
  1269. }
  1270. }
  1271. }
  1272. }
  1273. if process := currentXrayProcess(); process != nil {
  1274. tree := snap.OnlineTree
  1275. switch {
  1276. case len(tree) == 0 && len(snap.OnlineEmails) > 0:
  1277. // Old-build node (no GUID tree): key its flat online list under its
  1278. // own effective identity so attribution still works for that branch.
  1279. tree = map[string][]string{selfKey: snap.OnlineEmails}
  1280. case guidShared && len(tree) > 0:
  1281. // Newer cloned node: its own clients arrive keyed under the shared
  1282. // panelGuid. Remap just that entry to the node-unique key so the
  1283. // clones don't merge; descendant subtrees keep their distinct GUIDs.
  1284. if _, ok := tree[nodeRow.Guid]; ok {
  1285. tree = remapGuidTreeKey(tree, nodeRow.Guid, selfKey)
  1286. }
  1287. }
  1288. process.SetNodeOnlineTree(nodeID, tree)
  1289. activeTree := normalizeActiveInboundTreeTags(snap.ActiveInboundTree, tagToCentral)
  1290. if guidShared && len(activeTree) > 0 {
  1291. if _, ok := activeTree[nodeRow.Guid]; ok {
  1292. activeTree = remapGuidTreeKey(activeTree, nodeRow.Guid, selfKey)
  1293. }
  1294. }
  1295. if len(activeTree) > 0 {
  1296. activeTree = filterGuidTreeKeys(activeTree, activeInboundGuidKeys(snap.Inbounds, tagToCentral, originGuidFor))
  1297. }
  1298. process.SetNodeActiveInboundTree(nodeID, activeTree)
  1299. }
  1300. return structuralChange, nil
  1301. }
  1302. func (s *InboundService) restartRemoteNodesOnDisable(nodeIDs []int) {
  1303. restartOnDisable, err := (&SettingService{}).GetRestartXrayOnClientDisable()
  1304. if err != nil {
  1305. logger.Warning("disableInvalidClients: get RestartXrayOnClientDisable failed:", err)
  1306. return
  1307. }
  1308. if !restartOnDisable {
  1309. return
  1310. }
  1311. for _, nodeID := range nodeIDs {
  1312. nodeIDCopy := nodeID
  1313. rt, rtErr := runtime.GetManager().RuntimeFor(&nodeIDCopy)
  1314. if rtErr != nil {
  1315. logger.Warning("disableInvalidClients: get runtime for node", nodeID, "failed:", rtErr)
  1316. continue
  1317. }
  1318. if rtErr = rt.RestartXray(context.Background()); rtErr != nil {
  1319. logger.Warning("disableInvalidClients: restart xray on node", nodeID, "failed:", rtErr)
  1320. }
  1321. }
  1322. }
  1323. func (s *InboundService) GetOnlineClients() []string {
  1324. process := currentXrayProcess()
  1325. if process == nil {
  1326. return []string{}
  1327. }
  1328. return process.GetOnlineClients()
  1329. }
  1330. // GetOnlineClientsByGuid returns online emails keyed by the panelGuid of the
  1331. // node that physically hosts each set: this panel's own clients under its own
  1332. // GUID, plus every node in the tree under its GUID (#4983). Replaces the old
  1333. // node-id keying so a client three hops down is attributed to its real node,
  1334. // not the intermediate one it was synced through.
  1335. func (s *InboundService) GetOnlineClientsByGuid() map[string][]string {
  1336. process := currentXrayProcess()
  1337. if process == nil {
  1338. return map[string][]string{}
  1339. }
  1340. out := process.GetMergedNodeTrees()
  1341. if local := process.GetLocalOnlineClients(); len(local) > 0 {
  1342. if guid := s.panelGuid(); guid != "" {
  1343. out[guid] = mergeEmails(out[guid], local)
  1344. }
  1345. }
  1346. return out
  1347. }
  1348. // GetActiveInboundsByGuid returns the inbound tags that carried traffic within
  1349. // the grace window, keyed by the panelGuid of the node that physically hosts
  1350. // each inbound. A GUID missing from the map means "don't gate" for that node's
  1351. // inbounds (old-build node or no active-inbound signal).
  1352. func (s *InboundService) GetActiveInboundsByGuid() map[string][]string {
  1353. process := currentXrayProcess()
  1354. if process == nil {
  1355. return map[string][]string{}
  1356. }
  1357. out := process.GetMergedActiveInboundTrees()
  1358. active := process.GetLocalActiveInbounds()
  1359. if len(active) == 0 {
  1360. return out
  1361. }
  1362. guid := s.panelGuid()
  1363. if guid == "" {
  1364. return out
  1365. }
  1366. out[guid] = mergeEmails(out[guid], active)
  1367. return out
  1368. }
  1369. func (s *InboundService) SetNodeOnlineTree(nodeID int, tree map[string][]string) {
  1370. if process := currentXrayProcess(); process != nil {
  1371. process.SetNodeOnlineTree(nodeID, tree)
  1372. }
  1373. }
  1374. func (s *InboundService) ClearNodeOnlineClients(nodeID int) {
  1375. if process := currentXrayProcess(); process != nil {
  1376. process.ClearNodeOnlineClients(nodeID)
  1377. }
  1378. }
  1379. // panelGuid returns this panel's stable self-identifier, used to key the local
  1380. // panel's own clients in the per-node online maps (#4983).
  1381. func (s *InboundService) panelGuid() string {
  1382. guid, _ := (&SettingService{}).GetPanelGuid()
  1383. return guid
  1384. }
  1385. // synthNodeGuid is the stable per-node fallback identity for a directly-attached
  1386. // node whose panel hasn't reported a panelGuid yet (old build). Node ids are
  1387. // master-local, so this only composes for direct nodes — exactly the pre-#4983
  1388. // flat-topology case where an old-build node appears.
  1389. func synthNodeGuid(nodeID int) string {
  1390. return fmt.Sprintf("node:%d", nodeID)
  1391. }
  1392. // mergeEmails returns the deduped union of two email slices.
  1393. func mergeEmails(a, b []string) []string {
  1394. if len(a) == 0 {
  1395. return b
  1396. }
  1397. seen := make(map[string]struct{}, len(a)+len(b))
  1398. out := make([]string, 0, len(a)+len(b))
  1399. for _, e := range a {
  1400. if _, ok := seen[e]; !ok {
  1401. seen[e] = struct{}{}
  1402. out = append(out, e)
  1403. }
  1404. }
  1405. for _, e := range b {
  1406. if _, ok := seen[e]; !ok {
  1407. seen[e] = struct{}{}
  1408. out = append(out, e)
  1409. }
  1410. }
  1411. return out
  1412. }
  1413. func remapGuidTreeKey(tree map[string][]string, from, to string) map[string][]string {
  1414. if from == "" || to == "" || from == to {
  1415. return tree
  1416. }
  1417. remapped := make(map[string][]string, len(tree))
  1418. for guid, values := range tree {
  1419. if guid == from {
  1420. guid = to
  1421. }
  1422. remapped[guid] = mergeEmails(remapped[guid], values)
  1423. }
  1424. return remapped
  1425. }
  1426. func normalizeActiveInboundTreeTags(tree map[string][]string, tagToCentral map[string]*model.Inbound) map[string][]string {
  1427. if len(tree) == 0 {
  1428. return nil
  1429. }
  1430. out := make(map[string][]string, len(tree))
  1431. for guid, tags := range tree {
  1432. if guid == "" || len(tags) == 0 {
  1433. continue
  1434. }
  1435. seen := make(map[string]struct{}, len(tags))
  1436. for _, tag := range tags {
  1437. if tag == "" {
  1438. continue
  1439. }
  1440. if central, ok := tagToCentral[tag]; ok && central != nil && central.Tag != "" {
  1441. tag = central.Tag
  1442. }
  1443. if _, dup := seen[tag]; dup {
  1444. continue
  1445. }
  1446. seen[tag] = struct{}{}
  1447. out[guid] = append(out[guid], tag)
  1448. }
  1449. }
  1450. if len(out) == 0 {
  1451. return nil
  1452. }
  1453. return out
  1454. }
  1455. func activeInboundGuidKeys(inbounds []*model.Inbound, tagToCentral map[string]*model.Inbound, originGuidFor func(*model.Inbound) string) map[string]struct{} {
  1456. allowed := make(map[string]struct{})
  1457. for _, ib := range inbounds {
  1458. if ib == nil {
  1459. continue
  1460. }
  1461. if _, ok := tagToCentral[ib.Tag]; !ok {
  1462. continue
  1463. }
  1464. if guid := originGuidFor(ib); guid != "" {
  1465. allowed[guid] = struct{}{}
  1466. }
  1467. }
  1468. return allowed
  1469. }
  1470. func filterGuidTreeKeys(tree map[string][]string, allowed map[string]struct{}) map[string][]string {
  1471. if len(tree) == 0 || len(allowed) == 0 {
  1472. return nil
  1473. }
  1474. out := make(map[string][]string, len(tree))
  1475. for guid, values := range tree {
  1476. if _, ok := allowed[guid]; !ok {
  1477. continue
  1478. }
  1479. if len(values) > 0 {
  1480. out[guid] = values
  1481. }
  1482. }
  1483. if len(out) == 0 {
  1484. return nil
  1485. }
  1486. return out
  1487. }
  1488. func (s *InboundService) GetClientsLastOnline() (map[string]int64, error) {
  1489. db := database.GetDB()
  1490. var rows []xray.ClientTraffic
  1491. err := db.Model(&xray.ClientTraffic{}).Select("email, last_online").Find(&rows).Error
  1492. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1493. return nil, err
  1494. }
  1495. result := make(map[string]int64, len(rows))
  1496. for _, r := range rows {
  1497. result[r.Email] = r.LastOnline
  1498. }
  1499. return result, nil
  1500. }
  1501. // RefreshLocalOnlineClients folds the emails and inbound tags active on this
  1502. // panel's own xray this poll into the local online/active sets, applying the
  1503. // grace window and pruning stale entries. Pass nil to only prune. See
  1504. // xray.Process for why the local sets are kept separate from the shared
  1505. // last_online column.
  1506. func (s *InboundService) RefreshLocalOnlineClients(activeEmails, activeInboundTags []string) {
  1507. if process := currentXrayProcess(); process != nil {
  1508. process.RefreshLocalOnline(activeEmails, activeInboundTags, time.Now().UnixMilli(), onlineGracePeriodMs)
  1509. }
  1510. }
  1511. func (s *InboundService) FilterAndSortClientEmails(emails []string) ([]string, []string, error) {
  1512. db := database.GetDB()
  1513. // Step 1: Get ClientTraffic records for emails in the input list.
  1514. // Chunked to stay under SQLite's bind-variable limit on huge inputs.
  1515. uniqEmails := uniqueNonEmptyStrings(emails)
  1516. clients := make([]xray.ClientTraffic, 0, len(uniqEmails))
  1517. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  1518. var page []xray.ClientTraffic
  1519. if err := db.Where("email IN ?", batch).Find(&page).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1520. return nil, nil, err
  1521. }
  1522. clients = append(clients, page...)
  1523. }
  1524. // Step 2: Sort clients by (Up + Down) descending
  1525. sort.Slice(clients, func(i, j int) bool {
  1526. return (clients[i].Up + clients[i].Down) > (clients[j].Up + clients[j].Down)
  1527. })
  1528. // Step 3: Extract sorted valid emails and track found ones
  1529. validEmails := make([]string, 0, len(clients))
  1530. found := make(map[string]bool)
  1531. for _, client := range clients {
  1532. validEmails = append(validEmails, client.Email)
  1533. found[client.Email] = true
  1534. }
  1535. // Step 4: Identify emails that were not found in the database
  1536. extraEmails := make([]string, 0)
  1537. for _, email := range emails {
  1538. if !found[email] {
  1539. extraEmails = append(extraEmails, email)
  1540. }
  1541. }
  1542. return validEmails, extraEmails, nil
  1543. }