inbound_node.go 33 KB

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