1
0

inbound_node.go 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735
  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. if candidate.OriginNodeGuid == origin &&
  654. candidate.Port == snapIb.Port &&
  655. candidate.Protocol == snapIb.Protocol &&
  656. strings.TrimSpace(candidate.Listen) == strings.TrimSpace(snapIb.Listen) {
  657. compatible = append(compatible, candidate)
  658. }
  659. }
  660. switch len(compatible) {
  661. case 1:
  662. c, ok = compatible[0], true
  663. tagToCentral[snapIb.Tag] = c
  664. snapTags[c.Tag] = struct{}{}
  665. case 0:
  666. // A genuinely new inbound follows the normal adoption path.
  667. default:
  668. return false, fmt.Errorf("setRemoteTraffic: inbound %q has ambiguous compatible central aliases", snapIb.Tag)
  669. }
  670. }
  671. if !ok {
  672. if dirty {
  673. continue
  674. }
  675. // Try snap.Tag first; on collision fall back to the n<id>-
  676. // prefixed form so local+node can both own the same port.
  677. pickFreeTag := func() (string, error) {
  678. candidates := []string{snapIb.Tag}
  679. if prefix != "" && !strings.HasPrefix(snapIb.Tag, prefix) {
  680. candidates = append(candidates, prefix+snapIb.Tag)
  681. }
  682. for _, t := range candidates {
  683. var owner model.Inbound
  684. err := tx.Where("tag = ?", t).First(&owner).Error
  685. if errors.Is(err, gorm.ErrRecordNotFound) {
  686. return t, nil
  687. }
  688. if err != nil {
  689. return "", err
  690. }
  691. }
  692. return "", nil
  693. }
  694. chosenTag, err := pickFreeTag()
  695. if err != nil {
  696. logger.Warningf("setRemoteTraffic: check tag %q failed: %v", snapIb.Tag, err)
  697. continue
  698. }
  699. if chosenTag == "" {
  700. key := fmt.Sprintf("%d:%s", nodeID, snapIb.Tag)
  701. if _, seen := reportedRemoteTagConflict.LoadOrStore(key, struct{}{}); !seen {
  702. logger.Warningf(
  703. "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)",
  704. snapIb.Tag, nodeID, nodeID,
  705. )
  706. }
  707. continue
  708. }
  709. reportedRemoteTagConflict.Delete(fmt.Sprintf("%d:%s", nodeID, snapIb.Tag))
  710. newIb := model.Inbound{
  711. UserId: defaultUserId,
  712. NodeID: &nodeID,
  713. OriginNodeGuid: originGuidFor(snapIb),
  714. Tag: chosenTag,
  715. Listen: snapIb.Listen,
  716. Port: snapIb.Port,
  717. Protocol: snapIb.Protocol,
  718. Settings: snapIb.Settings,
  719. StreamSettings: snapIb.StreamSettings,
  720. Sniffing: snapIb.Sniffing,
  721. TrafficReset: snapIb.TrafficReset,
  722. TrafficResetDay: normalizeTrafficResetDay(snapIb.TrafficResetDay),
  723. LastTrafficResetTime: snapIb.LastTrafficResetTime,
  724. Enable: snapIb.Enable,
  725. Remark: snapIb.Remark,
  726. SubSortIndex: normalizeSubSortIndex(snapIb.SubSortIndex),
  727. ExcludeFromSub: snapIb.ExcludeFromSub,
  728. Total: snapIb.Total,
  729. ExpiryTime: snapIb.ExpiryTime,
  730. Up: snapIb.Up,
  731. Down: snapIb.Down,
  732. ShareAddrStrategy: "node",
  733. DisableFlow: snapIb.DisableFlow,
  734. }
  735. if err := tx.Create(&newIb).Error; err != nil {
  736. logger.Warningf("setRemoteTraffic: create central inbound for tag %q failed: %v", snapIb.Tag, err)
  737. continue
  738. }
  739. tagToCentral[snapIb.Tag] = &newIb
  740. if newIb.Tag != snapIb.Tag {
  741. tagToCentral[newIb.Tag] = &newIb
  742. }
  743. if rows := adoptedHostRows(snap.HostGroups, snapIb.Id, newIb.Id); len(rows) > 0 {
  744. if err := tx.Create(&rows).Error; err != nil {
  745. logger.Warningf("setRemoteTraffic: adopt host rows for tag %q failed: %v", newIb.Tag, err)
  746. }
  747. }
  748. newInboundIDs[newIb.Id] = struct{}{}
  749. structuralChange = true
  750. continue
  751. }
  752. inGrace := c.LastTrafficResetTime > 0 && now-c.LastTrafficResetTime < resetGracePeriodMs
  753. // Adopting the node's settings verbatim would re-add a client the master
  754. // deleted moments ago if this snapshot was fetched before the deletion
  755. // push landed — filter just-deleted emails out while their tombstone lives.
  756. adoptedSettings := snapIb.Settings
  757. if stripped, changed := stripTombstonedClients(adoptedSettings); changed {
  758. adoptedSettings = stripped
  759. }
  760. if deduped, changed := dedupeSettingsClients(adoptedSettings); changed {
  761. adoptedSettings = deduped
  762. }
  763. updates := map[string]any{}
  764. if !dirty && snapshotDropsEveryHubClient(tx, c.Id, adoptedSettings) {
  765. degradedInbounds[c.Id] = c.Tag
  766. } else if !dirty {
  767. // Defer lifecycle lift until after client_traffics absorbs this tick's
  768. // deltas so quota stale-disable matches SQL (#6228).
  769. pendingAdopts = append(pendingAdopts, pendingAdopt{
  770. central: c, snapIb: snapIb, wireSettings: adoptedSettings,
  771. })
  772. updates["enable"] = snapIb.Enable
  773. updates["remark"] = snapIb.Remark
  774. updates["sub_sort_index"] = normalizeSubSortIndex(snapIb.SubSortIndex)
  775. updates["listen"] = snapIb.Listen
  776. updates["port"] = snapIb.Port
  777. updates["protocol"] = snapIb.Protocol
  778. updates["total"] = snapIb.Total
  779. updates["expiry_time"] = snapIb.ExpiryTime
  780. updates["stream_settings"] = snapIb.StreamSettings
  781. updates["sniffing"] = snapIb.Sniffing
  782. updates["traffic_reset"] = snapIb.TrafficReset
  783. updates["traffic_reset_day"] = normalizeTrafficResetDay(snapIb.TrafficResetDay)
  784. updates["last_traffic_reset_time"] = snapIb.LastTrafficResetTime
  785. }
  786. if !inGrace || (snapIb.Up+snapIb.Down) <= (c.Up+c.Down) {
  787. updates["up"] = snapIb.Up
  788. updates["down"] = snapIb.Down
  789. }
  790. // Physical-home attribution is independent of config-dirty state, so
  791. // keep it current even while the node has pending offline edits. Writes
  792. // once to backfill an existing row, then stays equal (#4983).
  793. if og := originGuidFor(snapIb); c.OriginNodeGuid != og {
  794. updates["origin_node_guid"] = og
  795. }
  796. if !dirty && (c.Remark != snapIb.Remark ||
  797. c.Listen != snapIb.Listen ||
  798. c.Port != snapIb.Port ||
  799. c.Total != snapIb.Total ||
  800. c.ExpiryTime != snapIb.ExpiryTime ||
  801. c.Enable != snapIb.Enable) {
  802. structuralChange = true
  803. }
  804. if len(updates) > 0 {
  805. if err := tx.Model(model.Inbound{}).
  806. Where("id = ?", c.Id).
  807. Updates(updates).Error; err != nil {
  808. return false, err
  809. }
  810. }
  811. }
  812. for _, c := range central {
  813. if dirty {
  814. continue
  815. }
  816. // A node inbound created disabled is never delivered, so its absence from
  817. // the snapshot is ambiguous rather than evidence of a node-side delete.
  818. if !c.Enable {
  819. continue
  820. }
  821. if len(snapTags) == 0 {
  822. // A node mid-restart or with a transient DB error can return an empty
  823. // inbound list with success=true. Treat "zero inbounds reported" as
  824. // "nothing to say", not "delete all my inbounds" — otherwise a blip
  825. // wipes the node's central inbounds and every client on them (and
  826. // resets traffic history on re-create). A real per-inbound deletion
  827. // still sweeps, because the node keeps reporting its other inbounds.
  828. continue
  829. }
  830. if _, kept := snapTags[c.Tag]; kept {
  831. continue
  832. }
  833. if unmanagedTag(c.Tag) {
  834. continue
  835. }
  836. // This drops the central inbound and its clients' traffic history, so say
  837. // so: silent removal is indistinguishable from an inbound never arriving.
  838. logger.Warningf("setRemoteTraffic: node %d no longer reports inbound %q (id %d, port %d) — removing it centrally", nodeID, c.Tag, c.Id, c.Port)
  839. var goneEmails []string
  840. if err := tx.Model(xray.ClientTraffic{}).
  841. Where("inbound_id = ?", c.Id).
  842. Pluck("email", &goneEmails).Error; err != nil {
  843. return false, err
  844. }
  845. if len(goneEmails) > 0 {
  846. // Baselines are per (node, email), not per inbound: keep them for
  847. // emails the snapshot still reports under a sibling inbound (#5202).
  848. baselineGone := make([]string, 0, len(goneEmails))
  849. for _, e := range goneEmails {
  850. if _, still := snapEmailsAll[e]; !still {
  851. baselineGone = append(baselineGone, e)
  852. }
  853. }
  854. // Chunk to avoid SQLite bind var limit when a node has many clients
  855. // removed (e.g. after API bulk delete or structural change on node inbound).
  856. for _, batch := range chunkStrings(baselineGone, sqliteMaxVars) {
  857. if err := tx.Where("node_id = ? AND email IN ?", nodeID, batch).
  858. Delete(&model.NodeClientTraffic{}).Error; err != nil {
  859. return false, err
  860. }
  861. }
  862. // The per-email row is the shared accumulator across every inbound
  863. // (and node) the email is attached to. Only drop it when this was the
  864. // email's last inbound — wiping it while a sibling still feeds it
  865. // loses the summed history, and the next node sync would re-seed the
  866. // row with that node's counter alone.
  867. sharedEmails, sErr := s.emailsUsedByOtherInbounds(goneEmails, c.Id)
  868. if sErr != nil {
  869. return false, sErr
  870. }
  871. delEmails := make([]string, 0, len(goneEmails))
  872. for _, e := range goneEmails {
  873. if !sharedEmails[strings.ToLower(strings.TrimSpace(e))] {
  874. delEmails = append(delEmails, e)
  875. }
  876. }
  877. for _, batch := range chunkStrings(delEmails, sqliteMaxVars) {
  878. if err := tx.Where("inbound_id = ? AND email IN ?", c.Id, batch).
  879. Delete(&xray.ClientTraffic{}).Error; err != nil {
  880. return false, err
  881. }
  882. }
  883. }
  884. if err := s.clientService.DetachInbound(tx, c.Id); err != nil {
  885. return false, err
  886. }
  887. if err := tx.Where("id = ?", c.Id).
  888. Delete(&model.Inbound{}).Error; err != nil {
  889. return false, err
  890. }
  891. delete(tagToCentral, c.Tag)
  892. structuralChange = true
  893. }
  894. for _, snapIb := range snap.Inbounds {
  895. if snapIb == nil {
  896. continue
  897. }
  898. c, ok := tagToCentral[snapIb.Tag]
  899. if !ok {
  900. continue
  901. }
  902. snapEmails := make(map[string]struct{}, len(snapIb.ClientStats))
  903. // Parsed once per inbound on the first renewal candidate, not per client.
  904. var snapExpiries map[string]int64
  905. attachedOnNode, membershipKnown := snapshotAttachedEmails(snapIb.Settings)
  906. for _, cs := range snapIb.ClientStats {
  907. // A node detach keeps the stat row, so its quota and verdict are stale (#6724).
  908. if _, attached := attachedOnNode[strings.ToLower(cs.Email)]; membershipKnown && !attached {
  909. continue
  910. }
  911. snapEmails[cs.Email] = struct{}{}
  912. // Node-wide total, not this inbound's possibly-stale copy (#5274).
  913. canon := nodeEmailTotals[cs.Email]
  914. // Until the node applies a reset it owes, its verdict rests on the
  915. // pre-reset counters: only usage may move for this client.
  916. _, owed := owedResets[cs.Email]
  917. clientFrozen := lifecycleFrozen || owed
  918. base, seen := nodeBaselines[cs.Email]
  919. var deltaUp, deltaDown int64
  920. if seen {
  921. if deltaUp = canon.Up - base.Up; deltaUp < 0 {
  922. deltaUp = 0
  923. }
  924. if deltaDown = canon.Down - base.Down; deltaDown < 0 {
  925. deltaDown = 0
  926. }
  927. }
  928. if _, rowExists := existingEmails[cs.Email]; !rowExists {
  929. if dirty {
  930. continue
  931. }
  932. _, isNewInbound := newInboundIDs[c.Id]
  933. // On a known inbound a missing row plus a live tombstone means the
  934. // master just deleted this client and the snapshot predates the
  935. // deletion push — recreating the row (at zero) would resurrect the
  936. // client. A freshly adopted inbound still gets its row (seeded at
  937. // zero) so adoption semantics stay intact.
  938. if !isNewInbound && isClientEmailTombstoned(cs.Email) {
  939. continue
  940. }
  941. var seedUp, seedDown int64
  942. if isNewInbound && !isClientEmailTombstoned(cs.Email) {
  943. seedUp, seedDown = canon.Up, canon.Down
  944. }
  945. row := &xray.ClientTraffic{
  946. InboundId: c.Id,
  947. Email: cs.Email,
  948. Enable: cs.Enable,
  949. Total: cs.Total,
  950. ExpiryTime: cs.ExpiryTime,
  951. Reset: cs.Reset,
  952. ResetDay: cs.ResetDay,
  953. ResetWeekday: cs.ResetWeekday,
  954. ResetMax: cs.ResetMax,
  955. ResetCount: cs.ResetCount,
  956. Up: seedUp,
  957. Down: seedDown,
  958. LastOnline: cs.LastOnline,
  959. }
  960. if err := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "email"}}, DoNothing: true}).
  961. Create(row).Error; err != nil {
  962. return false, err
  963. }
  964. centralCS[csKey{c.Id, cs.Email}] = row
  965. centralCSByEmail[cs.Email] = row
  966. existingEmails[cs.Email] = struct{}{}
  967. structuralChange = true
  968. if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon.Up, canon.Down); err != nil {
  969. return false, err
  970. }
  971. nodeBaselines[cs.Email] = nodeTrafficCounter{Up: canon.Up, Down: canon.Down}
  972. continue
  973. }
  974. existing := centralCSByEmail[cs.Email]
  975. if existing != nil {
  976. expiryChanged := !clientFrozen && existing.ExpiryTime != mergeActivationExpiry(existing.ExpiryTime, cs.ExpiryTime)
  977. // Only a real latch to disabled is structural; one-way merge never
  978. // re-enables from the node.
  979. enableChanged := !clientFrozen && existing.Enable && !cs.Enable &&
  980. !nodeDisableIsStale(existing, cs, now, deltaUp, deltaDown)
  981. metaChanged := !clientFrozen && (existing.Total != cs.Total || existing.Reset != cs.Reset || existing.ResetWeekday != cs.ResetWeekday)
  982. if enableChanged || metaChanged || expiryChanged {
  983. structuralChange = true
  984. }
  985. }
  986. renewed := !clientFrozen && seen && existing != nil && nodeClientRenewed(existing, cs, canon, base)
  987. if renewed {
  988. // Reject when the node's own settings still carry the old absolute:
  989. // lagging ClientStats after a master shorten mimic a renew (#6228).
  990. if snapExpiries == nil {
  991. snapExpiries = settingsClientAbsoluteExpiries(snapIb.Settings)
  992. }
  993. if se, ok := snapExpiries[cs.Email]; ok && se <= existing.ExpiryTime {
  994. renewed = false
  995. }
  996. }
  997. if renewed {
  998. // A renewal starts a fresh quota window: adopt the node's counters
  999. // and enable state, drop stale pushes (mirrors autoRenewClients).
  1000. if err := tx.Exec(
  1001. fmt.Sprintf(
  1002. `UPDATE client_traffics
  1003. SET up = ?, down = ?, enable = ?, total = ?,
  1004. expiry_time = ?, reset = ?, reset_day = ?, reset_weekday = ?, reset_count = ?, last_online = %s
  1005. WHERE email = ?`,
  1006. database.GreatestExpr("last_online", "?"),
  1007. ),
  1008. canon.Up, canon.Down, cs.Enable, cs.Total,
  1009. cs.ExpiryTime, cs.Reset, cs.ResetDay, cs.ResetWeekday, cs.ResetCount,
  1010. cs.LastOnline, cs.Email,
  1011. ).Error; err != nil {
  1012. return false, err
  1013. }
  1014. if err := clearGlobalTraffic(tx, cs.Email); err != nil {
  1015. return false, err
  1016. }
  1017. existing.Up = canon.Up
  1018. existing.Down = canon.Down
  1019. existing.Enable = cs.Enable
  1020. existing.Total = cs.Total
  1021. existing.ExpiryTime = cs.ExpiryTime
  1022. existing.Reset = cs.Reset
  1023. existing.ResetWeekday = cs.ResetWeekday
  1024. existing.ResetCount = cs.ResetCount
  1025. structuralChange = true
  1026. } else if clientFrozen {
  1027. // Push pending or just landed: only counters may move, the master
  1028. // keeps expiry/enable/total/reset.
  1029. if err := tx.Exec(
  1030. fmt.Sprintf(
  1031. `UPDATE client_traffics
  1032. SET up = %s, down = %s, last_online = %s
  1033. WHERE email = ?`,
  1034. database.ClampedAddExpr("up"),
  1035. database.ClampedAddExpr("down"),
  1036. database.GreatestExpr("last_online", "?"),
  1037. ),
  1038. deltaUp, deltaDown, cs.LastOnline, cs.Email,
  1039. ).Error; err != nil {
  1040. return false, err
  1041. }
  1042. if existing != nil {
  1043. existing.Up = clampTrafficCounter(existing.Up + deltaUp)
  1044. existing.Down = clampTrafficCounter(existing.Down + deltaDown)
  1045. }
  1046. } else {
  1047. enableExpr := database.ClientTrafficEnableMergeExpr()
  1048. expiryExpr := database.ClientTrafficExpiryMergeExpr()
  1049. if err := tx.Exec(
  1050. fmt.Sprintf(
  1051. `UPDATE client_traffics
  1052. SET up = %s, down = %s, enable = %s, total = ?,
  1053. expiry_time = %s,
  1054. reset = ?, reset_day = ?, reset_weekday = ?, last_online = %s
  1055. WHERE email = ?`,
  1056. database.ClampedAddExpr("up"),
  1057. database.ClampedAddExpr("down"),
  1058. enableExpr,
  1059. expiryExpr,
  1060. database.GreatestExpr("last_online", "?"),
  1061. ),
  1062. deltaUp, deltaDown,
  1063. cs.Enable, cs.ExpiryTime, cs.Total, now, deltaUp, deltaDown,
  1064. cs.Total,
  1065. cs.ExpiryTime, cs.Reset, cs.ResetDay, cs.ResetWeekday,
  1066. cs.LastOnline, cs.Email,
  1067. ).Error; err != nil {
  1068. return false, err
  1069. }
  1070. if existing != nil {
  1071. priorExpiry := existing.ExpiryTime
  1072. if !cs.Enable && !nodeDisableIsStale(existing, cs, now, deltaUp, deltaDown) {
  1073. existing.Enable = false
  1074. }
  1075. existing.ExpiryTime = mergeActivationExpiry(priorExpiry, cs.ExpiryTime)
  1076. existing.Up = clampTrafficCounter(existing.Up + deltaUp)
  1077. existing.Down = clampTrafficCounter(existing.Down + deltaDown)
  1078. existing.Total = cs.Total
  1079. existing.Reset = cs.Reset
  1080. existing.ResetWeekday = cs.ResetWeekday
  1081. }
  1082. }
  1083. // A dip plus a lagging longer expiry mimics nodeClientRenewed and would
  1084. // undo a master shorten once the freeze lifts (#6228).
  1085. if clientFrozen && seen && (canon.Up < base.Up || canon.Down < base.Down) {
  1086. continue
  1087. }
  1088. if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon.Up, canon.Down); err != nil {
  1089. return false, err
  1090. }
  1091. nodeBaselines[cs.Email] = nodeTrafficCounter{Up: canon.Up, Down: canon.Down}
  1092. }
  1093. for k, existing := range centralCS {
  1094. if dirty {
  1095. continue
  1096. }
  1097. if k.inboundID != c.Id {
  1098. continue
  1099. }
  1100. if _, degraded := degradedInbounds[c.Id]; degraded {
  1101. continue
  1102. }
  1103. if _, kept := snapEmails[k.email]; kept {
  1104. continue
  1105. }
  1106. // Gone from this inbound's stats but still reported by the node under
  1107. // a sibling inbound: both the shared accumulator row and the (node,
  1108. // email) baseline must survive, or the sibling's next delta would
  1109. // compute against nothing and freeze the counter (#5202).
  1110. if _, still := snapEmailsAll[k.email]; still {
  1111. continue
  1112. }
  1113. if err := tx.Where("node_id = ? AND email = ?", nodeID, existing.Email).
  1114. Delete(&model.NodeClientTraffic{}).Error; err != nil {
  1115. return false, err
  1116. }
  1117. // Same shared-accumulator rule as the inbound-removal sweep above:
  1118. // keep the row while another inbound still references the email.
  1119. stillUsed, uErr := s.emailUsedByOtherInbounds(existing.Email, c.Id)
  1120. if uErr != nil {
  1121. return false, uErr
  1122. }
  1123. // Usage, quota and expiry live on this row, so a client the orphan
  1124. // sweep will mark keeps it until the reaper confirms the removal.
  1125. if !stillUsed && !clientRecordExists(tx, existing.Email) {
  1126. if err := tx.Where("inbound_id = ? AND email = ?", c.Id, existing.Email).
  1127. Delete(&xray.ClientTraffic{}).Error; err != nil {
  1128. return false, err
  1129. }
  1130. }
  1131. structuralChange = true
  1132. }
  1133. }
  1134. type oldSet struct {
  1135. inboundID int
  1136. emails map[string]struct{}
  1137. }
  1138. var perInboundOld []oldSet
  1139. syncFailedInbounds := map[int]struct{}{}
  1140. for _, p := range pendingAdopts {
  1141. lifted, liftChanged := liftClientLifecycleInSettings(p.wireSettings, centralCSByEmail)
  1142. adoptedSettings := p.wireSettings
  1143. if liftChanged {
  1144. adoptedSettings = lifted
  1145. lifecycleLifted = true
  1146. }
  1147. if p.central.Settings != adoptedSettings {
  1148. if err := tx.Model(model.Inbound{}).
  1149. Where("id = ?", p.central.Id).
  1150. Update("settings", adoptedSettings).Error; err != nil {
  1151. return false, err
  1152. }
  1153. structuralChange = true
  1154. }
  1155. // The fingerprint stamps the un-lifted wire blob on purpose: a lift must
  1156. // leave reconcile a mismatch to re-push against.
  1157. if liftChanged || adoptedWireChanged(p.central, p.snapIb, p.wireSettings) {
  1158. adoptedInbounds = append(adoptedInbounds, adoptedWireInbound(p.central, p.snapIb, p.wireSettings))
  1159. }
  1160. }
  1161. for _, snapIb := range snap.Inbounds {
  1162. if snapIb == nil {
  1163. continue
  1164. }
  1165. c, ok := tagToCentral[snapIb.Tag]
  1166. if !ok {
  1167. continue
  1168. }
  1169. if dirty {
  1170. continue
  1171. }
  1172. var oldEmailsRows []string
  1173. if err := tx.Table("clients").
  1174. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  1175. Where("client_inbounds.inbound_id = ?", c.Id).
  1176. Pluck("email", &oldEmailsRows).Error; err == nil {
  1177. oldEmails := make(map[string]struct{}, len(oldEmailsRows))
  1178. for _, e := range oldEmailsRows {
  1179. if e != "" {
  1180. oldEmails[e] = struct{}{}
  1181. }
  1182. }
  1183. perInboundOld = append(perInboundOld, oldSet{inboundID: c.Id, emails: oldEmails})
  1184. }
  1185. clients, gcErr := s.GetClients(snapIb)
  1186. if gcErr != nil {
  1187. logger.Warningf("setRemoteTraffic: parse clients for tag %q failed: %v", snapIb.Tag, gcErr)
  1188. continue
  1189. }
  1190. csByEmail := make(map[string]xray.ClientTraffic, len(snapIb.ClientStats))
  1191. for _, cs := range snapIb.ClientStats {
  1192. csByEmail[cs.Email] = cs
  1193. }
  1194. filtered := clients[:0]
  1195. for i := range clients {
  1196. if isClientEmailTombstoned(clients[i].Email) {
  1197. continue
  1198. }
  1199. existing := centralCSByEmail[clients[i].Email]
  1200. var csPtr *xray.ClientTraffic
  1201. if cs, hit := csByEmail[clients[i].Email]; hit {
  1202. csCopy := cs
  1203. csPtr = &csCopy
  1204. }
  1205. applyMasterClientLifecycle(&clients[i], existing, csPtr)
  1206. filtered = append(filtered, clients[i])
  1207. }
  1208. // A degraded node (reset/restart/removal) reports zero clients for an inbound the
  1209. // hub populates; adopting it empties links and ReapSyncOrphans deletes shared clients (#6734).
  1210. if _, degraded := degradedInbounds[c.Id]; degraded {
  1211. 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))
  1212. syncFailedInbounds[c.Id] = struct{}{}
  1213. continue
  1214. }
  1215. localEmails := make([]string, 0, len(filtered))
  1216. for i := range filtered {
  1217. if filtered[i].Email != "" {
  1218. localEmails = append(localEmails, filtered[i].Email)
  1219. }
  1220. }
  1221. if len(localEmails) > 0 {
  1222. var localMeta []struct {
  1223. Email string
  1224. Comment string `gorm:"column:comment"`
  1225. }
  1226. if err := tx.Table("clients").
  1227. Select("email, comment").
  1228. Where("email IN ?", localEmails).
  1229. Find(&localMeta).Error; err == nil {
  1230. commentByEmail := make(map[string]string, len(localMeta))
  1231. for _, m := range localMeta {
  1232. commentByEmail[m.Email] = m.Comment
  1233. }
  1234. for i := range filtered {
  1235. if cmt, ok := commentByEmail[filtered[i].Email]; ok {
  1236. filtered[i].Comment = cmt
  1237. }
  1238. }
  1239. }
  1240. }
  1241. if len(localEmails) > 0 {
  1242. foreign, err := clientEmailsOwnedElsewhere(tx, nodeID, localEmails)
  1243. if err != nil {
  1244. return false, err
  1245. }
  1246. if len(foreign) > 0 {
  1247. kept := filtered[:0]
  1248. for i := range filtered {
  1249. if _, claimed := foreign[filtered[i].Email]; !claimed {
  1250. kept = append(kept, filtered[i])
  1251. continue
  1252. }
  1253. key := fmt.Sprintf("%d:%s", nodeID, filtered[i].Email)
  1254. if _, seen := reportedForeignClientClaim.LoadOrStore(key, struct{}{}); !seen {
  1255. logger.Warningf(
  1256. "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)",
  1257. nodeID, filtered[i].Email,
  1258. )
  1259. }
  1260. }
  1261. filtered = kept
  1262. }
  1263. }
  1264. if err := s.clientService.SyncInbound(tx, c.Id, filtered); err != nil {
  1265. logger.Warningf("setRemoteTraffic: sync clients for tag %q failed: %v", snapIb.Tag, err)
  1266. syncFailedInbounds[c.Id] = struct{}{}
  1267. }
  1268. }
  1269. for _, old := range perInboundOld {
  1270. // The sweep's premise is that links were just rebuilt from the snapshot,
  1271. // which is exactly what a failed SyncInbound violates.
  1272. if _, failed := syncFailedInbounds[old.inboundID]; failed {
  1273. continue
  1274. }
  1275. var stillAttached []string
  1276. if err := tx.Table("clients").
  1277. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  1278. Where("client_inbounds.inbound_id = ?", old.inboundID).
  1279. Pluck("email", &stillAttached).Error; err != nil {
  1280. continue
  1281. }
  1282. stillSet := make(map[string]struct{}, len(stillAttached))
  1283. for _, e := range stillAttached {
  1284. stillSet[e] = struct{}{}
  1285. }
  1286. for email := range old.emails {
  1287. if _, kept := stillSet[email]; kept {
  1288. continue
  1289. }
  1290. var attachmentCount int64
  1291. if err := tx.Table("client_inbounds").
  1292. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  1293. Where("clients.email = ?", email).
  1294. Count(&attachmentCount).Error; err != nil {
  1295. continue
  1296. }
  1297. if attachmentCount > 0 {
  1298. continue
  1299. }
  1300. // "Ended the merge unattached" is true for a real remote deletion and
  1301. // equally true for a bad merge, so record a strike instead of deleting.
  1302. if err := markSyncOrphan(tx, email, now); err != nil {
  1303. logger.Warningf("setRemoteTraffic: mark orphan %q failed: %v", email, err)
  1304. continue
  1305. }
  1306. structuralChange = true
  1307. }
  1308. }
  1309. if err := clearSyncOrphanMarks(tx); err != nil {
  1310. logger.Warning("setRemoteTraffic: clear orphan marks failed:", err)
  1311. }
  1312. if err := liftActivatedClientRecordExpiries(tx); err != nil {
  1313. logger.Warning("setRemoteTraffic: lift activated expiries failed:", err)
  1314. }
  1315. if err := tx.Commit().Error; err != nil {
  1316. return false, err
  1317. }
  1318. committed = true
  1319. if len(degradedInbounds) > 0 {
  1320. if mgr := runtime.GetManager(); mgr != nil {
  1321. if rt, rtErr := mgr.RuntimeFor(&nodeID); rtErr == nil {
  1322. if rem, ok := rt.(*runtime.Remote); ok {
  1323. for _, tag := range degradedInbounds {
  1324. rem.ForgetPushedInbound(tag)
  1325. }
  1326. }
  1327. }
  1328. }
  1329. if err := (&NodeService{}).MarkNodeDirty(nodeID); err != nil {
  1330. logger.Warningf("setRemoteTraffic: mark node %d dirty after an empty snapshot failed: %v", nodeID, err)
  1331. }
  1332. }
  1333. if lifecycleLifted && !dirty {
  1334. var already model.Node
  1335. if err := database.GetDB().Select("config_dirty").Where("id = ?", nodeID).First(&already).Error; err == nil && already.ConfigDirty {
  1336. logger.Debugf("setRemoteTraffic: node %d lifecycle lift; already dirty", nodeID)
  1337. } else {
  1338. logger.Infof("setRemoteTraffic: node %d lifecycle lift; marking dirty for re-push", nodeID)
  1339. if err := (&NodeService{}).MarkNodeDirty(nodeID); err != nil {
  1340. logger.Warningf("setRemoteTraffic: mark node %d dirty after lifecycle lift failed: %v", nodeID, err)
  1341. }
  1342. }
  1343. }
  1344. if len(adoptedInbounds) > 0 {
  1345. if mgr := runtime.GetManager(); mgr != nil {
  1346. if rt, rtErr := mgr.RuntimeFor(&nodeID); rtErr == nil {
  1347. if rem, ok := rt.(*runtime.Remote); ok {
  1348. for _, ib := range adoptedInbounds {
  1349. rem.RecordAdoptedInbound(ib)
  1350. }
  1351. }
  1352. }
  1353. }
  1354. }
  1355. if process := currentXrayProcess(); process != nil {
  1356. tree := snap.OnlineTree
  1357. switch {
  1358. case len(tree) == 0 && len(snap.OnlineEmails) > 0:
  1359. // Old-build node (no GUID tree): key its flat online list under its
  1360. // own effective identity so attribution still works for that branch.
  1361. tree = map[string][]string{selfKey: snap.OnlineEmails}
  1362. case guidShared && len(tree) > 0:
  1363. // Newer cloned node: its own clients arrive keyed under the shared
  1364. // panelGuid. Remap just that entry to the node-unique key so the
  1365. // clones don't merge; descendant subtrees keep their distinct GUIDs.
  1366. if _, ok := tree[nodeRow.Guid]; ok {
  1367. tree = remapGuidTreeKey(tree, nodeRow.Guid, selfKey)
  1368. }
  1369. }
  1370. process.SetNodeOnlineTree(nodeID, tree)
  1371. activeTree := normalizeActiveInboundTreeTags(snap.ActiveInboundTree, tagToCentral)
  1372. if guidShared && len(activeTree) > 0 {
  1373. if _, ok := activeTree[nodeRow.Guid]; ok {
  1374. activeTree = remapGuidTreeKey(activeTree, nodeRow.Guid, selfKey)
  1375. }
  1376. }
  1377. if len(activeTree) > 0 {
  1378. activeTree = filterGuidTreeKeys(activeTree, activeInboundGuidKeys(snap.Inbounds, tagToCentral, originGuidFor))
  1379. }
  1380. process.SetNodeActiveInboundTree(nodeID, activeTree)
  1381. }
  1382. return structuralChange, nil
  1383. }
  1384. func (s *InboundService) restartRemoteNodesOnDisable(nodeIDs []int) {
  1385. restartOnDisable, err := (&SettingService{}).GetRestartXrayOnClientDisable()
  1386. if err != nil {
  1387. logger.Warning("disableInvalidClients: get RestartXrayOnClientDisable failed:", err)
  1388. return
  1389. }
  1390. if !restartOnDisable {
  1391. return
  1392. }
  1393. // Best-effort and never replayed: a hanging node must not hold the traffic poll.
  1394. common.GoRecover("restart-nodes-on-client-disable", func() {
  1395. for _, nodeID := range nodeIDs {
  1396. nodeIDCopy := nodeID
  1397. rt, rtErr := runtime.GetManager().RuntimeFor(&nodeIDCopy)
  1398. if rtErr != nil {
  1399. logger.Warning("disableInvalidClients: get runtime for node", nodeID, "failed:", rtErr)
  1400. continue
  1401. }
  1402. if rtErr = rt.RestartXray(context.Background()); rtErr != nil {
  1403. logger.Warning("disableInvalidClients: restart xray on node", nodeID, "failed:", rtErr)
  1404. }
  1405. }
  1406. })
  1407. }
  1408. func (s *InboundService) GetOnlineClients() []string {
  1409. process := currentXrayProcess()
  1410. if process == nil {
  1411. return []string{}
  1412. }
  1413. return process.GetOnlineClients()
  1414. }
  1415. // GetOnlineClientsByGuid returns online emails keyed by the panelGuid of the
  1416. // node that physically hosts each set: this panel's own clients under its own
  1417. // GUID, plus every node in the tree under its GUID (#4983). Replaces the old
  1418. // node-id keying so a client three hops down is attributed to its real node,
  1419. // not the intermediate one it was synced through.
  1420. func (s *InboundService) GetOnlineClientsByGuid() map[string][]string {
  1421. process := currentXrayProcess()
  1422. if process == nil {
  1423. return map[string][]string{}
  1424. }
  1425. out := process.GetMergedNodeTrees()
  1426. if local := process.GetLocalOnlineClients(); len(local) > 0 {
  1427. if guid := s.panelGuid(); guid != "" {
  1428. out[guid] = mergeEmails(out[guid], local)
  1429. }
  1430. }
  1431. return out
  1432. }
  1433. // GetActiveInboundsByGuid returns the inbound tags that carried traffic within
  1434. // the grace window, keyed by the panelGuid of the node that physically hosts
  1435. // each inbound. A GUID missing from the map means "don't gate" for that node's
  1436. // inbounds (old-build node or no active-inbound signal).
  1437. func (s *InboundService) GetActiveInboundsByGuid() map[string][]string {
  1438. process := currentXrayProcess()
  1439. if process == nil {
  1440. return map[string][]string{}
  1441. }
  1442. out := process.GetMergedActiveInboundTrees()
  1443. active := process.GetLocalActiveInbounds()
  1444. if len(active) == 0 {
  1445. return out
  1446. }
  1447. guid := s.panelGuid()
  1448. if guid == "" {
  1449. return out
  1450. }
  1451. out[guid] = mergeEmails(out[guid], active)
  1452. return out
  1453. }
  1454. func (s *InboundService) SetNodeOnlineTree(nodeID int, tree map[string][]string) {
  1455. if process := currentXrayProcess(); process != nil {
  1456. process.SetNodeOnlineTree(nodeID, tree)
  1457. }
  1458. }
  1459. func (s *InboundService) ClearNodeOnlineClients(nodeID int) {
  1460. if process := currentXrayProcess(); process != nil {
  1461. process.ClearNodeOnlineClients(nodeID)
  1462. }
  1463. }
  1464. // RetainSyncedNodeOnlineClients keeps online clients only for nodes the traffic
  1465. // sync still fetches; a node missing from nodes was deleted.
  1466. func (s *InboundService) RetainSyncedNodeOnlineClients(nodes []*model.Node) {
  1467. process := currentXrayProcess()
  1468. if process == nil {
  1469. return
  1470. }
  1471. synced := make(map[int]bool, len(nodes))
  1472. for _, n := range nodes {
  1473. synced[n.Id] = n.Enable && n.Status == "online"
  1474. }
  1475. process.RetainNodeOnlineClients(func(nodeID int) bool { return synced[nodeID] })
  1476. }
  1477. // panelGuid returns this panel's stable self-identifier, used to key the local
  1478. // panel's own clients in the per-node online maps (#4983).
  1479. func (s *InboundService) panelGuid() string {
  1480. guid, _ := (&SettingService{}).GetPanelGuid()
  1481. return guid
  1482. }
  1483. // synthNodeGuid is the stable per-node fallback identity for a directly-attached
  1484. // node whose panel hasn't reported a panelGuid yet (old build). Node ids are
  1485. // master-local, so this only composes for direct nodes — exactly the pre-#4983
  1486. // flat-topology case where an old-build node appears.
  1487. func synthNodeGuid(nodeID int) string {
  1488. return fmt.Sprintf("node:%d", nodeID)
  1489. }
  1490. // mergeEmails returns the deduped union of two email slices.
  1491. func mergeEmails(a, b []string) []string {
  1492. if len(a) == 0 {
  1493. return b
  1494. }
  1495. seen := make(map[string]struct{}, len(a)+len(b))
  1496. out := make([]string, 0, len(a)+len(b))
  1497. for _, e := range a {
  1498. if _, ok := seen[e]; !ok {
  1499. seen[e] = struct{}{}
  1500. out = append(out, e)
  1501. }
  1502. }
  1503. for _, e := range b {
  1504. if _, ok := seen[e]; !ok {
  1505. seen[e] = struct{}{}
  1506. out = append(out, e)
  1507. }
  1508. }
  1509. return out
  1510. }
  1511. func remapGuidTreeKey(tree map[string][]string, from, to string) map[string][]string {
  1512. if from == "" || to == "" || from == to {
  1513. return tree
  1514. }
  1515. remapped := make(map[string][]string, len(tree))
  1516. for guid, values := range tree {
  1517. if guid == from {
  1518. guid = to
  1519. }
  1520. remapped[guid] = mergeEmails(remapped[guid], values)
  1521. }
  1522. return remapped
  1523. }
  1524. func normalizeActiveInboundTreeTags(tree map[string][]string, tagToCentral map[string]*model.Inbound) map[string][]string {
  1525. if len(tree) == 0 {
  1526. return nil
  1527. }
  1528. out := make(map[string][]string, len(tree))
  1529. for guid, tags := range tree {
  1530. if guid == "" || len(tags) == 0 {
  1531. continue
  1532. }
  1533. seen := make(map[string]struct{}, len(tags))
  1534. for _, tag := range tags {
  1535. if tag == "" {
  1536. continue
  1537. }
  1538. if central, ok := tagToCentral[tag]; ok && central != nil && central.Tag != "" {
  1539. tag = central.Tag
  1540. }
  1541. if _, dup := seen[tag]; dup {
  1542. continue
  1543. }
  1544. seen[tag] = struct{}{}
  1545. out[guid] = append(out[guid], tag)
  1546. }
  1547. }
  1548. if len(out) == 0 {
  1549. return nil
  1550. }
  1551. return out
  1552. }
  1553. func activeInboundGuidKeys(inbounds []*model.Inbound, tagToCentral map[string]*model.Inbound, originGuidFor func(*model.Inbound) string) map[string]struct{} {
  1554. allowed := make(map[string]struct{})
  1555. for _, ib := range inbounds {
  1556. if ib == nil {
  1557. continue
  1558. }
  1559. if _, ok := tagToCentral[ib.Tag]; !ok {
  1560. continue
  1561. }
  1562. if guid := originGuidFor(ib); guid != "" {
  1563. allowed[guid] = struct{}{}
  1564. }
  1565. }
  1566. return allowed
  1567. }
  1568. func filterGuidTreeKeys(tree map[string][]string, allowed map[string]struct{}) map[string][]string {
  1569. if len(tree) == 0 || len(allowed) == 0 {
  1570. return nil
  1571. }
  1572. out := make(map[string][]string, len(tree))
  1573. for guid, values := range tree {
  1574. if _, ok := allowed[guid]; !ok {
  1575. continue
  1576. }
  1577. if len(values) > 0 {
  1578. out[guid] = values
  1579. }
  1580. }
  1581. if len(out) == 0 {
  1582. return nil
  1583. }
  1584. return out
  1585. }
  1586. func (s *InboundService) GetClientsLastOnline() (map[string]int64, error) {
  1587. db := database.GetDB()
  1588. var rows []xray.ClientTraffic
  1589. err := db.Model(&xray.ClientTraffic{}).Select("email, last_online").Find(&rows).Error
  1590. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1591. return nil, err
  1592. }
  1593. result := make(map[string]int64, len(rows))
  1594. for _, r := range rows {
  1595. result[r.Email] = r.LastOnline
  1596. }
  1597. return result, nil
  1598. }
  1599. // RefreshLocalOnlineClients folds the emails and inbound tags active on this
  1600. // panel's own xray this poll into the local online/active sets, applying the
  1601. // grace window and pruning stale entries. Pass nil to only prune. See
  1602. // xray.Process for why the local sets are kept separate from the shared
  1603. // last_online column.
  1604. func (s *InboundService) RefreshLocalOnlineClients(activeEmails, activeInboundTags []string) {
  1605. if process := currentXrayProcess(); process != nil {
  1606. process.RefreshLocalOnline(activeEmails, activeInboundTags, time.Now().UnixMilli(), onlineGracePeriodMs)
  1607. }
  1608. }
  1609. func (s *InboundService) FilterAndSortClientEmails(emails []string) ([]string, []string, error) {
  1610. db := database.GetDB()
  1611. // Step 1: Get ClientTraffic records for emails in the input list.
  1612. // Chunked to stay under SQLite's bind-variable limit on huge inputs.
  1613. uniqEmails := uniqueNonEmptyStrings(emails)
  1614. clients := make([]xray.ClientTraffic, 0, len(uniqEmails))
  1615. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  1616. var page []xray.ClientTraffic
  1617. if err := db.Where("email IN ?", batch).Find(&page).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1618. return nil, nil, err
  1619. }
  1620. clients = append(clients, page...)
  1621. }
  1622. // Step 2: Sort clients by (Up + Down) descending
  1623. sort.Slice(clients, func(i, j int) bool {
  1624. return (clients[i].Up + clients[i].Down) > (clients[j].Up + clients[j].Down)
  1625. })
  1626. // Step 3: Extract sorted valid emails and track found ones
  1627. validEmails := make([]string, 0, len(clients))
  1628. found := make(map[string]bool)
  1629. for _, client := range clients {
  1630. validEmails = append(validEmails, client.Email)
  1631. found[client.Email] = true
  1632. }
  1633. // Step 4: Identify emails that were not found in the database
  1634. extraEmails := make([]string, 0)
  1635. for _, email := range emails {
  1636. if !found[email] {
  1637. extraEmails = append(extraEmails, email)
  1638. }
  1639. }
  1640. return validEmails, extraEmails, nil
  1641. }