inbound_node.go 31 KB

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