1
0

inbound_node.go 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240
  1. package service
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "sort"
  7. "strings"
  8. "sync"
  9. "time"
  10. "github.com/mhsanaei/3x-ui/v3/internal/database"
  11. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  12. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  13. "github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
  14. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  15. "gorm.io/gorm"
  16. "gorm.io/gorm/clause"
  17. )
  18. var reportedRemoteTagConflict sync.Map
  19. // nodeBulkPushThreshold caps how many per-client RPCs a single operation will
  20. // stream to a remote node. Above it, the panel marks the node dirty instead and
  21. // lets one ReconcileNode push converge the whole inbound — far cheaper than M
  22. // sequential round-trips. Small ops stay on the live per-client path.
  23. const nodeBulkPushThreshold = 32
  24. func (s *InboundService) runtimeFor(ib *model.Inbound) (runtime.Runtime, error) {
  25. mgr := runtime.GetManager()
  26. if mgr == nil {
  27. return nil, fmt.Errorf("runtime manager not initialised")
  28. }
  29. return mgr.RuntimeFor(ib.NodeID)
  30. }
  31. func (s *InboundService) nodePushPlan(ib *model.Inbound) (runtime.Runtime, bool, bool, error) {
  32. if ib.NodeID == nil {
  33. rt, err := s.runtimeFor(ib)
  34. if err != nil {
  35. return nil, false, false, nil
  36. }
  37. return rt, true, false, nil
  38. }
  39. nodeSvc := NodeService{}
  40. enabled, status, _, _, err := nodeSvc.NodeSyncState(*ib.NodeID)
  41. if err != nil {
  42. return nil, false, false, err
  43. }
  44. if !enabled || status == "offline" {
  45. return nil, false, true, nil
  46. }
  47. rt, err := s.runtimeFor(ib)
  48. if err != nil {
  49. return nil, false, true, nil
  50. }
  51. return rt, true, false, nil
  52. }
  53. func (s *InboundService) NodeIsPending(nodeID *int) bool {
  54. if nodeID == nil {
  55. return false
  56. }
  57. return (&NodeService{}).IsNodePending(*nodeID)
  58. }
  59. func (s *InboundService) AnyNodePending(inboundIds []int) bool {
  60. if len(inboundIds) == 0 {
  61. return false
  62. }
  63. nodeSvc := NodeService{}
  64. for _, id := range inboundIds {
  65. ib, err := s.GetInbound(id)
  66. if err != nil || ib.NodeID == nil {
  67. continue
  68. }
  69. if nodeSvc.IsNodePending(*ib.NodeID) {
  70. return true
  71. }
  72. }
  73. return false
  74. }
  75. // ReconcileNode pushes every inbound and sweeps undesired remote tags even when
  76. // individual operations fail, returning the failures joined: one inbound the
  77. // node rejects (e.g. a legacy protocol failing validation, #5685) must not
  78. // stall the rest of the node's config — or, via syncOne, its traffic sync.
  79. func (s *InboundService) ReconcileNode(ctx context.Context, rt *runtime.Remote, n *model.Node) error {
  80. if rt == nil || n == nil || n.Id <= 0 {
  81. return nil
  82. }
  83. nodeID := n.Id
  84. db := database.GetDB()
  85. var inbounds []*model.Inbound
  86. if err := db.Model(model.Inbound{}).Where("node_id = ?", nodeID).Find(&inbounds).Error; err != nil {
  87. return err
  88. }
  89. remoteTags, err := rt.ListRemoteTags(ctx)
  90. if err != nil {
  91. return err
  92. }
  93. remoteTagSet := make(map[string]struct{}, len(remoteTags))
  94. for _, tag := range remoteTags {
  95. remoteTagSet[tag] = struct{}{}
  96. }
  97. prefix := nodeTagPrefix(&nodeID)
  98. desiredTags := make(map[string]struct{}, len(inbounds)*2)
  99. var errs []error
  100. for _, ib := range inbounds {
  101. desiredTags[ib.Tag] = struct{}{}
  102. // existsOnNode: does the node already report this inbound under any of the
  103. // tag forms it may be stored as? If so, an unchanged push can be skipped.
  104. _, existsOnNode := remoteTagSet[ib.Tag]
  105. if prefix != "" {
  106. if stripped, found := strings.CutPrefix(ib.Tag, prefix); found {
  107. desiredTags[stripped] = struct{}{}
  108. if _, ok := remoteTagSet[stripped]; ok {
  109. existsOnNode = true
  110. }
  111. } else {
  112. desiredTags[prefix+ib.Tag] = struct{}{}
  113. if _, ok := remoteTagSet[prefix+ib.Tag]; ok {
  114. existsOnNode = true
  115. }
  116. }
  117. }
  118. runtimeIb := ib
  119. if built, bErr := s.buildInboundForNodePush(db, ib); bErr == nil {
  120. runtimeIb = built
  121. }
  122. if _, err := rt.ReconcileInbound(ctx, runtimeIb, existsOnNode); err != nil {
  123. errs = append(errs, fmt.Errorf("reconcile inbound %q: %w", ib.Tag, err))
  124. }
  125. }
  126. // Before the first clean sync adopts the node's inbounds, "absent locally"
  127. // means "not imported yet" — sweeping now would wipe the node at onboarding.
  128. if n.InboundsAdoptedAt == 0 {
  129. return errors.Join(errs...)
  130. }
  131. // In "selected" sync mode the panel only manages the selected tags: the
  132. // rest were never imported, so their absence from the local DB must not
  133. // delete them from the node. Only a selected tag missing locally (the
  134. // panel deleted it while the node was unreachable) may be swept.
  135. var selected map[string]struct{}
  136. if n.InboundSyncMode == "selected" {
  137. selected = make(map[string]struct{}, len(n.InboundTags))
  138. for _, tag := range n.InboundTags {
  139. selected[tag] = struct{}{}
  140. }
  141. }
  142. for _, tag := range remoteTags {
  143. if _, want := desiredTags[tag]; want {
  144. continue
  145. }
  146. if selected != nil {
  147. if _, managed := selected[tag]; !managed {
  148. continue
  149. }
  150. }
  151. if err := rt.DelInbound(ctx, &model.Inbound{Tag: tag}); err != nil {
  152. errs = append(errs, fmt.Errorf("reconcile delete %q: %w", tag, err))
  153. }
  154. }
  155. return errors.Join(errs...)
  156. }
  157. const resetGracePeriodMs int64 = 30000
  158. // onlineGracePeriodMs must comfortably exceed the 5s traffic-poll interval —
  159. // Xray's stats counters often report a zero delta for an active session across
  160. // a single poll, so a 5s grace would still drop the client on the next tick.
  161. // ~4 polls of slack keeps idle-but-connected clients visible without lingering
  162. // long after a real disconnect.
  163. const onlineGracePeriodMs int64 = 20000
  164. type nodeTrafficCounter struct {
  165. Up int64
  166. Down int64
  167. }
  168. func (s *InboundService) upsertNodeBaseline(tx *gorm.DB, nodeID int, email string, up, down int64) error {
  169. return tx.Clauses(clause.OnConflict{
  170. Columns: []clause.Column{{Name: "node_id"}, {Name: "email"}},
  171. DoUpdates: clause.AssignmentColumns([]string{"up", "down"}),
  172. }).Create(&model.NodeClientTraffic{NodeId: nodeID, Email: email, Up: up, Down: down}).Error
  173. }
  174. // mergeActivationExpiry reconciles a node-reported client expiry with the value
  175. // already stored on the master. "Start after first connect" persists a negative
  176. // duration that each node converts to an absolute deadline (now+duration) the
  177. // first time the client connects there. The per-email client_traffics row is
  178. // shared across every node, so a node that has not yet seen a first connection
  179. // keeps reporting the negative duration — which must never reset a deadline
  180. // another node already activated.
  181. //
  182. // A node may legitimately move an already-activated deadline forward (traffic
  183. // reset / auto-renew extends it), so any positive node value is still adopted —
  184. // only an un-activated (<= 0) value is rejected once an absolute deadline
  185. // exists. Kept in lockstep with the SQL CASE in setRemoteTrafficLocked.
  186. func mergeActivationExpiry(existing, node int64) int64 {
  187. if existing > 0 && node <= 0 {
  188. return existing
  189. }
  190. return node
  191. }
  192. // nodeClientRenewed reports a node-side auto-renew: an absolute deadline moved
  193. // forward while the node's cumulative counter fell below the stored baseline.
  194. func nodeClientRenewed(existing *xray.ClientTraffic, cs xray.ClientTraffic, canon, base nodeTrafficCounter) bool {
  195. if cs.Reset <= 0 || cs.ExpiryTime <= 0 || existing.ExpiryTime <= 0 {
  196. return false
  197. }
  198. if cs.ExpiryTime <= existing.ExpiryTime {
  199. return false
  200. }
  201. return canon.Up < base.Up || canon.Down < base.Down
  202. }
  203. // liftActivatedClientRecordExpiries copies a node-activated deadline from
  204. // client_traffics onto client records still holding the negative duration (#5714).
  205. func liftActivatedClientRecordExpiries(tx *gorm.DB) error {
  206. return tx.Exec(
  207. `UPDATE clients
  208. SET expiry_time = (SELECT ct.expiry_time FROM client_traffics ct WHERE ct.email = clients.email AND ct.expiry_time > 0 LIMIT 1)
  209. WHERE clients.expiry_time < 0
  210. AND EXISTS (SELECT 1 FROM client_traffics ct WHERE ct.email = clients.email AND ct.expiry_time > 0)`,
  211. ).Error
  212. }
  213. // SnapshotHasUnadoptedInbounds reports whether the snapshot carries a tag with
  214. // no central row yet, i.e. the next merge would adopt a new inbound.
  215. func (s *InboundService) SnapshotHasUnadoptedInbounds(nodeID int, snap *runtime.TrafficSnapshot) (bool, error) {
  216. if snap == nil || len(snap.Inbounds) == 0 {
  217. return false, nil
  218. }
  219. var tags []string
  220. if err := database.GetDB().Model(model.Inbound{}).
  221. Where("node_id = ?", nodeID).
  222. Pluck("tag", &tags).Error; err != nil {
  223. return false, err
  224. }
  225. prefix := nodeTagPrefix(&nodeID)
  226. known := make(map[string]struct{}, len(tags)*2)
  227. for _, tag := range tags {
  228. known[tag] = struct{}{}
  229. if prefix != "" {
  230. if stripped, found := strings.CutPrefix(tag, prefix); found {
  231. known[stripped] = struct{}{}
  232. } else {
  233. known[prefix+tag] = struct{}{}
  234. }
  235. }
  236. }
  237. for _, ib := range snap.Inbounds {
  238. if ib == nil {
  239. continue
  240. }
  241. if _, ok := known[ib.Tag]; !ok {
  242. return true, nil
  243. }
  244. }
  245. return false, nil
  246. }
  247. func (s *InboundService) SetRemoteTraffic(nodeID int, snap *runtime.TrafficSnapshot, dirty bool) (bool, error) {
  248. var structuralChange bool
  249. err := submitTrafficWrite(func() error {
  250. var inner error
  251. structuralChange, inner = s.setRemoteTrafficLocked(nodeID, snap, dirty)
  252. return inner
  253. })
  254. return structuralChange, err
  255. }
  256. // GetNodeInboundTrafficTotals returns the current cumulative up/down for every
  257. // node-hosted inbound, keyed by tag. The node sync diffs successive snapshots of
  258. // this to derive per-inbound speed for the dashboard — node inbounds have no
  259. // local Xray poll to produce live deltas the way local inbounds do.
  260. func (s *InboundService) GetNodeInboundTrafficTotals() (map[string][2]int64, error) {
  261. var rows []struct {
  262. Tag string
  263. Up int64
  264. Down int64
  265. }
  266. if err := database.GetDB().Table("inbounds").
  267. Select("tag, up, down").
  268. Where("node_id IS NOT NULL").
  269. Scan(&rows).Error; err != nil {
  270. return nil, err
  271. }
  272. out := make(map[string][2]int64, len(rows))
  273. for _, r := range rows {
  274. out[r.Tag] = [2]int64{r.Up, r.Down}
  275. }
  276. return out, nil
  277. }
  278. func adoptedWireChanged(c, snapIb *model.Inbound, adoptedSettings string) bool {
  279. return c.Settings != adoptedSettings ||
  280. c.Enable != snapIb.Enable ||
  281. c.Remark != snapIb.Remark ||
  282. c.SubSortIndex != normalizeSubSortIndex(snapIb.SubSortIndex) ||
  283. c.Listen != snapIb.Listen ||
  284. c.Port != snapIb.Port ||
  285. c.Protocol != snapIb.Protocol ||
  286. c.Total != snapIb.Total ||
  287. c.ExpiryTime != snapIb.ExpiryTime ||
  288. c.StreamSettings != snapIb.StreamSettings ||
  289. c.Sniffing != snapIb.Sniffing ||
  290. c.TrafficReset != snapIb.TrafficReset ||
  291. c.TrafficResetDay != normalizeTrafficResetDay(snapIb.TrafficResetDay)
  292. }
  293. // adoptedWireInbound is the central inbound as it reads after adopting the
  294. // node-reported wire fields — the payload the reconcile fingerprint must track.
  295. func adoptedWireInbound(c, snapIb *model.Inbound, adoptedSettings string) *model.Inbound {
  296. a := *c
  297. a.Enable = snapIb.Enable
  298. a.Remark = snapIb.Remark
  299. a.SubSortIndex = normalizeSubSortIndex(snapIb.SubSortIndex)
  300. a.Listen = snapIb.Listen
  301. a.Port = snapIb.Port
  302. a.Protocol = snapIb.Protocol
  303. a.Total = snapIb.Total
  304. a.ExpiryTime = snapIb.ExpiryTime
  305. a.Settings = adoptedSettings
  306. a.StreamSettings = snapIb.StreamSettings
  307. a.Sniffing = snapIb.Sniffing
  308. a.TrafficReset = snapIb.TrafficReset
  309. a.TrafficResetDay = normalizeTrafficResetDay(snapIb.TrafficResetDay)
  310. return &a
  311. }
  312. func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.TrafficSnapshot, dirty bool) (bool, error) {
  313. if snap == nil || nodeID <= 0 {
  314. return false, nil
  315. }
  316. db := database.GetDB()
  317. now := time.Now().UnixMilli()
  318. // originGuidFor attributes a synced inbound to the panel that physically
  319. // hosts it. A node's OWN inbounds report either an empty origin or — on
  320. // builds that set it locally — the node's own panelGuid; both resolve to
  321. // selfKey, which is the node's panelGuid unless that GUID is ambiguous
  322. // (shared with another node or the master, i.e. a cloned server), in which
  323. // case it falls back to the node-unique id so #4983 attribution doesn't
  324. // collapse two physical nodes into one bucket. Only a DIFFERENT, non-empty
  325. // origin (an inbound the node forwards from its own sub-node) is kept as-is,
  326. // so a chained Node1->Node2->Node3 still attributes Node3's inbounds to Node3.
  327. var nodeRow model.Node
  328. db.Select("guid", "config_dirty", "inbound_sync_mode", "inbound_tags").Where("id = ?", nodeID).First(&nodeRow)
  329. // Re-read inside the serialized writer: a client added while this snapshot
  330. // was in flight marks the node dirty after the caller sampled the flag.
  331. dirty = dirty || nodeRow.ConfigDirty
  332. nodeRow.Id = nodeID
  333. unmanagedTag := unmanagedTagPredicate(&nodeRow)
  334. selfKey := effectiveNodeKey(&model.Node{Id: nodeID, Guid: nodeRow.Guid})
  335. guidShared := nodeRow.Guid != "" && selfKey != nodeRow.Guid
  336. originGuidFor := func(snapIb *model.Inbound) string {
  337. if snapIb.OriginNodeGuid != "" && snapIb.OriginNodeGuid != nodeRow.Guid {
  338. return snapIb.OriginNodeGuid
  339. }
  340. return selfKey
  341. }
  342. var central []model.Inbound
  343. if err := db.Model(model.Inbound{}).
  344. Where("node_id = ?", nodeID).
  345. Find(&central).Error; err != nil {
  346. return false, err
  347. }
  348. // Index under the stored tag and its prefix-flipped form so a snap matches
  349. // whether the n<id>- prefix lives on the node side, the central side, or
  350. // neither — a mismatch must never spawn a duplicate central inbound.
  351. tagToCentral := make(map[string]*model.Inbound, len(central)*2)
  352. prefix := nodeTagPrefix(&nodeID)
  353. for i := range central {
  354. tagToCentral[central[i].Tag] = &central[i]
  355. if prefix != "" {
  356. if stripped, found := strings.CutPrefix(central[i].Tag, prefix); found {
  357. tagToCentral[stripped] = &central[i]
  358. } else {
  359. tagToCentral[prefix+central[i].Tag] = &central[i]
  360. }
  361. }
  362. }
  363. var centralClientStats []xray.ClientTraffic
  364. if len(central) > 0 {
  365. ids := make([]int, 0, len(central))
  366. for i := range central {
  367. ids = append(ids, central[i].Id)
  368. }
  369. if err := db.Model(xray.ClientTraffic{}).
  370. Where("inbound_id IN ?", ids).
  371. Find(&centralClientStats).Error; err != nil {
  372. return false, err
  373. }
  374. }
  375. type csKey struct {
  376. inboundID int
  377. email string
  378. }
  379. centralCS := make(map[csKey]*xray.ClientTraffic, len(centralClientStats))
  380. centralCSByEmail := make(map[string]*xray.ClientTraffic, len(centralClientStats))
  381. for i := range centralClientStats {
  382. centralCS[csKey{centralClientStats[i].InboundId, centralClientStats[i].Email}] = &centralClientStats[i]
  383. centralCSByEmail[centralClientStats[i].Email] = &centralClientStats[i]
  384. }
  385. nodeBaselines := make(map[string]nodeTrafficCounter)
  386. var baselineRows []model.NodeClientTraffic
  387. if err := db.Model(&model.NodeClientTraffic{}).
  388. Where("node_id = ?", nodeID).
  389. Find(&baselineRows).Error; err != nil {
  390. return false, err
  391. }
  392. for i := range baselineRows {
  393. nodeBaselines[baselineRows[i].Email] = nodeTrafficCounter{Up: baselineRows[i].Up, Down: baselineRows[i].Down}
  394. }
  395. var defaultUserId int
  396. if len(central) > 0 {
  397. defaultUserId = central[0].UserId
  398. } else {
  399. var u model.User
  400. if err := db.Model(model.User{}).Order("id asc").First(&u).Error; err == nil {
  401. defaultUserId = u.Id
  402. } else {
  403. defaultUserId = 1
  404. }
  405. }
  406. // Union of every email the snapshot still reports, across all inbounds.
  407. // The (node, email) baseline rows are keyed per node, not per inbound, so
  408. // the sweeps below must only drop one when the email left the node
  409. // entirely — an email whose stats moved to (or always lived under) a
  410. // sibling inbound still needs its baseline for the sibling's delta
  411. // computation (#5202).
  412. //
  413. // Xray counts traffic per email, not per inbound, so a multi-attached
  414. // client's shared counter is copied onto every inbound it's on. Fold each
  415. // email to its per-field max (nodeEmailTotals) so divergent copies can't make
  416. // the reset clamp re-add a lower sibling as fresh traffic (#5274).
  417. snapEmailsAll := make(map[string]struct{})
  418. nodeEmailTotals := make(map[string]nodeTrafficCounter)
  419. for _, snapIb := range snap.Inbounds {
  420. if snapIb == nil {
  421. continue
  422. }
  423. for i := range snapIb.ClientStats {
  424. email := snapIb.ClientStats[i].Email
  425. snapEmailsAll[email] = struct{}{}
  426. cur := nodeEmailTotals[email]
  427. if snapIb.ClientStats[i].Up > cur.Up {
  428. cur.Up = snapIb.ClientStats[i].Up
  429. }
  430. if snapIb.ClientStats[i].Down > cur.Down {
  431. cur.Down = snapIb.ClientStats[i].Down
  432. }
  433. nodeEmailTotals[email] = cur
  434. }
  435. }
  436. // Membership set for the rowExists checks below. Only the snapshot's emails
  437. // are ever probed, so scope the lookup to those instead of plucking the whole
  438. // client_traffics table (50k+ rows) on every node poll.
  439. existingEmails := make(map[string]struct{}, len(snapEmailsAll))
  440. if len(snapEmailsAll) > 0 {
  441. snapEmailList := make([]string, 0, len(snapEmailsAll))
  442. for email := range snapEmailsAll {
  443. snapEmailList = append(snapEmailList, email)
  444. }
  445. for _, batch := range chunkStrings(snapEmailList, sqliteMaxVars) {
  446. var found []string
  447. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Pluck("email", &found).Error; err != nil {
  448. return false, err
  449. }
  450. for _, e := range found {
  451. existingEmails[e] = struct{}{}
  452. }
  453. }
  454. }
  455. tx := db.Begin()
  456. committed := false
  457. defer func() {
  458. if !committed {
  459. tx.Rollback()
  460. }
  461. }()
  462. structuralChange := false
  463. var adoptedInbounds []*model.Inbound
  464. newInboundIDs := make(map[int]struct{})
  465. snapTags := make(map[string]struct{}, len(snap.Inbounds))
  466. for _, snapIb := range snap.Inbounds {
  467. if snapIb == nil {
  468. continue
  469. }
  470. snapTags[snapIb.Tag] = struct{}{}
  471. // Record the prefix-flipped form too so the orphan sweep below keeps a
  472. // central inbound whether its tag carries the n<id>- prefix or not.
  473. if prefix != "" {
  474. if stripped, found := strings.CutPrefix(snapIb.Tag, prefix); found {
  475. snapTags[stripped] = struct{}{}
  476. } else {
  477. snapTags[prefix+snapIb.Tag] = struct{}{}
  478. }
  479. }
  480. c, ok := tagToCentral[snapIb.Tag]
  481. if !ok {
  482. if dirty {
  483. continue
  484. }
  485. // Try snap.Tag first; on collision fall back to the n<id>-
  486. // prefixed form so local+node can both own the same port.
  487. pickFreeTag := func() (string, error) {
  488. candidates := []string{snapIb.Tag}
  489. if prefix != "" && !strings.HasPrefix(snapIb.Tag, prefix) {
  490. candidates = append(candidates, prefix+snapIb.Tag)
  491. }
  492. for _, t := range candidates {
  493. var owner model.Inbound
  494. err := tx.Where("tag = ?", t).First(&owner).Error
  495. if errors.Is(err, gorm.ErrRecordNotFound) {
  496. return t, nil
  497. }
  498. if err != nil {
  499. return "", err
  500. }
  501. }
  502. return "", nil
  503. }
  504. chosenTag, err := pickFreeTag()
  505. if err != nil {
  506. logger.Warningf("setRemoteTraffic: check tag %q failed: %v", snapIb.Tag, err)
  507. continue
  508. }
  509. if chosenTag == "" {
  510. key := fmt.Sprintf("%d:%s", nodeID, snapIb.Tag)
  511. if _, seen := reportedRemoteTagConflict.LoadOrStore(key, struct{}{}); !seen {
  512. logger.Warningf(
  513. "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)",
  514. snapIb.Tag, nodeID, nodeID,
  515. )
  516. }
  517. continue
  518. }
  519. reportedRemoteTagConflict.Delete(fmt.Sprintf("%d:%s", nodeID, snapIb.Tag))
  520. newIb := model.Inbound{
  521. UserId: defaultUserId,
  522. NodeID: &nodeID,
  523. OriginNodeGuid: originGuidFor(snapIb),
  524. Tag: chosenTag,
  525. Listen: snapIb.Listen,
  526. Port: snapIb.Port,
  527. Protocol: snapIb.Protocol,
  528. Settings: snapIb.Settings,
  529. StreamSettings: snapIb.StreamSettings,
  530. Sniffing: snapIb.Sniffing,
  531. TrafficReset: snapIb.TrafficReset,
  532. TrafficResetDay: normalizeTrafficResetDay(snapIb.TrafficResetDay),
  533. LastTrafficResetTime: snapIb.LastTrafficResetTime,
  534. Enable: snapIb.Enable,
  535. Remark: snapIb.Remark,
  536. SubSortIndex: normalizeSubSortIndex(snapIb.SubSortIndex),
  537. Total: snapIb.Total,
  538. ExpiryTime: snapIb.ExpiryTime,
  539. Up: snapIb.Up,
  540. Down: snapIb.Down,
  541. ShareAddrStrategy: "node",
  542. }
  543. if err := tx.Create(&newIb).Error; err != nil {
  544. logger.Warningf("setRemoteTraffic: create central inbound for tag %q failed: %v", snapIb.Tag, err)
  545. continue
  546. }
  547. tagToCentral[snapIb.Tag] = &newIb
  548. if newIb.Tag != snapIb.Tag {
  549. tagToCentral[newIb.Tag] = &newIb
  550. }
  551. if rows := adoptedHostRows(snap.HostGroups, snapIb.Id, newIb.Id); len(rows) > 0 {
  552. if err := tx.Create(&rows).Error; err != nil {
  553. logger.Warningf("setRemoteTraffic: adopt host rows for tag %q failed: %v", newIb.Tag, err)
  554. }
  555. }
  556. newInboundIDs[newIb.Id] = struct{}{}
  557. structuralChange = true
  558. continue
  559. }
  560. inGrace := c.LastTrafficResetTime > 0 && now-c.LastTrafficResetTime < resetGracePeriodMs
  561. // Adopting the node's settings verbatim would re-add a client the master
  562. // deleted moments ago if this snapshot was fetched before the deletion
  563. // push landed — filter just-deleted emails out while their tombstone lives.
  564. adoptedSettings := snapIb.Settings
  565. if stripped, changed := stripTombstonedClients(adoptedSettings); changed {
  566. adoptedSettings = stripped
  567. }
  568. if deduped, changed := dedupeSettingsClients(adoptedSettings); changed {
  569. adoptedSettings = deduped
  570. }
  571. updates := map[string]any{}
  572. if !dirty {
  573. updates["enable"] = snapIb.Enable
  574. updates["remark"] = snapIb.Remark
  575. updates["sub_sort_index"] = normalizeSubSortIndex(snapIb.SubSortIndex)
  576. updates["listen"] = snapIb.Listen
  577. updates["port"] = snapIb.Port
  578. updates["protocol"] = snapIb.Protocol
  579. updates["total"] = snapIb.Total
  580. updates["expiry_time"] = snapIb.ExpiryTime
  581. updates["settings"] = adoptedSettings
  582. updates["stream_settings"] = snapIb.StreamSettings
  583. updates["sniffing"] = snapIb.Sniffing
  584. updates["traffic_reset"] = snapIb.TrafficReset
  585. updates["traffic_reset_day"] = normalizeTrafficResetDay(snapIb.TrafficResetDay)
  586. updates["last_traffic_reset_time"] = snapIb.LastTrafficResetTime
  587. if adoptedWireChanged(c, snapIb, adoptedSettings) {
  588. adoptedInbounds = append(adoptedInbounds, adoptedWireInbound(c, snapIb, adoptedSettings))
  589. }
  590. }
  591. if !inGrace || (snapIb.Up+snapIb.Down) <= (c.Up+c.Down) {
  592. updates["up"] = snapIb.Up
  593. updates["down"] = snapIb.Down
  594. }
  595. // Physical-home attribution is independent of config-dirty state, so
  596. // keep it current even while the node has pending offline edits. Writes
  597. // once to backfill an existing row, then stays equal (#4983).
  598. if og := originGuidFor(snapIb); c.OriginNodeGuid != og {
  599. updates["origin_node_guid"] = og
  600. }
  601. if !dirty && (c.Settings != adoptedSettings ||
  602. c.Remark != snapIb.Remark ||
  603. c.Listen != snapIb.Listen ||
  604. c.Port != snapIb.Port ||
  605. c.Total != snapIb.Total ||
  606. c.ExpiryTime != snapIb.ExpiryTime ||
  607. c.Enable != snapIb.Enable) {
  608. structuralChange = true
  609. }
  610. if len(updates) > 0 {
  611. if err := tx.Model(model.Inbound{}).
  612. Where("id = ?", c.Id).
  613. Updates(updates).Error; err != nil {
  614. return false, err
  615. }
  616. }
  617. }
  618. for _, c := range central {
  619. if dirty {
  620. continue
  621. }
  622. if len(snapTags) == 0 {
  623. // A node mid-restart or with a transient DB error can return an empty
  624. // inbound list with success=true. Treat "zero inbounds reported" as
  625. // "nothing to say", not "delete all my inbounds" — otherwise a blip
  626. // wipes the node's central inbounds and every client on them (and
  627. // resets traffic history on re-create). A real per-inbound deletion
  628. // still sweeps, because the node keeps reporting its other inbounds.
  629. continue
  630. }
  631. if _, kept := snapTags[c.Tag]; kept {
  632. continue
  633. }
  634. if unmanagedTag(c.Tag) {
  635. continue
  636. }
  637. var goneEmails []string
  638. if err := tx.Model(xray.ClientTraffic{}).
  639. Where("inbound_id = ?", c.Id).
  640. Pluck("email", &goneEmails).Error; err != nil {
  641. return false, err
  642. }
  643. if len(goneEmails) > 0 {
  644. // Baselines are per (node, email), not per inbound: keep them for
  645. // emails the snapshot still reports under a sibling inbound (#5202).
  646. baselineGone := make([]string, 0, len(goneEmails))
  647. for _, e := range goneEmails {
  648. if _, still := snapEmailsAll[e]; !still {
  649. baselineGone = append(baselineGone, e)
  650. }
  651. }
  652. // Chunk to avoid SQLite bind var limit when a node has many clients
  653. // removed (e.g. after API bulk delete or structural change on node inbound).
  654. for _, batch := range chunkStrings(baselineGone, sqliteMaxVars) {
  655. if err := tx.Where("node_id = ? AND email IN ?", nodeID, batch).
  656. Delete(&model.NodeClientTraffic{}).Error; err != nil {
  657. return false, err
  658. }
  659. }
  660. // The per-email row is the shared accumulator across every inbound
  661. // (and node) the email is attached to. Only drop it when this was the
  662. // email's last inbound — wiping it while a sibling still feeds it
  663. // loses the summed history, and the next node sync would re-seed the
  664. // row with that node's counter alone.
  665. sharedEmails, sErr := s.emailsUsedByOtherInbounds(goneEmails, c.Id)
  666. if sErr != nil {
  667. return false, sErr
  668. }
  669. delEmails := make([]string, 0, len(goneEmails))
  670. for _, e := range goneEmails {
  671. if !sharedEmails[strings.ToLower(strings.TrimSpace(e))] {
  672. delEmails = append(delEmails, e)
  673. }
  674. }
  675. for _, batch := range chunkStrings(delEmails, sqliteMaxVars) {
  676. if err := tx.Where("inbound_id = ? AND email IN ?", c.Id, batch).
  677. Delete(&xray.ClientTraffic{}).Error; err != nil {
  678. return false, err
  679. }
  680. }
  681. }
  682. if err := s.clientService.DetachInbound(tx, c.Id); err != nil {
  683. return false, err
  684. }
  685. if err := tx.Where("id = ?", c.Id).
  686. Delete(&model.Inbound{}).Error; err != nil {
  687. return false, err
  688. }
  689. delete(tagToCentral, c.Tag)
  690. structuralChange = true
  691. }
  692. for _, snapIb := range snap.Inbounds {
  693. if snapIb == nil {
  694. continue
  695. }
  696. c, ok := tagToCentral[snapIb.Tag]
  697. if !ok {
  698. continue
  699. }
  700. snapEmails := make(map[string]struct{}, len(snapIb.ClientStats))
  701. for _, cs := range snapIb.ClientStats {
  702. snapEmails[cs.Email] = struct{}{}
  703. // Node-wide total, not this inbound's possibly-stale copy (#5274).
  704. canon := nodeEmailTotals[cs.Email]
  705. base, seen := nodeBaselines[cs.Email]
  706. var deltaUp, deltaDown int64
  707. if seen {
  708. if deltaUp = canon.Up - base.Up; deltaUp < 0 {
  709. deltaUp = 0
  710. }
  711. if deltaDown = canon.Down - base.Down; deltaDown < 0 {
  712. deltaDown = 0
  713. }
  714. }
  715. if _, rowExists := existingEmails[cs.Email]; !rowExists {
  716. if dirty {
  717. continue
  718. }
  719. _, isNewInbound := newInboundIDs[c.Id]
  720. // On a known inbound a missing row plus a live tombstone means the
  721. // master just deleted this client and the snapshot predates the
  722. // deletion push — recreating the row (at zero) would resurrect the
  723. // client. A freshly adopted inbound still gets its row (seeded at
  724. // zero) so adoption semantics stay intact.
  725. if !isNewInbound && isClientEmailTombstoned(cs.Email) {
  726. continue
  727. }
  728. var seedUp, seedDown int64
  729. if isNewInbound && !isClientEmailTombstoned(cs.Email) {
  730. seedUp, seedDown = canon.Up, canon.Down
  731. }
  732. row := &xray.ClientTraffic{
  733. InboundId: c.Id,
  734. Email: cs.Email,
  735. Enable: cs.Enable,
  736. Total: cs.Total,
  737. ExpiryTime: cs.ExpiryTime,
  738. Reset: cs.Reset,
  739. Up: seedUp,
  740. Down: seedDown,
  741. LastOnline: cs.LastOnline,
  742. }
  743. if err := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "email"}}, DoNothing: true}).
  744. Create(row).Error; err != nil {
  745. return false, err
  746. }
  747. centralCS[csKey{c.Id, cs.Email}] = row
  748. centralCSByEmail[cs.Email] = row
  749. existingEmails[cs.Email] = struct{}{}
  750. structuralChange = true
  751. if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon.Up, canon.Down); err != nil {
  752. return false, err
  753. }
  754. nodeBaselines[cs.Email] = nodeTrafficCounter{Up: canon.Up, Down: canon.Down}
  755. continue
  756. }
  757. existing := centralCSByEmail[cs.Email]
  758. if existing != nil &&
  759. (existing.Enable != cs.Enable ||
  760. existing.Total != cs.Total ||
  761. existing.ExpiryTime != mergeActivationExpiry(existing.ExpiryTime, cs.ExpiryTime) ||
  762. existing.Reset != cs.Reset) {
  763. structuralChange = true
  764. }
  765. if seen && existing != nil && nodeClientRenewed(existing, cs, canon, base) {
  766. // A renewal starts a fresh quota window: adopt the node's counters
  767. // and enable state, drop stale pushes (mirrors autoRenewClients).
  768. if err := tx.Exec(
  769. fmt.Sprintf(
  770. `UPDATE client_traffics
  771. SET up = ?, down = ?, enable = ?, total = ?,
  772. expiry_time = ?, reset = ?, last_online = %s
  773. WHERE email = ?`,
  774. database.GreatestExpr("last_online", "?"),
  775. ),
  776. canon.Up, canon.Down, cs.Enable, cs.Total,
  777. cs.ExpiryTime, cs.Reset,
  778. cs.LastOnline, cs.Email,
  779. ).Error; err != nil {
  780. return false, err
  781. }
  782. if err := clearGlobalTraffic(tx, cs.Email); err != nil {
  783. return false, err
  784. }
  785. } else {
  786. enableExpr := database.ClientTrafficEnableMergeExpr()
  787. // expiry_time merge mirrors mergeActivationExpiry: a node that has not
  788. // yet seen the client's first connection keeps reporting the negative
  789. // "start after first connect" duration, which must never reset the
  790. // absolute deadline another node already activated. A positive node
  791. // value is still adopted (e.g. auto-renew moves the deadline forward).
  792. // CAST(? AS BIGINT): in the `<= 0` comparison Postgres would otherwise
  793. // infer int4 from the literal and overflow on real expiry values.
  794. if err := tx.Exec(
  795. fmt.Sprintf(
  796. `UPDATE client_traffics
  797. SET up = %s, down = %s, enable = %s, total = ?,
  798. expiry_time = CASE WHEN expiry_time > 0 AND CAST(? AS BIGINT) <= 0 THEN expiry_time ELSE CAST(? AS BIGINT) END,
  799. reset = ?, last_online = %s
  800. WHERE email = ?`,
  801. database.ClampedAddExpr("up"),
  802. database.ClampedAddExpr("down"),
  803. enableExpr,
  804. database.GreatestExpr("last_online", "?"),
  805. ),
  806. deltaUp, deltaDown, cs.Enable, cs.Total,
  807. cs.ExpiryTime, cs.ExpiryTime, cs.Reset,
  808. cs.LastOnline, cs.Email,
  809. ).Error; err != nil {
  810. return false, err
  811. }
  812. }
  813. if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon.Up, canon.Down); err != nil {
  814. return false, err
  815. }
  816. nodeBaselines[cs.Email] = nodeTrafficCounter{Up: canon.Up, Down: canon.Down}
  817. }
  818. for k, existing := range centralCS {
  819. if dirty {
  820. continue
  821. }
  822. if k.inboundID != c.Id {
  823. continue
  824. }
  825. if _, kept := snapEmails[k.email]; kept {
  826. continue
  827. }
  828. // Gone from this inbound's stats but still reported by the node under
  829. // a sibling inbound: both the shared accumulator row and the (node,
  830. // email) baseline must survive, or the sibling's next delta would
  831. // compute against nothing and freeze the counter (#5202).
  832. if _, still := snapEmailsAll[k.email]; still {
  833. continue
  834. }
  835. if err := tx.Where("node_id = ? AND email = ?", nodeID, existing.Email).
  836. Delete(&model.NodeClientTraffic{}).Error; err != nil {
  837. return false, err
  838. }
  839. // Same shared-accumulator rule as the inbound-removal sweep above:
  840. // keep the row while another inbound still references the email.
  841. stillUsed, uErr := s.emailUsedByOtherInbounds(existing.Email, c.Id)
  842. if uErr != nil {
  843. return false, uErr
  844. }
  845. // Usage, quota and expiry live on this row, so a client the orphan
  846. // sweep will mark keeps it until the reaper confirms the removal.
  847. if !stillUsed && !clientRecordExists(tx, existing.Email) {
  848. if err := tx.Where("inbound_id = ? AND email = ?", c.Id, existing.Email).
  849. Delete(&xray.ClientTraffic{}).Error; err != nil {
  850. return false, err
  851. }
  852. }
  853. structuralChange = true
  854. }
  855. }
  856. type oldSet struct {
  857. inboundID int
  858. emails map[string]struct{}
  859. }
  860. var perInboundOld []oldSet
  861. syncFailedInbounds := map[int]struct{}{}
  862. for _, snapIb := range snap.Inbounds {
  863. if snapIb == nil {
  864. continue
  865. }
  866. c, ok := tagToCentral[snapIb.Tag]
  867. if !ok {
  868. continue
  869. }
  870. if dirty {
  871. continue
  872. }
  873. var oldEmailsRows []string
  874. if err := tx.Table("clients").
  875. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  876. Where("client_inbounds.inbound_id = ?", c.Id).
  877. Pluck("email", &oldEmailsRows).Error; err == nil {
  878. oldEmails := make(map[string]struct{}, len(oldEmailsRows))
  879. for _, e := range oldEmailsRows {
  880. if e != "" {
  881. oldEmails[e] = struct{}{}
  882. }
  883. }
  884. perInboundOld = append(perInboundOld, oldSet{inboundID: c.Id, emails: oldEmails})
  885. }
  886. clients, gcErr := s.GetClients(snapIb)
  887. if gcErr != nil {
  888. logger.Warningf("setRemoteTraffic: parse clients for tag %q failed: %v", snapIb.Tag, gcErr)
  889. continue
  890. }
  891. csEnableByEmail := make(map[string]bool, len(snapIb.ClientStats))
  892. for _, cs := range snapIb.ClientStats {
  893. csEnableByEmail[cs.Email] = cs.Enable
  894. }
  895. filtered := clients[:0]
  896. for i := range clients {
  897. if isClientEmailTombstoned(clients[i].Email) {
  898. continue
  899. }
  900. if cse, hit := csEnableByEmail[clients[i].Email]; hit && !cse {
  901. clients[i].Enable = false
  902. }
  903. filtered = append(filtered, clients[i])
  904. }
  905. localEmails := make([]string, 0, len(filtered))
  906. for i := range filtered {
  907. if filtered[i].Email != "" {
  908. localEmails = append(localEmails, filtered[i].Email)
  909. }
  910. }
  911. if len(localEmails) > 0 {
  912. var localMeta []struct {
  913. Email string
  914. Comment string `gorm:"column:comment"`
  915. }
  916. if err := tx.Table("clients").
  917. Select("email, comment").
  918. Where("email IN ?", localEmails).
  919. Find(&localMeta).Error; err == nil {
  920. commentByEmail := make(map[string]string, len(localMeta))
  921. for _, m := range localMeta {
  922. commentByEmail[m.Email] = m.Comment
  923. }
  924. for i := range filtered {
  925. if cmt, ok := commentByEmail[filtered[i].Email]; ok {
  926. filtered[i].Comment = cmt
  927. }
  928. }
  929. }
  930. }
  931. if err := s.clientService.SyncInbound(tx, c.Id, filtered); err != nil {
  932. logger.Warningf("setRemoteTraffic: sync clients for tag %q failed: %v", snapIb.Tag, err)
  933. syncFailedInbounds[c.Id] = struct{}{}
  934. }
  935. }
  936. for _, old := range perInboundOld {
  937. // The sweep's premise is that links were just rebuilt from the snapshot,
  938. // which is exactly what a failed SyncInbound violates.
  939. if _, failed := syncFailedInbounds[old.inboundID]; failed {
  940. continue
  941. }
  942. var stillAttached []string
  943. if err := tx.Table("clients").
  944. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  945. Where("client_inbounds.inbound_id = ?", old.inboundID).
  946. Pluck("email", &stillAttached).Error; err != nil {
  947. continue
  948. }
  949. stillSet := make(map[string]struct{}, len(stillAttached))
  950. for _, e := range stillAttached {
  951. stillSet[e] = struct{}{}
  952. }
  953. for email := range old.emails {
  954. if _, kept := stillSet[email]; kept {
  955. continue
  956. }
  957. var attachmentCount int64
  958. if err := tx.Table("client_inbounds").
  959. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  960. Where("clients.email = ?", email).
  961. Count(&attachmentCount).Error; err != nil {
  962. continue
  963. }
  964. if attachmentCount > 0 {
  965. continue
  966. }
  967. // "Ended the merge unattached" is true for a real remote deletion and
  968. // equally true for a bad merge, so record a strike instead of deleting.
  969. if err := markSyncOrphan(tx, email, now); err != nil {
  970. logger.Warningf("setRemoteTraffic: mark orphan %q failed: %v", email, err)
  971. continue
  972. }
  973. structuralChange = true
  974. }
  975. }
  976. if err := clearSyncOrphanMarks(tx); err != nil {
  977. logger.Warning("setRemoteTraffic: clear orphan marks failed:", err)
  978. }
  979. if err := liftActivatedClientRecordExpiries(tx); err != nil {
  980. logger.Warning("setRemoteTraffic: lift activated expiries failed:", err)
  981. }
  982. if err := tx.Commit().Error; err != nil {
  983. return false, err
  984. }
  985. committed = true
  986. if len(adoptedInbounds) > 0 {
  987. if mgr := runtime.GetManager(); mgr != nil {
  988. if rt, rtErr := mgr.RuntimeFor(&nodeID); rtErr == nil {
  989. if rem, ok := rt.(*runtime.Remote); ok {
  990. for _, ib := range adoptedInbounds {
  991. rem.RecordAdoptedInbound(ib)
  992. }
  993. }
  994. }
  995. }
  996. }
  997. if process := currentXrayProcess(); process != nil {
  998. tree := snap.OnlineTree
  999. switch {
  1000. case len(tree) == 0 && len(snap.OnlineEmails) > 0:
  1001. // Old-build node (no GUID tree): key its flat online list under its
  1002. // own effective identity so attribution still works for that branch.
  1003. tree = map[string][]string{selfKey: snap.OnlineEmails}
  1004. case guidShared && len(tree) > 0:
  1005. // Newer cloned node: its own clients arrive keyed under the shared
  1006. // panelGuid. Remap just that entry to the node-unique key so the
  1007. // clones don't merge; descendant subtrees keep their distinct GUIDs.
  1008. if _, ok := tree[nodeRow.Guid]; ok {
  1009. remapped := make(map[string][]string, len(tree))
  1010. for g, emails := range tree {
  1011. if g == nodeRow.Guid {
  1012. g = selfKey
  1013. }
  1014. remapped[g] = emails
  1015. }
  1016. tree = remapped
  1017. }
  1018. }
  1019. process.SetNodeOnlineTree(nodeID, tree)
  1020. }
  1021. return structuralChange, nil
  1022. }
  1023. func (s *InboundService) GetOnlineClients() []string {
  1024. process := currentXrayProcess()
  1025. if process == nil {
  1026. return []string{}
  1027. }
  1028. return process.GetOnlineClients()
  1029. }
  1030. // GetOnlineClientsByGuid returns online emails keyed by the panelGuid of the
  1031. // node that physically hosts each set: this panel's own clients under its own
  1032. // GUID, plus every node in the tree under its GUID (#4983). Replaces the old
  1033. // node-id keying so a client three hops down is attributed to its real node,
  1034. // not the intermediate one it was synced through.
  1035. func (s *InboundService) GetOnlineClientsByGuid() map[string][]string {
  1036. process := currentXrayProcess()
  1037. if process == nil {
  1038. return map[string][]string{}
  1039. }
  1040. out := process.GetMergedNodeTrees()
  1041. if local := process.GetLocalOnlineClients(); len(local) > 0 {
  1042. if guid := s.panelGuid(); guid != "" {
  1043. out[guid] = mergeEmails(out[guid], local)
  1044. }
  1045. }
  1046. return out
  1047. }
  1048. // GetActiveInboundsByGuid returns the inbound tags that carried traffic within
  1049. // the grace window for THIS panel, under its own GUID. Remote nodes don't
  1050. // report per-inbound activity, so a GUID missing from the map means "don't
  1051. // gate" for that node's inbounds.
  1052. func (s *InboundService) GetActiveInboundsByGuid() map[string][]string {
  1053. process := currentXrayProcess()
  1054. if process == nil {
  1055. return map[string][]string{}
  1056. }
  1057. active := process.GetLocalActiveInbounds()
  1058. if len(active) == 0 {
  1059. return map[string][]string{}
  1060. }
  1061. guid := s.panelGuid()
  1062. if guid == "" {
  1063. return map[string][]string{}
  1064. }
  1065. return map[string][]string{guid: active}
  1066. }
  1067. func (s *InboundService) SetNodeOnlineTree(nodeID int, tree map[string][]string) {
  1068. if process := currentXrayProcess(); process != nil {
  1069. process.SetNodeOnlineTree(nodeID, tree)
  1070. }
  1071. }
  1072. func (s *InboundService) ClearNodeOnlineClients(nodeID int) {
  1073. if process := currentXrayProcess(); process != nil {
  1074. process.ClearNodeOnlineClients(nodeID)
  1075. }
  1076. }
  1077. // panelGuid returns this panel's stable self-identifier, used to key the local
  1078. // panel's own clients in the per-node online maps (#4983).
  1079. func (s *InboundService) panelGuid() string {
  1080. guid, _ := (&SettingService{}).GetPanelGuid()
  1081. return guid
  1082. }
  1083. // synthNodeGuid is the stable per-node fallback identity for a directly-attached
  1084. // node whose panel hasn't reported a panelGuid yet (old build). Node ids are
  1085. // master-local, so this only composes for direct nodes — exactly the pre-#4983
  1086. // flat-topology case where an old-build node appears.
  1087. func synthNodeGuid(nodeID int) string {
  1088. return fmt.Sprintf("node:%d", nodeID)
  1089. }
  1090. // mergeEmails returns the deduped union of two email slices.
  1091. func mergeEmails(a, b []string) []string {
  1092. if len(a) == 0 {
  1093. return b
  1094. }
  1095. seen := make(map[string]struct{}, len(a)+len(b))
  1096. out := make([]string, 0, len(a)+len(b))
  1097. for _, e := range a {
  1098. if _, ok := seen[e]; !ok {
  1099. seen[e] = struct{}{}
  1100. out = append(out, e)
  1101. }
  1102. }
  1103. for _, e := range b {
  1104. if _, ok := seen[e]; !ok {
  1105. seen[e] = struct{}{}
  1106. out = append(out, e)
  1107. }
  1108. }
  1109. return out
  1110. }
  1111. func (s *InboundService) GetClientsLastOnline() (map[string]int64, error) {
  1112. db := database.GetDB()
  1113. var rows []xray.ClientTraffic
  1114. err := db.Model(&xray.ClientTraffic{}).Select("email, last_online").Find(&rows).Error
  1115. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1116. return nil, err
  1117. }
  1118. result := make(map[string]int64, len(rows))
  1119. for _, r := range rows {
  1120. result[r.Email] = r.LastOnline
  1121. }
  1122. return result, nil
  1123. }
  1124. // RefreshLocalOnlineClients folds the emails and inbound tags active on this
  1125. // panel's own xray this poll into the local online/active sets, applying the
  1126. // grace window and pruning stale entries. Pass nil to only prune. See
  1127. // xray.Process for why the local sets are kept separate from the shared
  1128. // last_online column.
  1129. func (s *InboundService) RefreshLocalOnlineClients(activeEmails, activeInboundTags []string) {
  1130. if process := currentXrayProcess(); process != nil {
  1131. process.RefreshLocalOnline(activeEmails, activeInboundTags, time.Now().UnixMilli(), onlineGracePeriodMs)
  1132. }
  1133. }
  1134. func (s *InboundService) FilterAndSortClientEmails(emails []string) ([]string, []string, error) {
  1135. db := database.GetDB()
  1136. // Step 1: Get ClientTraffic records for emails in the input list.
  1137. // Chunked to stay under SQLite's bind-variable limit on huge inputs.
  1138. uniqEmails := uniqueNonEmptyStrings(emails)
  1139. clients := make([]xray.ClientTraffic, 0, len(uniqEmails))
  1140. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  1141. var page []xray.ClientTraffic
  1142. if err := db.Where("email IN ?", batch).Find(&page).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1143. return nil, nil, err
  1144. }
  1145. clients = append(clients, page...)
  1146. }
  1147. // Step 2: Sort clients by (Up + Down) descending
  1148. sort.Slice(clients, func(i, j int) bool {
  1149. return (clients[i].Up + clients[i].Down) > (clients[j].Up + clients[j].Down)
  1150. })
  1151. // Step 3: Extract sorted valid emails and track found ones
  1152. validEmails := make([]string, 0, len(clients))
  1153. found := make(map[string]bool)
  1154. for _, client := range clients {
  1155. validEmails = append(validEmails, client.Email)
  1156. found[client.Email] = true
  1157. }
  1158. // Step 4: Identify emails that were not found in the database
  1159. extraEmails := make([]string, 0)
  1160. for _, email := range emails {
  1161. if !found[email] {
  1162. extraEmails = append(extraEmails, email)
  1163. }
  1164. }
  1165. return validEmails, extraEmails, nil
  1166. }