1
0

inbound_node.go 44 KB

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