inbound_node.go 60 KB

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