1
0

inbound_node.go 26 KB

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