1
0

inbound_node.go 30 KB

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