inbound_node.go 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410
  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.ResetDay <= 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. DisableFlow: snapIb.DisableFlow,
  595. }
  596. if err := tx.Create(&newIb).Error; err != nil {
  597. logger.Warningf("setRemoteTraffic: create central inbound for tag %q failed: %v", snapIb.Tag, err)
  598. continue
  599. }
  600. tagToCentral[snapIb.Tag] = &newIb
  601. if newIb.Tag != snapIb.Tag {
  602. tagToCentral[newIb.Tag] = &newIb
  603. }
  604. if rows := adoptedHostRows(snap.HostGroups, snapIb.Id, newIb.Id); len(rows) > 0 {
  605. if err := tx.Create(&rows).Error; err != nil {
  606. logger.Warningf("setRemoteTraffic: adopt host rows for tag %q failed: %v", newIb.Tag, err)
  607. }
  608. }
  609. newInboundIDs[newIb.Id] = struct{}{}
  610. structuralChange = true
  611. continue
  612. }
  613. inGrace := c.LastTrafficResetTime > 0 && now-c.LastTrafficResetTime < resetGracePeriodMs
  614. // Adopting the node's settings verbatim would re-add a client the master
  615. // deleted moments ago if this snapshot was fetched before the deletion
  616. // push landed — filter just-deleted emails out while their tombstone lives.
  617. adoptedSettings := snapIb.Settings
  618. if stripped, changed := stripTombstonedClients(adoptedSettings); changed {
  619. adoptedSettings = stripped
  620. }
  621. if deduped, changed := dedupeSettingsClients(adoptedSettings); changed {
  622. adoptedSettings = deduped
  623. }
  624. updates := map[string]any{}
  625. if !dirty {
  626. updates["enable"] = snapIb.Enable
  627. updates["remark"] = snapIb.Remark
  628. updates["sub_sort_index"] = normalizeSubSortIndex(snapIb.SubSortIndex)
  629. updates["listen"] = snapIb.Listen
  630. updates["port"] = snapIb.Port
  631. updates["protocol"] = snapIb.Protocol
  632. updates["total"] = snapIb.Total
  633. updates["expiry_time"] = snapIb.ExpiryTime
  634. updates["settings"] = adoptedSettings
  635. updates["stream_settings"] = snapIb.StreamSettings
  636. updates["sniffing"] = snapIb.Sniffing
  637. updates["traffic_reset"] = snapIb.TrafficReset
  638. updates["traffic_reset_day"] = normalizeTrafficResetDay(snapIb.TrafficResetDay)
  639. updates["last_traffic_reset_time"] = snapIb.LastTrafficResetTime
  640. if adoptedWireChanged(c, snapIb, adoptedSettings) {
  641. adoptedInbounds = append(adoptedInbounds, adoptedWireInbound(c, snapIb, adoptedSettings))
  642. }
  643. }
  644. if !inGrace || (snapIb.Up+snapIb.Down) <= (c.Up+c.Down) {
  645. updates["up"] = snapIb.Up
  646. updates["down"] = snapIb.Down
  647. }
  648. // Physical-home attribution is independent of config-dirty state, so
  649. // keep it current even while the node has pending offline edits. Writes
  650. // once to backfill an existing row, then stays equal (#4983).
  651. if og := originGuidFor(snapIb); c.OriginNodeGuid != og {
  652. updates["origin_node_guid"] = og
  653. }
  654. if !dirty && (c.Settings != adoptedSettings ||
  655. c.Remark != snapIb.Remark ||
  656. c.Listen != snapIb.Listen ||
  657. c.Port != snapIb.Port ||
  658. c.Total != snapIb.Total ||
  659. c.ExpiryTime != snapIb.ExpiryTime ||
  660. c.Enable != snapIb.Enable) {
  661. structuralChange = true
  662. }
  663. if len(updates) > 0 {
  664. if err := tx.Model(model.Inbound{}).
  665. Where("id = ?", c.Id).
  666. Updates(updates).Error; err != nil {
  667. return false, err
  668. }
  669. }
  670. }
  671. for _, c := range central {
  672. if dirty {
  673. continue
  674. }
  675. // Disabled inbounds are intentionally absent from the node's runtime
  676. // snapshot. Their absence is not evidence of deletion; retain the row,
  677. // client history and port reservation until an explicit delete occurs.
  678. if !c.Enable {
  679. continue
  680. }
  681. if len(snapTags) == 0 {
  682. // A node mid-restart or with a transient DB error can return an empty
  683. // inbound list with success=true. Treat "zero inbounds reported" as
  684. // "nothing to say", not "delete all my inbounds" — otherwise a blip
  685. // wipes the node's central inbounds and every client on them (and
  686. // resets traffic history on re-create). A real per-inbound deletion
  687. // still sweeps, because the node keeps reporting its other inbounds.
  688. continue
  689. }
  690. if _, kept := snapTags[c.Tag]; kept {
  691. continue
  692. }
  693. if unmanagedTag(c.Tag) {
  694. continue
  695. }
  696. // This drops the central inbound and its clients' traffic history, so say
  697. // so: silent removal is indistinguishable from an inbound never arriving.
  698. logger.Warningf("setRemoteTraffic: node %d no longer reports inbound %q (id %d, port %d) — removing it centrally", nodeID, c.Tag, c.Id, c.Port)
  699. var goneEmails []string
  700. if err := tx.Model(xray.ClientTraffic{}).
  701. Where("inbound_id = ?", c.Id).
  702. Pluck("email", &goneEmails).Error; err != nil {
  703. return false, err
  704. }
  705. if len(goneEmails) > 0 {
  706. // Baselines are per (node, email), not per inbound: keep them for
  707. // emails the snapshot still reports under a sibling inbound (#5202).
  708. baselineGone := make([]string, 0, len(goneEmails))
  709. for _, e := range goneEmails {
  710. if _, still := snapEmailsAll[e]; !still {
  711. baselineGone = append(baselineGone, e)
  712. }
  713. }
  714. // Chunk to avoid SQLite bind var limit when a node has many clients
  715. // removed (e.g. after API bulk delete or structural change on node inbound).
  716. for _, batch := range chunkStrings(baselineGone, sqliteMaxVars) {
  717. if err := tx.Where("node_id = ? AND email IN ?", nodeID, batch).
  718. Delete(&model.NodeClientTraffic{}).Error; err != nil {
  719. return false, err
  720. }
  721. }
  722. // The per-email row is the shared accumulator across every inbound
  723. // (and node) the email is attached to. Only drop it when this was the
  724. // email's last inbound — wiping it while a sibling still feeds it
  725. // loses the summed history, and the next node sync would re-seed the
  726. // row with that node's counter alone.
  727. sharedEmails, sErr := s.emailsUsedByOtherInbounds(goneEmails, c.Id)
  728. if sErr != nil {
  729. return false, sErr
  730. }
  731. delEmails := make([]string, 0, len(goneEmails))
  732. for _, e := range goneEmails {
  733. if !sharedEmails[strings.ToLower(strings.TrimSpace(e))] {
  734. delEmails = append(delEmails, e)
  735. }
  736. }
  737. for _, batch := range chunkStrings(delEmails, sqliteMaxVars) {
  738. if err := tx.Where("inbound_id = ? AND email IN ?", c.Id, batch).
  739. Delete(&xray.ClientTraffic{}).Error; err != nil {
  740. return false, err
  741. }
  742. }
  743. }
  744. if err := s.clientService.DetachInbound(tx, c.Id); err != nil {
  745. return false, err
  746. }
  747. if err := tx.Where("id = ?", c.Id).
  748. Delete(&model.Inbound{}).Error; err != nil {
  749. return false, err
  750. }
  751. delete(tagToCentral, c.Tag)
  752. structuralChange = true
  753. }
  754. for _, snapIb := range snap.Inbounds {
  755. if snapIb == nil {
  756. continue
  757. }
  758. c, ok := tagToCentral[snapIb.Tag]
  759. if !ok {
  760. continue
  761. }
  762. snapEmails := make(map[string]struct{}, len(snapIb.ClientStats))
  763. for _, cs := range snapIb.ClientStats {
  764. snapEmails[cs.Email] = struct{}{}
  765. // Node-wide total, not this inbound's possibly-stale copy (#5274).
  766. canon := nodeEmailTotals[cs.Email]
  767. base, seen := nodeBaselines[cs.Email]
  768. var deltaUp, deltaDown int64
  769. if seen {
  770. if deltaUp = canon.Up - base.Up; deltaUp < 0 {
  771. deltaUp = 0
  772. }
  773. if deltaDown = canon.Down - base.Down; deltaDown < 0 {
  774. deltaDown = 0
  775. }
  776. }
  777. if _, rowExists := existingEmails[cs.Email]; !rowExists {
  778. if dirty {
  779. continue
  780. }
  781. _, isNewInbound := newInboundIDs[c.Id]
  782. // On a known inbound a missing row plus a live tombstone means the
  783. // master just deleted this client and the snapshot predates the
  784. // deletion push — recreating the row (at zero) would resurrect the
  785. // client. A freshly adopted inbound still gets its row (seeded at
  786. // zero) so adoption semantics stay intact.
  787. if !isNewInbound && isClientEmailTombstoned(cs.Email) {
  788. continue
  789. }
  790. var seedUp, seedDown int64
  791. if isNewInbound && !isClientEmailTombstoned(cs.Email) {
  792. seedUp, seedDown = canon.Up, canon.Down
  793. }
  794. row := &xray.ClientTraffic{
  795. InboundId: c.Id,
  796. Email: cs.Email,
  797. Enable: cs.Enable,
  798. Total: cs.Total,
  799. ExpiryTime: cs.ExpiryTime,
  800. Reset: cs.Reset,
  801. ResetDay: cs.ResetDay,
  802. Up: seedUp,
  803. Down: seedDown,
  804. LastOnline: cs.LastOnline,
  805. }
  806. if err := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "email"}}, DoNothing: true}).
  807. Create(row).Error; err != nil {
  808. return false, err
  809. }
  810. centralCS[csKey{c.Id, cs.Email}] = row
  811. centralCSByEmail[cs.Email] = row
  812. existingEmails[cs.Email] = struct{}{}
  813. structuralChange = true
  814. if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon.Up, canon.Down); err != nil {
  815. return false, err
  816. }
  817. nodeBaselines[cs.Email] = nodeTrafficCounter{Up: canon.Up, Down: canon.Down}
  818. continue
  819. }
  820. existing := centralCSByEmail[cs.Email]
  821. if existing != nil &&
  822. (existing.Enable != cs.Enable ||
  823. existing.Total != cs.Total ||
  824. existing.ExpiryTime != mergeActivationExpiry(existing.ExpiryTime, cs.ExpiryTime) ||
  825. existing.Reset != cs.Reset) {
  826. structuralChange = true
  827. }
  828. if seen && existing != nil && nodeClientRenewed(existing, cs, canon, base) {
  829. // A renewal starts a fresh quota window: adopt the node's counters
  830. // and enable state, drop stale pushes (mirrors autoRenewClients).
  831. if err := tx.Exec(
  832. fmt.Sprintf(
  833. `UPDATE client_traffics
  834. SET up = ?, down = ?, enable = ?, total = ?,
  835. expiry_time = ?, reset = ?, reset_day = ?, last_online = %s
  836. WHERE email = ?`,
  837. database.GreatestExpr("last_online", "?"),
  838. ),
  839. canon.Up, canon.Down, cs.Enable, cs.Total,
  840. cs.ExpiryTime, cs.Reset, cs.ResetDay,
  841. cs.LastOnline, cs.Email,
  842. ).Error; err != nil {
  843. return false, err
  844. }
  845. if err := clearGlobalTraffic(tx, cs.Email); err != nil {
  846. return false, err
  847. }
  848. } else {
  849. enableExpr := database.ClientTrafficEnableMergeExpr()
  850. // expiry_time merge mirrors mergeActivationExpiry: a node that has not
  851. // yet seen the client's first connection keeps reporting the negative
  852. // "start after first connect" duration, which must never reset the
  853. // absolute deadline another node already activated. A positive node
  854. // value is still adopted (e.g. auto-renew moves the deadline forward).
  855. // CAST(? AS BIGINT): in the `<= 0` comparison Postgres would otherwise
  856. // infer int4 from the literal and overflow on real expiry values.
  857. if err := tx.Exec(
  858. fmt.Sprintf(
  859. `UPDATE client_traffics
  860. SET up = %s, down = %s, enable = %s, total = ?,
  861. expiry_time = CASE WHEN expiry_time > 0 AND CAST(? AS BIGINT) <= 0 THEN expiry_time ELSE CAST(? AS BIGINT) END,
  862. reset = ?, reset_day = ?, last_online = %s
  863. WHERE email = ?`,
  864. database.ClampedAddExpr("up"),
  865. database.ClampedAddExpr("down"),
  866. enableExpr,
  867. database.GreatestExpr("last_online", "?"),
  868. ),
  869. deltaUp, deltaDown, cs.Enable, cs.Total,
  870. cs.ExpiryTime, cs.ExpiryTime, cs.Reset, cs.ResetDay,
  871. cs.LastOnline, cs.Email,
  872. ).Error; err != nil {
  873. return false, err
  874. }
  875. }
  876. if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon.Up, canon.Down); err != nil {
  877. return false, err
  878. }
  879. nodeBaselines[cs.Email] = nodeTrafficCounter{Up: canon.Up, Down: canon.Down}
  880. }
  881. for k, existing := range centralCS {
  882. if dirty {
  883. continue
  884. }
  885. if k.inboundID != c.Id {
  886. continue
  887. }
  888. if _, kept := snapEmails[k.email]; kept {
  889. continue
  890. }
  891. // Gone from this inbound's stats but still reported by the node under
  892. // a sibling inbound: both the shared accumulator row and the (node,
  893. // email) baseline must survive, or the sibling's next delta would
  894. // compute against nothing and freeze the counter (#5202).
  895. if _, still := snapEmailsAll[k.email]; still {
  896. continue
  897. }
  898. if err := tx.Where("node_id = ? AND email = ?", nodeID, existing.Email).
  899. Delete(&model.NodeClientTraffic{}).Error; err != nil {
  900. return false, err
  901. }
  902. // Same shared-accumulator rule as the inbound-removal sweep above:
  903. // keep the row while another inbound still references the email.
  904. stillUsed, uErr := s.emailUsedByOtherInbounds(existing.Email, c.Id)
  905. if uErr != nil {
  906. return false, uErr
  907. }
  908. // Usage, quota and expiry live on this row, so a client the orphan
  909. // sweep will mark keeps it until the reaper confirms the removal.
  910. if !stillUsed && !clientRecordExists(tx, existing.Email) {
  911. if err := tx.Where("inbound_id = ? AND email = ?", c.Id, existing.Email).
  912. Delete(&xray.ClientTraffic{}).Error; err != nil {
  913. return false, err
  914. }
  915. }
  916. structuralChange = true
  917. }
  918. }
  919. type oldSet struct {
  920. inboundID int
  921. emails map[string]struct{}
  922. }
  923. var perInboundOld []oldSet
  924. syncFailedInbounds := map[int]struct{}{}
  925. for _, snapIb := range snap.Inbounds {
  926. if snapIb == nil {
  927. continue
  928. }
  929. c, ok := tagToCentral[snapIb.Tag]
  930. if !ok {
  931. continue
  932. }
  933. if dirty {
  934. continue
  935. }
  936. var oldEmailsRows []string
  937. if err := tx.Table("clients").
  938. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  939. Where("client_inbounds.inbound_id = ?", c.Id).
  940. Pluck("email", &oldEmailsRows).Error; err == nil {
  941. oldEmails := make(map[string]struct{}, len(oldEmailsRows))
  942. for _, e := range oldEmailsRows {
  943. if e != "" {
  944. oldEmails[e] = struct{}{}
  945. }
  946. }
  947. perInboundOld = append(perInboundOld, oldSet{inboundID: c.Id, emails: oldEmails})
  948. }
  949. clients, gcErr := s.GetClients(snapIb)
  950. if gcErr != nil {
  951. logger.Warningf("setRemoteTraffic: parse clients for tag %q failed: %v", snapIb.Tag, gcErr)
  952. continue
  953. }
  954. csEnableByEmail := make(map[string]bool, len(snapIb.ClientStats))
  955. for _, cs := range snapIb.ClientStats {
  956. csEnableByEmail[cs.Email] = cs.Enable
  957. }
  958. filtered := clients[:0]
  959. for i := range clients {
  960. if isClientEmailTombstoned(clients[i].Email) {
  961. continue
  962. }
  963. if cse, hit := csEnableByEmail[clients[i].Email]; hit && !cse {
  964. clients[i].Enable = false
  965. }
  966. filtered = append(filtered, clients[i])
  967. }
  968. localEmails := make([]string, 0, len(filtered))
  969. for i := range filtered {
  970. if filtered[i].Email != "" {
  971. localEmails = append(localEmails, filtered[i].Email)
  972. }
  973. }
  974. if len(localEmails) > 0 {
  975. var localMeta []struct {
  976. Email string
  977. Comment string `gorm:"column:comment"`
  978. }
  979. if err := tx.Table("clients").
  980. Select("email, comment").
  981. Where("email IN ?", localEmails).
  982. Find(&localMeta).Error; err == nil {
  983. commentByEmail := make(map[string]string, len(localMeta))
  984. for _, m := range localMeta {
  985. commentByEmail[m.Email] = m.Comment
  986. }
  987. for i := range filtered {
  988. if cmt, ok := commentByEmail[filtered[i].Email]; ok {
  989. filtered[i].Comment = cmt
  990. }
  991. }
  992. }
  993. }
  994. if err := s.clientService.SyncInbound(tx, c.Id, filtered); err != nil {
  995. logger.Warningf("setRemoteTraffic: sync clients for tag %q failed: %v", snapIb.Tag, err)
  996. syncFailedInbounds[c.Id] = struct{}{}
  997. }
  998. }
  999. for _, old := range perInboundOld {
  1000. // The sweep's premise is that links were just rebuilt from the snapshot,
  1001. // which is exactly what a failed SyncInbound violates.
  1002. if _, failed := syncFailedInbounds[old.inboundID]; failed {
  1003. continue
  1004. }
  1005. var stillAttached []string
  1006. if err := tx.Table("clients").
  1007. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  1008. Where("client_inbounds.inbound_id = ?", old.inboundID).
  1009. Pluck("email", &stillAttached).Error; err != nil {
  1010. continue
  1011. }
  1012. stillSet := make(map[string]struct{}, len(stillAttached))
  1013. for _, e := range stillAttached {
  1014. stillSet[e] = struct{}{}
  1015. }
  1016. for email := range old.emails {
  1017. if _, kept := stillSet[email]; kept {
  1018. continue
  1019. }
  1020. var attachmentCount int64
  1021. if err := tx.Table("client_inbounds").
  1022. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  1023. Where("clients.email = ?", email).
  1024. Count(&attachmentCount).Error; err != nil {
  1025. continue
  1026. }
  1027. if attachmentCount > 0 {
  1028. continue
  1029. }
  1030. // "Ended the merge unattached" is true for a real remote deletion and
  1031. // equally true for a bad merge, so record a strike instead of deleting.
  1032. if err := markSyncOrphan(tx, email, now); err != nil {
  1033. logger.Warningf("setRemoteTraffic: mark orphan %q failed: %v", email, err)
  1034. continue
  1035. }
  1036. structuralChange = true
  1037. }
  1038. }
  1039. if err := clearSyncOrphanMarks(tx); err != nil {
  1040. logger.Warning("setRemoteTraffic: clear orphan marks failed:", err)
  1041. }
  1042. if err := liftActivatedClientRecordExpiries(tx); err != nil {
  1043. logger.Warning("setRemoteTraffic: lift activated expiries failed:", err)
  1044. }
  1045. if err := tx.Commit().Error; err != nil {
  1046. return false, err
  1047. }
  1048. committed = true
  1049. if len(adoptedInbounds) > 0 {
  1050. if mgr := runtime.GetManager(); mgr != nil {
  1051. if rt, rtErr := mgr.RuntimeFor(&nodeID); rtErr == nil {
  1052. if rem, ok := rt.(*runtime.Remote); ok {
  1053. for _, ib := range adoptedInbounds {
  1054. rem.RecordAdoptedInbound(ib)
  1055. }
  1056. }
  1057. }
  1058. }
  1059. }
  1060. if process := currentXrayProcess(); process != nil {
  1061. tree := snap.OnlineTree
  1062. switch {
  1063. case len(tree) == 0 && len(snap.OnlineEmails) > 0:
  1064. // Old-build node (no GUID tree): key its flat online list under its
  1065. // own effective identity so attribution still works for that branch.
  1066. tree = map[string][]string{selfKey: snap.OnlineEmails}
  1067. case guidShared && len(tree) > 0:
  1068. // Newer cloned node: its own clients arrive keyed under the shared
  1069. // panelGuid. Remap just that entry to the node-unique key so the
  1070. // clones don't merge; descendant subtrees keep their distinct GUIDs.
  1071. if _, ok := tree[nodeRow.Guid]; ok {
  1072. tree = remapGuidTreeKey(tree, nodeRow.Guid, selfKey)
  1073. }
  1074. }
  1075. process.SetNodeOnlineTree(nodeID, tree)
  1076. activeTree := normalizeActiveInboundTreeTags(snap.ActiveInboundTree, tagToCentral)
  1077. if guidShared && len(activeTree) > 0 {
  1078. if _, ok := activeTree[nodeRow.Guid]; ok {
  1079. activeTree = remapGuidTreeKey(activeTree, nodeRow.Guid, selfKey)
  1080. }
  1081. }
  1082. if len(activeTree) > 0 {
  1083. activeTree = filterGuidTreeKeys(activeTree, activeInboundGuidKeys(snap.Inbounds, tagToCentral, originGuidFor))
  1084. }
  1085. process.SetNodeActiveInboundTree(nodeID, activeTree)
  1086. }
  1087. return structuralChange, nil
  1088. }
  1089. func (s *InboundService) restartRemoteNodesOnDisable(nodeIDs []int) {
  1090. restartOnDisable, err := (&SettingService{}).GetRestartXrayOnClientDisable()
  1091. if err != nil {
  1092. logger.Warning("disableInvalidClients: get RestartXrayOnClientDisable failed:", err)
  1093. return
  1094. }
  1095. if !restartOnDisable {
  1096. return
  1097. }
  1098. for _, nodeID := range nodeIDs {
  1099. nodeIDCopy := nodeID
  1100. rt, rtErr := runtime.GetManager().RuntimeFor(&nodeIDCopy)
  1101. if rtErr != nil {
  1102. logger.Warning("disableInvalidClients: get runtime for node", nodeID, "failed:", rtErr)
  1103. continue
  1104. }
  1105. if rtErr = rt.RestartXray(context.Background()); rtErr != nil {
  1106. logger.Warning("disableInvalidClients: restart xray on node", nodeID, "failed:", rtErr)
  1107. }
  1108. }
  1109. }
  1110. func (s *InboundService) GetOnlineClients() []string {
  1111. process := currentXrayProcess()
  1112. if process == nil {
  1113. return []string{}
  1114. }
  1115. return process.GetOnlineClients()
  1116. }
  1117. // GetOnlineClientsByGuid returns online emails keyed by the panelGuid of the
  1118. // node that physically hosts each set: this panel's own clients under its own
  1119. // GUID, plus every node in the tree under its GUID (#4983). Replaces the old
  1120. // node-id keying so a client three hops down is attributed to its real node,
  1121. // not the intermediate one it was synced through.
  1122. func (s *InboundService) GetOnlineClientsByGuid() map[string][]string {
  1123. process := currentXrayProcess()
  1124. if process == nil {
  1125. return map[string][]string{}
  1126. }
  1127. out := process.GetMergedNodeTrees()
  1128. if local := process.GetLocalOnlineClients(); len(local) > 0 {
  1129. if guid := s.panelGuid(); guid != "" {
  1130. out[guid] = mergeEmails(out[guid], local)
  1131. }
  1132. }
  1133. return out
  1134. }
  1135. // GetActiveInboundsByGuid returns the inbound tags that carried traffic within
  1136. // the grace window, keyed by the panelGuid of the node that physically hosts
  1137. // each inbound. A GUID missing from the map means "don't gate" for that node's
  1138. // inbounds (old-build node or no active-inbound signal).
  1139. func (s *InboundService) GetActiveInboundsByGuid() map[string][]string {
  1140. process := currentXrayProcess()
  1141. if process == nil {
  1142. return map[string][]string{}
  1143. }
  1144. out := process.GetMergedActiveInboundTrees()
  1145. active := process.GetLocalActiveInbounds()
  1146. if len(active) == 0 {
  1147. return out
  1148. }
  1149. guid := s.panelGuid()
  1150. if guid == "" {
  1151. return out
  1152. }
  1153. out[guid] = mergeEmails(out[guid], active)
  1154. return out
  1155. }
  1156. func (s *InboundService) SetNodeOnlineTree(nodeID int, tree map[string][]string) {
  1157. if process := currentXrayProcess(); process != nil {
  1158. process.SetNodeOnlineTree(nodeID, tree)
  1159. }
  1160. }
  1161. func (s *InboundService) ClearNodeOnlineClients(nodeID int) {
  1162. if process := currentXrayProcess(); process != nil {
  1163. process.ClearNodeOnlineClients(nodeID)
  1164. }
  1165. }
  1166. // panelGuid returns this panel's stable self-identifier, used to key the local
  1167. // panel's own clients in the per-node online maps (#4983).
  1168. func (s *InboundService) panelGuid() string {
  1169. guid, _ := (&SettingService{}).GetPanelGuid()
  1170. return guid
  1171. }
  1172. // synthNodeGuid is the stable per-node fallback identity for a directly-attached
  1173. // node whose panel hasn't reported a panelGuid yet (old build). Node ids are
  1174. // master-local, so this only composes for direct nodes — exactly the pre-#4983
  1175. // flat-topology case where an old-build node appears.
  1176. func synthNodeGuid(nodeID int) string {
  1177. return fmt.Sprintf("node:%d", nodeID)
  1178. }
  1179. // mergeEmails returns the deduped union of two email slices.
  1180. func mergeEmails(a, b []string) []string {
  1181. if len(a) == 0 {
  1182. return b
  1183. }
  1184. seen := make(map[string]struct{}, len(a)+len(b))
  1185. out := make([]string, 0, len(a)+len(b))
  1186. for _, e := range a {
  1187. if _, ok := seen[e]; !ok {
  1188. seen[e] = struct{}{}
  1189. out = append(out, e)
  1190. }
  1191. }
  1192. for _, e := range b {
  1193. if _, ok := seen[e]; !ok {
  1194. seen[e] = struct{}{}
  1195. out = append(out, e)
  1196. }
  1197. }
  1198. return out
  1199. }
  1200. func remapGuidTreeKey(tree map[string][]string, from, to string) map[string][]string {
  1201. if from == "" || to == "" || from == to {
  1202. return tree
  1203. }
  1204. remapped := make(map[string][]string, len(tree))
  1205. for guid, values := range tree {
  1206. if guid == from {
  1207. guid = to
  1208. }
  1209. remapped[guid] = mergeEmails(remapped[guid], values)
  1210. }
  1211. return remapped
  1212. }
  1213. func normalizeActiveInboundTreeTags(tree map[string][]string, tagToCentral map[string]*model.Inbound) map[string][]string {
  1214. if len(tree) == 0 {
  1215. return nil
  1216. }
  1217. out := make(map[string][]string, len(tree))
  1218. for guid, tags := range tree {
  1219. if guid == "" || len(tags) == 0 {
  1220. continue
  1221. }
  1222. seen := make(map[string]struct{}, len(tags))
  1223. for _, tag := range tags {
  1224. if tag == "" {
  1225. continue
  1226. }
  1227. if central, ok := tagToCentral[tag]; ok && central != nil && central.Tag != "" {
  1228. tag = central.Tag
  1229. }
  1230. if _, dup := seen[tag]; dup {
  1231. continue
  1232. }
  1233. seen[tag] = struct{}{}
  1234. out[guid] = append(out[guid], tag)
  1235. }
  1236. }
  1237. if len(out) == 0 {
  1238. return nil
  1239. }
  1240. return out
  1241. }
  1242. func activeInboundGuidKeys(inbounds []*model.Inbound, tagToCentral map[string]*model.Inbound, originGuidFor func(*model.Inbound) string) map[string]struct{} {
  1243. allowed := make(map[string]struct{})
  1244. for _, ib := range inbounds {
  1245. if ib == nil {
  1246. continue
  1247. }
  1248. if _, ok := tagToCentral[ib.Tag]; !ok {
  1249. continue
  1250. }
  1251. if guid := originGuidFor(ib); guid != "" {
  1252. allowed[guid] = struct{}{}
  1253. }
  1254. }
  1255. return allowed
  1256. }
  1257. func filterGuidTreeKeys(tree map[string][]string, allowed map[string]struct{}) map[string][]string {
  1258. if len(tree) == 0 || len(allowed) == 0 {
  1259. return nil
  1260. }
  1261. out := make(map[string][]string, len(tree))
  1262. for guid, values := range tree {
  1263. if _, ok := allowed[guid]; !ok {
  1264. continue
  1265. }
  1266. if len(values) > 0 {
  1267. out[guid] = values
  1268. }
  1269. }
  1270. if len(out) == 0 {
  1271. return nil
  1272. }
  1273. return out
  1274. }
  1275. func (s *InboundService) GetClientsLastOnline() (map[string]int64, error) {
  1276. db := database.GetDB()
  1277. var rows []xray.ClientTraffic
  1278. err := db.Model(&xray.ClientTraffic{}).Select("email, last_online").Find(&rows).Error
  1279. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1280. return nil, err
  1281. }
  1282. result := make(map[string]int64, len(rows))
  1283. for _, r := range rows {
  1284. result[r.Email] = r.LastOnline
  1285. }
  1286. return result, nil
  1287. }
  1288. // RefreshLocalOnlineClients folds the emails and inbound tags active on this
  1289. // panel's own xray this poll into the local online/active sets, applying the
  1290. // grace window and pruning stale entries. Pass nil to only prune. See
  1291. // xray.Process for why the local sets are kept separate from the shared
  1292. // last_online column.
  1293. func (s *InboundService) RefreshLocalOnlineClients(activeEmails, activeInboundTags []string) {
  1294. if process := currentXrayProcess(); process != nil {
  1295. process.RefreshLocalOnline(activeEmails, activeInboundTags, time.Now().UnixMilli(), onlineGracePeriodMs)
  1296. }
  1297. }
  1298. func (s *InboundService) FilterAndSortClientEmails(emails []string) ([]string, []string, error) {
  1299. db := database.GetDB()
  1300. // Step 1: Get ClientTraffic records for emails in the input list.
  1301. // Chunked to stay under SQLite's bind-variable limit on huge inputs.
  1302. uniqEmails := uniqueNonEmptyStrings(emails)
  1303. clients := make([]xray.ClientTraffic, 0, len(uniqEmails))
  1304. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  1305. var page []xray.ClientTraffic
  1306. if err := db.Where("email IN ?", batch).Find(&page).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1307. return nil, nil, err
  1308. }
  1309. clients = append(clients, page...)
  1310. }
  1311. // Step 2: Sort clients by (Up + Down) descending
  1312. sort.Slice(clients, func(i, j int) bool {
  1313. return (clients[i].Up + clients[i].Down) > (clients[j].Up + clients[j].Down)
  1314. })
  1315. // Step 3: Extract sorted valid emails and track found ones
  1316. validEmails := make([]string, 0, len(clients))
  1317. found := make(map[string]bool)
  1318. for _, client := range clients {
  1319. validEmails = append(validEmails, client.Email)
  1320. found[client.Email] = true
  1321. }
  1322. // Step 4: Identify emails that were not found in the database
  1323. extraEmails := make([]string, 0)
  1324. for _, email := range emails {
  1325. if !found[email] {
  1326. extraEmails = append(extraEmails, email)
  1327. }
  1328. }
  1329. return validEmails, extraEmails, nil
  1330. }