inbound_node.go 40 KB

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