inbound_node.go 34 KB

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