inbound_node.go 25 KB

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