inbound_node.go 40 KB

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