inbound_node.go 33 KB

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