inbound_node.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877
  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. // The per-email row is the shared accumulator across every inbound
  385. // (and node) the email is attached to. Only drop it when this was the
  386. // email's last inbound — wiping it while a sibling still feeds it
  387. // loses the summed history, and the next node sync would re-seed the
  388. // row with that node's counter alone.
  389. sharedEmails, sErr := s.emailsUsedByOtherInbounds(goneEmails, c.Id)
  390. if sErr != nil {
  391. return false, sErr
  392. }
  393. delEmails := make([]string, 0, len(goneEmails))
  394. for _, e := range goneEmails {
  395. if !sharedEmails[strings.ToLower(strings.TrimSpace(e))] {
  396. delEmails = append(delEmails, e)
  397. }
  398. }
  399. for _, batch := range chunkStrings(delEmails, sqliteMaxVars) {
  400. if err := tx.Where("inbound_id = ? AND email IN ?", c.Id, batch).
  401. Delete(&xray.ClientTraffic{}).Error; err != nil {
  402. return false, err
  403. }
  404. }
  405. }
  406. if err := s.clientService.DetachInbound(tx, c.Id); err != nil {
  407. return false, err
  408. }
  409. if err := tx.Where("id = ?", c.Id).
  410. Delete(&model.Inbound{}).Error; err != nil {
  411. return false, err
  412. }
  413. delete(tagToCentral, c.Tag)
  414. structuralChange = true
  415. }
  416. for _, snapIb := range snap.Inbounds {
  417. if snapIb == nil {
  418. continue
  419. }
  420. c, ok := tagToCentral[snapIb.Tag]
  421. if !ok {
  422. continue
  423. }
  424. snapEmails := make(map[string]struct{}, len(snapIb.ClientStats))
  425. for _, cs := range snapIb.ClientStats {
  426. snapEmails[cs.Email] = struct{}{}
  427. base, seen := nodeBaselines[cs.Email]
  428. var deltaUp, deltaDown int64
  429. if seen {
  430. if deltaUp = cs.Up - base.Up; deltaUp < 0 {
  431. deltaUp = cs.Up
  432. }
  433. if deltaDown = cs.Down - base.Down; deltaDown < 0 {
  434. deltaDown = cs.Down
  435. }
  436. }
  437. if _, rowExists := existingEmails[cs.Email]; !rowExists {
  438. if dirty {
  439. continue
  440. }
  441. row := &xray.ClientTraffic{
  442. InboundId: c.Id,
  443. Email: cs.Email,
  444. Enable: cs.Enable,
  445. Total: cs.Total,
  446. ExpiryTime: cs.ExpiryTime,
  447. Reset: cs.Reset,
  448. Up: cs.Up,
  449. Down: cs.Down,
  450. LastOnline: cs.LastOnline,
  451. }
  452. if err := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "email"}}, DoNothing: true}).
  453. Create(row).Error; err != nil {
  454. return false, err
  455. }
  456. centralCS[csKey{c.Id, cs.Email}] = row
  457. centralCSByEmail[cs.Email] = row
  458. existingEmails[cs.Email] = struct{}{}
  459. structuralChange = true
  460. if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, cs.Up, cs.Down); err != nil {
  461. return false, err
  462. }
  463. nodeBaselines[cs.Email] = nodeTrafficCounter{Up: cs.Up, Down: cs.Down}
  464. continue
  465. }
  466. if existing := centralCSByEmail[cs.Email]; existing != nil &&
  467. (existing.Enable != cs.Enable ||
  468. existing.Total != cs.Total ||
  469. existing.ExpiryTime != cs.ExpiryTime ||
  470. existing.Reset != cs.Reset) {
  471. structuralChange = true
  472. }
  473. enableExpr := database.ClientTrafficEnableMergeExpr()
  474. if err := tx.Exec(
  475. fmt.Sprintf(
  476. `UPDATE client_traffics
  477. SET up = up + ?, down = down + ?, enable = %s, total = ?, expiry_time = ?, reset = ?,
  478. last_online = %s
  479. WHERE email = ?`,
  480. enableExpr,
  481. database.GreatestExpr("last_online", "?"),
  482. ),
  483. deltaUp, deltaDown, cs.Enable, cs.Total, cs.ExpiryTime, cs.Reset,
  484. cs.LastOnline, cs.Email,
  485. ).Error; err != nil {
  486. return false, err
  487. }
  488. if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, cs.Up, cs.Down); err != nil {
  489. return false, err
  490. }
  491. nodeBaselines[cs.Email] = nodeTrafficCounter{Up: cs.Up, Down: cs.Down}
  492. }
  493. for k, existing := range centralCS {
  494. if dirty {
  495. continue
  496. }
  497. if k.inboundID != c.Id {
  498. continue
  499. }
  500. if _, kept := snapEmails[k.email]; kept {
  501. continue
  502. }
  503. if err := tx.Where("node_id = ? AND email = ?", nodeID, existing.Email).
  504. Delete(&model.NodeClientTraffic{}).Error; err != nil {
  505. return false, err
  506. }
  507. // Same shared-accumulator rule as the inbound-removal sweep above:
  508. // keep the row while another inbound still references the email.
  509. stillUsed, uErr := s.emailUsedByOtherInbounds(existing.Email, c.Id)
  510. if uErr != nil {
  511. return false, uErr
  512. }
  513. if !stillUsed {
  514. if err := tx.Where("inbound_id = ? AND email = ?", c.Id, existing.Email).
  515. Delete(&xray.ClientTraffic{}).Error; err != nil {
  516. return false, err
  517. }
  518. }
  519. structuralChange = true
  520. }
  521. }
  522. type oldSet struct {
  523. inboundID int
  524. emails map[string]struct{}
  525. }
  526. var perInboundOld []oldSet
  527. for _, snapIb := range snap.Inbounds {
  528. if snapIb == nil {
  529. continue
  530. }
  531. c, ok := tagToCentral[snapIb.Tag]
  532. if !ok {
  533. continue
  534. }
  535. if dirty {
  536. continue
  537. }
  538. var oldEmailsRows []string
  539. if err := tx.Table("clients").
  540. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  541. Where("client_inbounds.inbound_id = ?", c.Id).
  542. Pluck("email", &oldEmailsRows).Error; err == nil {
  543. oldEmails := make(map[string]struct{}, len(oldEmailsRows))
  544. for _, e := range oldEmailsRows {
  545. if e != "" {
  546. oldEmails[e] = struct{}{}
  547. }
  548. }
  549. perInboundOld = append(perInboundOld, oldSet{inboundID: c.Id, emails: oldEmails})
  550. }
  551. clients, gcErr := s.GetClients(snapIb)
  552. if gcErr != nil {
  553. logger.Warningf("setRemoteTraffic: parse clients for tag %q failed: %v", snapIb.Tag, gcErr)
  554. continue
  555. }
  556. csEnableByEmail := make(map[string]bool, len(snapIb.ClientStats))
  557. for _, cs := range snapIb.ClientStats {
  558. csEnableByEmail[cs.Email] = cs.Enable
  559. }
  560. filtered := clients[:0]
  561. for i := range clients {
  562. if isClientEmailTombstoned(clients[i].Email) {
  563. continue
  564. }
  565. if cse, hit := csEnableByEmail[clients[i].Email]; hit && !cse {
  566. clients[i].Enable = false
  567. }
  568. filtered = append(filtered, clients[i])
  569. }
  570. localEmails := make([]string, 0, len(filtered))
  571. for i := range filtered {
  572. if filtered[i].Email != "" {
  573. localEmails = append(localEmails, filtered[i].Email)
  574. }
  575. }
  576. if len(localEmails) > 0 {
  577. var localMeta []struct {
  578. Email string
  579. Comment string `gorm:"column:comment"`
  580. }
  581. if err := tx.Table("clients").
  582. Select("email, comment").
  583. Where("email IN ?", localEmails).
  584. Find(&localMeta).Error; err == nil {
  585. commentByEmail := make(map[string]string, len(localMeta))
  586. for _, m := range localMeta {
  587. commentByEmail[m.Email] = m.Comment
  588. }
  589. for i := range filtered {
  590. if cmt, ok := commentByEmail[filtered[i].Email]; ok {
  591. filtered[i].Comment = cmt
  592. }
  593. }
  594. }
  595. }
  596. if err := s.clientService.SyncInbound(tx, c.Id, filtered); err != nil {
  597. logger.Warningf("setRemoteTraffic: sync clients for tag %q failed: %v", snapIb.Tag, err)
  598. }
  599. }
  600. for _, old := range perInboundOld {
  601. var stillAttached []string
  602. if err := tx.Table("clients").
  603. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  604. Where("client_inbounds.inbound_id = ?", old.inboundID).
  605. Pluck("email", &stillAttached).Error; err != nil {
  606. continue
  607. }
  608. stillSet := make(map[string]struct{}, len(stillAttached))
  609. for _, e := range stillAttached {
  610. stillSet[e] = struct{}{}
  611. }
  612. for email := range old.emails {
  613. if _, kept := stillSet[email]; kept {
  614. continue
  615. }
  616. var attachmentCount int64
  617. if err := tx.Table("client_inbounds").
  618. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  619. Where("clients.email = ?", email).
  620. Count(&attachmentCount).Error; err != nil {
  621. continue
  622. }
  623. if attachmentCount > 0 {
  624. continue
  625. }
  626. if err := tx.Where("email = ?", email).Delete(&model.ClientRecord{}).Error; err != nil {
  627. logger.Warningf("setRemoteTraffic: delete ClientRecord %q failed: %v", email, err)
  628. }
  629. if err := tx.Where("email = ?", email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  630. logger.Warningf("setRemoteTraffic: delete ClientTraffic %q failed: %v", email, err)
  631. }
  632. if err := tx.Where("email = ?", email).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  633. logger.Warningf("setRemoteTraffic: delete NodeClientTraffic %q failed: %v", email, err)
  634. }
  635. structuralChange = true
  636. }
  637. }
  638. if err := tx.Commit().Error; err != nil {
  639. return false, err
  640. }
  641. committed = true
  642. if p != nil {
  643. tree := snap.OnlineTree
  644. if len(tree) == 0 && len(snap.OnlineEmails) > 0 {
  645. // Old-build node (no GUID tree): key its flat online list under its
  646. // own effective identity so attribution still works for that branch.
  647. effectiveGuid := nodeRow.Guid
  648. if effectiveGuid == "" {
  649. effectiveGuid = synthNodeGuid(nodeID)
  650. }
  651. tree = map[string][]string{effectiveGuid: snap.OnlineEmails}
  652. }
  653. p.SetNodeOnlineTree(nodeID, tree)
  654. }
  655. return structuralChange, nil
  656. }
  657. func (s *InboundService) restartRemoteNodesOnDisable(nodeIDs []int) {
  658. restartOnDisable, err := (&SettingService{}).GetRestartXrayOnClientDisable()
  659. if err != nil {
  660. logger.Warning("disableInvalidClients: get RestartXrayOnClientDisable failed:", err)
  661. return
  662. }
  663. if !restartOnDisable {
  664. return
  665. }
  666. for _, nodeID := range nodeIDs {
  667. nodeIDCopy := nodeID
  668. rt, rtErr := runtime.GetManager().RuntimeFor(&nodeIDCopy)
  669. if rtErr != nil {
  670. logger.Warning("disableInvalidClients: get runtime for node", nodeID, "failed:", rtErr)
  671. continue
  672. }
  673. if rtErr = rt.RestartXray(context.Background()); rtErr != nil {
  674. logger.Warning("disableInvalidClients: restart xray on node", nodeID, "failed:", rtErr)
  675. }
  676. }
  677. }
  678. func (s *InboundService) GetOnlineClients() []string {
  679. if p == nil {
  680. return []string{}
  681. }
  682. return p.GetOnlineClients()
  683. }
  684. // GetOnlineClientsByGuid returns online emails keyed by the panelGuid of the
  685. // node that physically hosts each set: this panel's own clients under its own
  686. // GUID, plus every node in the tree under its GUID (#4983). Replaces the old
  687. // node-id keying so a client three hops down is attributed to its real node,
  688. // not the intermediate one it was synced through.
  689. func (s *InboundService) GetOnlineClientsByGuid() map[string][]string {
  690. if p == nil {
  691. return map[string][]string{}
  692. }
  693. out := p.GetMergedNodeTrees()
  694. if local := p.GetLocalOnlineClients(); len(local) > 0 {
  695. if guid := s.panelGuid(); guid != "" {
  696. out[guid] = mergeEmails(out[guid], local)
  697. }
  698. }
  699. return out
  700. }
  701. // GetActiveInboundsByGuid returns the inbound tags that carried traffic within
  702. // the grace window for THIS panel, under its own GUID. Remote nodes don't
  703. // report per-inbound activity, so a GUID missing from the map means "don't
  704. // gate" for that node's inbounds.
  705. func (s *InboundService) GetActiveInboundsByGuid() map[string][]string {
  706. if p == nil {
  707. return map[string][]string{}
  708. }
  709. active := p.GetLocalActiveInbounds()
  710. if len(active) == 0 {
  711. return map[string][]string{}
  712. }
  713. guid := s.panelGuid()
  714. if guid == "" {
  715. return map[string][]string{}
  716. }
  717. return map[string][]string{guid: active}
  718. }
  719. func (s *InboundService) SetNodeOnlineTree(nodeID int, tree map[string][]string) {
  720. if p != nil {
  721. p.SetNodeOnlineTree(nodeID, tree)
  722. }
  723. }
  724. func (s *InboundService) ClearNodeOnlineClients(nodeID int) {
  725. if p != nil {
  726. p.ClearNodeOnlineClients(nodeID)
  727. }
  728. }
  729. // panelGuid returns this panel's stable self-identifier, used to key the local
  730. // panel's own clients in the per-node online maps (#4983).
  731. func (s *InboundService) panelGuid() string {
  732. guid, _ := (&SettingService{}).GetPanelGuid()
  733. return guid
  734. }
  735. // synthNodeGuid is the stable per-node fallback identity for a directly-attached
  736. // node whose panel hasn't reported a panelGuid yet (old build). Node ids are
  737. // master-local, so this only composes for direct nodes — exactly the pre-#4983
  738. // flat-topology case where an old-build node appears.
  739. func synthNodeGuid(nodeID int) string {
  740. return fmt.Sprintf("node:%d", nodeID)
  741. }
  742. // mergeEmails returns the deduped union of two email slices.
  743. func mergeEmails(a, b []string) []string {
  744. if len(a) == 0 {
  745. return b
  746. }
  747. seen := make(map[string]struct{}, len(a)+len(b))
  748. out := make([]string, 0, len(a)+len(b))
  749. for _, e := range a {
  750. if _, ok := seen[e]; !ok {
  751. seen[e] = struct{}{}
  752. out = append(out, e)
  753. }
  754. }
  755. for _, e := range b {
  756. if _, ok := seen[e]; !ok {
  757. seen[e] = struct{}{}
  758. out = append(out, e)
  759. }
  760. }
  761. return out
  762. }
  763. func (s *InboundService) GetClientsLastOnline() (map[string]int64, error) {
  764. db := database.GetDB()
  765. var rows []xray.ClientTraffic
  766. err := db.Model(&xray.ClientTraffic{}).Select("email, last_online").Find(&rows).Error
  767. if err != nil && err != gorm.ErrRecordNotFound {
  768. return nil, err
  769. }
  770. result := make(map[string]int64, len(rows))
  771. for _, r := range rows {
  772. result[r.Email] = r.LastOnline
  773. }
  774. return result, nil
  775. }
  776. // RefreshLocalOnlineClients folds the emails and inbound tags active on this
  777. // panel's own xray this poll into the local online/active sets, applying the
  778. // grace window and pruning stale entries. Pass nil to only prune. See
  779. // xray.Process for why the local sets are kept separate from the shared
  780. // last_online column.
  781. func (s *InboundService) RefreshLocalOnlineClients(activeEmails, activeInboundTags []string) {
  782. if p != nil {
  783. p.RefreshLocalOnline(activeEmails, activeInboundTags, time.Now().UnixMilli(), onlineGracePeriodMs)
  784. }
  785. }
  786. func (s *InboundService) FilterAndSortClientEmails(emails []string) ([]string, []string, error) {
  787. db := database.GetDB()
  788. // Step 1: Get ClientTraffic records for emails in the input list.
  789. // Chunked to stay under SQLite's bind-variable limit on huge inputs.
  790. uniqEmails := uniqueNonEmptyStrings(emails)
  791. clients := make([]xray.ClientTraffic, 0, len(uniqEmails))
  792. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  793. var page []xray.ClientTraffic
  794. if err := db.Where("email IN ?", batch).Find(&page).Error; err != nil && err != gorm.ErrRecordNotFound {
  795. return nil, nil, err
  796. }
  797. clients = append(clients, page...)
  798. }
  799. // Step 2: Sort clients by (Up + Down) descending
  800. sort.Slice(clients, func(i, j int) bool {
  801. return (clients[i].Up + clients[i].Down) > (clients[j].Up + clients[j].Down)
  802. })
  803. // Step 3: Extract sorted valid emails and track found ones
  804. validEmails := make([]string, 0, len(clients))
  805. found := make(map[string]bool)
  806. for _, client := range clients {
  807. validEmails = append(validEmails, client.Email)
  808. found[client.Email] = true
  809. }
  810. // Step 4: Identify emails that were not found in the database
  811. extraEmails := make([]string, 0)
  812. for _, email := range emails {
  813. if !found[email] {
  814. extraEmails = append(extraEmails, email)
  815. }
  816. }
  817. return validEmails, extraEmails, nil
  818. }