inbound_node.go 28 KB

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