1
0

inbound_node.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005
  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. // nodeBulkPushThreshold caps how many per-client RPCs a single operation will
  20. // stream to a remote node. Above it, the panel marks the node dirty instead and
  21. // lets one ReconcileNode push converge the whole inbound — far cheaper than M
  22. // sequential round-trips. Small ops stay on the live per-client path.
  23. const nodeBulkPushThreshold = 32
  24. func (s *InboundService) runtimeFor(ib *model.Inbound) (runtime.Runtime, error) {
  25. mgr := runtime.GetManager()
  26. if mgr == nil {
  27. return nil, fmt.Errorf("runtime manager not initialised")
  28. }
  29. return mgr.RuntimeFor(ib.NodeID)
  30. }
  31. func (s *InboundService) nodePushPlan(ib *model.Inbound) (runtime.Runtime, bool, bool, error) {
  32. if ib.NodeID == nil {
  33. rt, err := s.runtimeFor(ib)
  34. if err != nil {
  35. return nil, false, false, nil
  36. }
  37. return rt, true, false, nil
  38. }
  39. nodeSvc := NodeService{}
  40. enabled, status, _, _, err := nodeSvc.NodeSyncState(*ib.NodeID)
  41. if err != nil {
  42. return nil, false, false, err
  43. }
  44. if !enabled || status == "offline" {
  45. return nil, false, true, nil
  46. }
  47. rt, err := s.runtimeFor(ib)
  48. if err != nil {
  49. return nil, false, true, nil
  50. }
  51. return rt, true, false, nil
  52. }
  53. func (s *InboundService) NodeIsPending(nodeID *int) bool {
  54. if nodeID == nil {
  55. return false
  56. }
  57. return (&NodeService{}).IsNodePending(*nodeID)
  58. }
  59. func (s *InboundService) AnyNodePending(inboundIds []int) bool {
  60. if len(inboundIds) == 0 {
  61. return false
  62. }
  63. nodeSvc := NodeService{}
  64. for _, id := range inboundIds {
  65. ib, err := s.GetInbound(id)
  66. if err != nil || ib.NodeID == nil {
  67. continue
  68. }
  69. if nodeSvc.IsNodePending(*ib.NodeID) {
  70. return true
  71. }
  72. }
  73. return false
  74. }
  75. func (s *InboundService) ReconcileNode(ctx context.Context, rt *runtime.Remote, n *model.Node) error {
  76. if rt == nil || n == nil || n.Id <= 0 {
  77. return nil
  78. }
  79. nodeID := n.Id
  80. db := database.GetDB()
  81. var inbounds []*model.Inbound
  82. if err := db.Model(model.Inbound{}).Where("node_id = ?", nodeID).Find(&inbounds).Error; err != nil {
  83. return err
  84. }
  85. remoteTags, err := rt.ListRemoteTags(ctx)
  86. if err != nil {
  87. return err
  88. }
  89. remoteTagSet := make(map[string]struct{}, len(remoteTags))
  90. for _, tag := range remoteTags {
  91. remoteTagSet[tag] = struct{}{}
  92. }
  93. prefix := nodeTagPrefix(&nodeID)
  94. desiredTags := make(map[string]struct{}, len(inbounds)*2)
  95. for _, ib := range inbounds {
  96. desiredTags[ib.Tag] = struct{}{}
  97. // existsOnNode: does the node already report this inbound under any of the
  98. // tag forms it may be stored as? If so, an unchanged push can be skipped.
  99. _, existsOnNode := remoteTagSet[ib.Tag]
  100. if prefix != "" {
  101. if stripped, found := strings.CutPrefix(ib.Tag, prefix); found {
  102. desiredTags[stripped] = struct{}{}
  103. if _, ok := remoteTagSet[stripped]; ok {
  104. existsOnNode = true
  105. }
  106. } else {
  107. desiredTags[prefix+ib.Tag] = struct{}{}
  108. if _, ok := remoteTagSet[prefix+ib.Tag]; ok {
  109. existsOnNode = true
  110. }
  111. }
  112. }
  113. if _, err := rt.ReconcileInbound(ctx, ib, existsOnNode); err != nil {
  114. return fmt.Errorf("reconcile inbound %q: %w", ib.Tag, err)
  115. }
  116. }
  117. // In "selected" sync mode the panel only manages the selected tags: the
  118. // rest were never imported, so their absence from the local DB must not
  119. // delete them from the node. Only a selected tag missing locally (the
  120. // panel deleted it while the node was unreachable) may be swept.
  121. var selected map[string]struct{}
  122. if n.InboundSyncMode == "selected" {
  123. selected = make(map[string]struct{}, len(n.InboundTags))
  124. for _, tag := range n.InboundTags {
  125. selected[tag] = struct{}{}
  126. }
  127. }
  128. for _, tag := range remoteTags {
  129. if _, want := desiredTags[tag]; want {
  130. continue
  131. }
  132. if selected != nil {
  133. if _, managed := selected[tag]; !managed {
  134. continue
  135. }
  136. }
  137. if err := rt.DelInbound(ctx, &model.Inbound{Tag: tag}); err != nil {
  138. return fmt.Errorf("reconcile delete %q: %w", tag, err)
  139. }
  140. }
  141. return nil
  142. }
  143. const resetGracePeriodMs int64 = 30000
  144. // onlineGracePeriodMs must comfortably exceed the 5s traffic-poll interval —
  145. // Xray's stats counters often report a zero delta for an active session across
  146. // a single poll, so a 5s grace would still drop the client on the next tick.
  147. // ~4 polls of slack keeps idle-but-connected clients visible without lingering
  148. // long after a real disconnect.
  149. const onlineGracePeriodMs int64 = 20000
  150. type nodeTrafficCounter struct {
  151. Up int64
  152. Down int64
  153. }
  154. func (s *InboundService) upsertNodeBaseline(tx *gorm.DB, nodeID int, email string, up, down int64) error {
  155. return tx.Clauses(clause.OnConflict{
  156. Columns: []clause.Column{{Name: "node_id"}, {Name: "email"}},
  157. DoUpdates: clause.AssignmentColumns([]string{"up", "down"}),
  158. }).Create(&model.NodeClientTraffic{NodeId: nodeID, Email: email, Up: up, Down: down}).Error
  159. }
  160. // mergeActivationExpiry reconciles a node-reported client expiry with the value
  161. // already stored on the master. "Start after first connect" persists a negative
  162. // duration that each node converts to an absolute deadline (now+duration) the
  163. // first time the client connects there. The per-email client_traffics row is
  164. // shared across every node, so a node that has not yet seen a first connection
  165. // keeps reporting the negative duration — which must never reset a deadline
  166. // another node already activated.
  167. //
  168. // A node may legitimately move an already-activated deadline forward (traffic
  169. // reset / auto-renew extends it), so any positive node value is still adopted —
  170. // only an un-activated (<= 0) value is rejected once an absolute deadline
  171. // exists. Kept in lockstep with the SQL CASE in setRemoteTrafficLocked.
  172. func mergeActivationExpiry(existing, node int64) int64 {
  173. if existing > 0 && node <= 0 {
  174. return existing
  175. }
  176. return node
  177. }
  178. func (s *InboundService) SetRemoteTraffic(nodeID int, snap *runtime.TrafficSnapshot, dirty bool) (bool, error) {
  179. var structuralChange bool
  180. err := submitTrafficWrite(func() error {
  181. var inner error
  182. structuralChange, inner = s.setRemoteTrafficLocked(nodeID, snap, dirty)
  183. return inner
  184. })
  185. return structuralChange, err
  186. }
  187. func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.TrafficSnapshot, dirty bool) (bool, error) {
  188. if snap == nil || nodeID <= 0 {
  189. return false, nil
  190. }
  191. db := database.GetDB()
  192. now := time.Now().UnixMilli()
  193. // originGuidFor attributes a synced inbound to the panel that physically
  194. // hosts it: inbounds the node forwards from its own sub-nodes already carry
  195. // a non-empty OriginNodeGuid (kept as-is across hops); the node's own local
  196. // inbounds report empty, so they are attributed to the node's own GUID. An
  197. // empty result (old-build node with no GUID yet) leaves attribution to the
  198. // node_id fallback downstream (#4983).
  199. var nodeRow model.Node
  200. db.Select("guid").Where("id = ?", nodeID).First(&nodeRow)
  201. originGuidFor := func(snapIb *model.Inbound) string {
  202. if snapIb.OriginNodeGuid != "" {
  203. return snapIb.OriginNodeGuid
  204. }
  205. return nodeRow.Guid
  206. }
  207. var central []model.Inbound
  208. if err := db.Model(model.Inbound{}).
  209. Where("node_id = ?", nodeID).
  210. Find(&central).Error; err != nil {
  211. return false, err
  212. }
  213. // Index under the stored tag and its prefix-flipped form so a snap matches
  214. // whether the n<id>- prefix lives on the node side, the central side, or
  215. // neither — a mismatch must never spawn a duplicate central inbound.
  216. tagToCentral := make(map[string]*model.Inbound, len(central)*2)
  217. prefix := nodeTagPrefix(&nodeID)
  218. for i := range central {
  219. tagToCentral[central[i].Tag] = &central[i]
  220. if prefix != "" {
  221. if stripped, found := strings.CutPrefix(central[i].Tag, prefix); found {
  222. tagToCentral[stripped] = &central[i]
  223. } else {
  224. tagToCentral[prefix+central[i].Tag] = &central[i]
  225. }
  226. }
  227. }
  228. var centralClientStats []xray.ClientTraffic
  229. if len(central) > 0 {
  230. ids := make([]int, 0, len(central))
  231. for i := range central {
  232. ids = append(ids, central[i].Id)
  233. }
  234. if err := db.Model(xray.ClientTraffic{}).
  235. Where("inbound_id IN ?", ids).
  236. Find(&centralClientStats).Error; err != nil {
  237. return false, err
  238. }
  239. }
  240. type csKey struct {
  241. inboundID int
  242. email string
  243. }
  244. centralCS := make(map[csKey]*xray.ClientTraffic, len(centralClientStats))
  245. centralCSByEmail := make(map[string]*xray.ClientTraffic, len(centralClientStats))
  246. for i := range centralClientStats {
  247. centralCS[csKey{centralClientStats[i].InboundId, centralClientStats[i].Email}] = &centralClientStats[i]
  248. centralCSByEmail[centralClientStats[i].Email] = &centralClientStats[i]
  249. }
  250. nodeBaselines := make(map[string]nodeTrafficCounter)
  251. var baselineRows []model.NodeClientTraffic
  252. if err := db.Model(&model.NodeClientTraffic{}).
  253. Where("node_id = ?", nodeID).
  254. Find(&baselineRows).Error; err != nil {
  255. return false, err
  256. }
  257. for i := range baselineRows {
  258. nodeBaselines[baselineRows[i].Email] = nodeTrafficCounter{Up: baselineRows[i].Up, Down: baselineRows[i].Down}
  259. }
  260. var defaultUserId int
  261. if len(central) > 0 {
  262. defaultUserId = central[0].UserId
  263. } else {
  264. var u model.User
  265. if err := db.Model(model.User{}).Order("id asc").First(&u).Error; err == nil {
  266. defaultUserId = u.Id
  267. } else {
  268. defaultUserId = 1
  269. }
  270. }
  271. // Union of every email the snapshot still reports, across all inbounds.
  272. // The (node, email) baseline rows are keyed per node, not per inbound, so
  273. // the sweeps below must only drop one when the email left the node
  274. // entirely — an email whose stats moved to (or always lived under) a
  275. // sibling inbound still needs its baseline for the sibling's delta
  276. // computation (#5202).
  277. //
  278. // Xray counts traffic per email, not per inbound, so a multi-attached
  279. // client's shared counter is copied onto every inbound it's on. Fold each
  280. // email to its per-field max (nodeEmailTotals) so divergent copies can't make
  281. // the reset clamp re-add a lower sibling as fresh traffic (#5274).
  282. snapEmailsAll := make(map[string]struct{})
  283. nodeEmailTotals := make(map[string]nodeTrafficCounter)
  284. for _, snapIb := range snap.Inbounds {
  285. if snapIb == nil {
  286. continue
  287. }
  288. for i := range snapIb.ClientStats {
  289. email := snapIb.ClientStats[i].Email
  290. snapEmailsAll[email] = struct{}{}
  291. cur := nodeEmailTotals[email]
  292. if snapIb.ClientStats[i].Up > cur.Up {
  293. cur.Up = snapIb.ClientStats[i].Up
  294. }
  295. if snapIb.ClientStats[i].Down > cur.Down {
  296. cur.Down = snapIb.ClientStats[i].Down
  297. }
  298. nodeEmailTotals[email] = cur
  299. }
  300. }
  301. // Membership set for the rowExists checks below. Only the snapshot's emails
  302. // are ever probed, so scope the lookup to those instead of plucking the whole
  303. // client_traffics table (50k+ rows) on every node poll.
  304. existingEmails := make(map[string]struct{}, len(snapEmailsAll))
  305. if len(snapEmailsAll) > 0 {
  306. snapEmailList := make([]string, 0, len(snapEmailsAll))
  307. for email := range snapEmailsAll {
  308. snapEmailList = append(snapEmailList, email)
  309. }
  310. for _, batch := range chunkStrings(snapEmailList, sqliteMaxVars) {
  311. var found []string
  312. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Pluck("email", &found).Error; err != nil {
  313. return false, err
  314. }
  315. for _, e := range found {
  316. existingEmails[e] = struct{}{}
  317. }
  318. }
  319. }
  320. tx := db.Begin()
  321. committed := false
  322. defer func() {
  323. if !committed {
  324. tx.Rollback()
  325. }
  326. }()
  327. structuralChange := false
  328. snapTags := make(map[string]struct{}, len(snap.Inbounds))
  329. for _, snapIb := range snap.Inbounds {
  330. if snapIb == nil {
  331. continue
  332. }
  333. snapTags[snapIb.Tag] = struct{}{}
  334. // Record the prefix-flipped form too so the orphan sweep below keeps a
  335. // central inbound whether its tag carries the n<id>- prefix or not.
  336. if prefix != "" {
  337. if stripped, found := strings.CutPrefix(snapIb.Tag, prefix); found {
  338. snapTags[stripped] = struct{}{}
  339. } else {
  340. snapTags[prefix+snapIb.Tag] = struct{}{}
  341. }
  342. }
  343. c, ok := tagToCentral[snapIb.Tag]
  344. if !ok {
  345. if dirty {
  346. continue
  347. }
  348. // Try snap.Tag first; on collision fall back to the n<id>-
  349. // prefixed form so local+node can both own the same port.
  350. pickFreeTag := func() (string, error) {
  351. candidates := []string{snapIb.Tag}
  352. if prefix != "" && !strings.HasPrefix(snapIb.Tag, prefix) {
  353. candidates = append(candidates, prefix+snapIb.Tag)
  354. }
  355. for _, t := range candidates {
  356. var owner model.Inbound
  357. err := tx.Where("tag = ?", t).First(&owner).Error
  358. if errors.Is(err, gorm.ErrRecordNotFound) {
  359. return t, nil
  360. }
  361. if err != nil {
  362. return "", err
  363. }
  364. }
  365. return "", nil
  366. }
  367. chosenTag, err := pickFreeTag()
  368. if err != nil {
  369. logger.Warningf("setRemoteTraffic: check tag %q failed: %v", snapIb.Tag, err)
  370. continue
  371. }
  372. if chosenTag == "" {
  373. key := fmt.Sprintf("%d:%s", nodeID, snapIb.Tag)
  374. if _, seen := reportedRemoteTagConflict.LoadOrStore(key, struct{}{}); !seen {
  375. logger.Warningf(
  376. "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)",
  377. snapIb.Tag, nodeID, nodeID,
  378. )
  379. }
  380. continue
  381. }
  382. reportedRemoteTagConflict.Delete(fmt.Sprintf("%d:%s", nodeID, snapIb.Tag))
  383. newIb := model.Inbound{
  384. UserId: defaultUserId,
  385. NodeID: &nodeID,
  386. OriginNodeGuid: originGuidFor(snapIb),
  387. Tag: chosenTag,
  388. Listen: snapIb.Listen,
  389. Port: snapIb.Port,
  390. Protocol: snapIb.Protocol,
  391. Settings: snapIb.Settings,
  392. StreamSettings: snapIb.StreamSettings,
  393. Sniffing: snapIb.Sniffing,
  394. TrafficReset: snapIb.TrafficReset,
  395. LastTrafficResetTime: snapIb.LastTrafficResetTime,
  396. Enable: snapIb.Enable,
  397. Remark: snapIb.Remark,
  398. SubSortIndex: normalizeSubSortIndex(snapIb.SubSortIndex),
  399. Total: snapIb.Total,
  400. ExpiryTime: snapIb.ExpiryTime,
  401. Up: snapIb.Up,
  402. Down: snapIb.Down,
  403. ShareAddrStrategy: "node",
  404. }
  405. if err := tx.Create(&newIb).Error; err != nil {
  406. logger.Warningf("setRemoteTraffic: create central inbound for tag %q failed: %v", snapIb.Tag, err)
  407. continue
  408. }
  409. tagToCentral[snapIb.Tag] = &newIb
  410. if newIb.Tag != snapIb.Tag {
  411. tagToCentral[newIb.Tag] = &newIb
  412. }
  413. structuralChange = true
  414. continue
  415. }
  416. inGrace := c.LastTrafficResetTime > 0 && now-c.LastTrafficResetTime < resetGracePeriodMs
  417. updates := map[string]any{}
  418. if !dirty {
  419. updates["enable"] = snapIb.Enable
  420. updates["remark"] = snapIb.Remark
  421. updates["sub_sort_index"] = normalizeSubSortIndex(snapIb.SubSortIndex)
  422. updates["listen"] = snapIb.Listen
  423. updates["port"] = snapIb.Port
  424. updates["protocol"] = snapIb.Protocol
  425. updates["total"] = snapIb.Total
  426. updates["expiry_time"] = snapIb.ExpiryTime
  427. updates["settings"] = snapIb.Settings
  428. updates["stream_settings"] = snapIb.StreamSettings
  429. updates["sniffing"] = snapIb.Sniffing
  430. updates["traffic_reset"] = snapIb.TrafficReset
  431. updates["last_traffic_reset_time"] = snapIb.LastTrafficResetTime
  432. }
  433. if !inGrace || (snapIb.Up+snapIb.Down) <= (c.Up+c.Down) {
  434. updates["up"] = snapIb.Up
  435. updates["down"] = snapIb.Down
  436. }
  437. // Physical-home attribution is independent of config-dirty state, so
  438. // keep it current even while the node has pending offline edits. Writes
  439. // once to backfill an existing row, then stays equal (#4983).
  440. if og := originGuidFor(snapIb); c.OriginNodeGuid != og {
  441. updates["origin_node_guid"] = og
  442. }
  443. if !dirty && (c.Settings != snapIb.Settings ||
  444. c.Remark != snapIb.Remark ||
  445. c.Listen != snapIb.Listen ||
  446. c.Port != snapIb.Port ||
  447. c.Total != snapIb.Total ||
  448. c.ExpiryTime != snapIb.ExpiryTime ||
  449. c.Enable != snapIb.Enable) {
  450. structuralChange = true
  451. }
  452. if len(updates) > 0 {
  453. if err := tx.Model(model.Inbound{}).
  454. Where("id = ?", c.Id).
  455. Updates(updates).Error; err != nil {
  456. return false, err
  457. }
  458. }
  459. }
  460. for _, c := range central {
  461. if dirty {
  462. continue
  463. }
  464. if _, kept := snapTags[c.Tag]; kept {
  465. continue
  466. }
  467. var goneEmails []string
  468. if err := tx.Model(xray.ClientTraffic{}).
  469. Where("inbound_id = ?", c.Id).
  470. Pluck("email", &goneEmails).Error; err != nil {
  471. return false, err
  472. }
  473. if len(goneEmails) > 0 {
  474. // Baselines are per (node, email), not per inbound: keep them for
  475. // emails the snapshot still reports under a sibling inbound (#5202).
  476. baselineGone := make([]string, 0, len(goneEmails))
  477. for _, e := range goneEmails {
  478. if _, still := snapEmailsAll[e]; !still {
  479. baselineGone = append(baselineGone, e)
  480. }
  481. }
  482. // Chunk to avoid SQLite bind var limit when a node has many clients
  483. // removed (e.g. after API bulk delete or structural change on node inbound).
  484. for _, batch := range chunkStrings(baselineGone, sqliteMaxVars) {
  485. if err := tx.Where("node_id = ? AND email IN ?", nodeID, batch).
  486. Delete(&model.NodeClientTraffic{}).Error; err != nil {
  487. return false, err
  488. }
  489. }
  490. // The per-email row is the shared accumulator across every inbound
  491. // (and node) the email is attached to. Only drop it when this was the
  492. // email's last inbound — wiping it while a sibling still feeds it
  493. // loses the summed history, and the next node sync would re-seed the
  494. // row with that node's counter alone.
  495. sharedEmails, sErr := s.emailsUsedByOtherInbounds(goneEmails, c.Id)
  496. if sErr != nil {
  497. return false, sErr
  498. }
  499. delEmails := make([]string, 0, len(goneEmails))
  500. for _, e := range goneEmails {
  501. if !sharedEmails[strings.ToLower(strings.TrimSpace(e))] {
  502. delEmails = append(delEmails, e)
  503. }
  504. }
  505. for _, batch := range chunkStrings(delEmails, sqliteMaxVars) {
  506. if err := tx.Where("inbound_id = ? AND email IN ?", c.Id, batch).
  507. Delete(&xray.ClientTraffic{}).Error; err != nil {
  508. return false, err
  509. }
  510. }
  511. }
  512. if err := s.clientService.DetachInbound(tx, c.Id); err != nil {
  513. return false, err
  514. }
  515. if err := tx.Where("id = ?", c.Id).
  516. Delete(&model.Inbound{}).Error; err != nil {
  517. return false, err
  518. }
  519. delete(tagToCentral, c.Tag)
  520. structuralChange = true
  521. }
  522. for _, snapIb := range snap.Inbounds {
  523. if snapIb == nil {
  524. continue
  525. }
  526. c, ok := tagToCentral[snapIb.Tag]
  527. if !ok {
  528. continue
  529. }
  530. snapEmails := make(map[string]struct{}, len(snapIb.ClientStats))
  531. for _, cs := range snapIb.ClientStats {
  532. snapEmails[cs.Email] = struct{}{}
  533. // Node-wide total, not this inbound's possibly-stale copy (#5274).
  534. canon := nodeEmailTotals[cs.Email]
  535. base, seen := nodeBaselines[cs.Email]
  536. var deltaUp, deltaDown int64
  537. if seen {
  538. if deltaUp = canon.Up - base.Up; deltaUp < 0 {
  539. deltaUp = 0
  540. }
  541. if deltaDown = canon.Down - base.Down; deltaDown < 0 {
  542. deltaDown = 0
  543. }
  544. }
  545. if _, rowExists := existingEmails[cs.Email]; !rowExists {
  546. if dirty {
  547. continue
  548. }
  549. row := &xray.ClientTraffic{
  550. InboundId: c.Id,
  551. Email: cs.Email,
  552. Enable: cs.Enable,
  553. Total: cs.Total,
  554. ExpiryTime: cs.ExpiryTime,
  555. Reset: cs.Reset,
  556. Up: 0,
  557. Down: 0,
  558. LastOnline: cs.LastOnline,
  559. }
  560. if err := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "email"}}, DoNothing: true}).
  561. Create(row).Error; err != nil {
  562. return false, err
  563. }
  564. centralCS[csKey{c.Id, cs.Email}] = row
  565. centralCSByEmail[cs.Email] = row
  566. existingEmails[cs.Email] = struct{}{}
  567. structuralChange = true
  568. if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon.Up, canon.Down); err != nil {
  569. return false, err
  570. }
  571. nodeBaselines[cs.Email] = nodeTrafficCounter{Up: canon.Up, Down: canon.Down}
  572. continue
  573. }
  574. if existing := centralCSByEmail[cs.Email]; existing != nil &&
  575. (existing.Enable != cs.Enable ||
  576. existing.Total != cs.Total ||
  577. existing.ExpiryTime != mergeActivationExpiry(existing.ExpiryTime, cs.ExpiryTime) ||
  578. existing.Reset != cs.Reset) {
  579. structuralChange = true
  580. }
  581. enableExpr := database.ClientTrafficEnableMergeExpr()
  582. // expiry_time merge mirrors mergeActivationExpiry: a node that has not
  583. // yet seen the client's first connection keeps reporting the negative
  584. // "start after first connect" duration, which must never reset the
  585. // absolute deadline another node already activated. A positive node
  586. // value is still adopted (e.g. auto-renew moves the deadline forward).
  587. // CAST(? AS BIGINT): in the `<= 0` comparison Postgres would otherwise
  588. // infer int4 from the literal and overflow on real expiry values.
  589. if err := tx.Exec(
  590. fmt.Sprintf(
  591. `UPDATE client_traffics
  592. SET up = up + ?, down = down + ?, enable = %s, total = ?,
  593. expiry_time = CASE WHEN expiry_time > 0 AND CAST(? AS BIGINT) <= 0 THEN expiry_time ELSE CAST(? AS BIGINT) END,
  594. reset = ?, last_online = %s
  595. WHERE email = ?`,
  596. enableExpr,
  597. database.GreatestExpr("last_online", "?"),
  598. ),
  599. deltaUp, deltaDown, cs.Enable, cs.Total,
  600. cs.ExpiryTime, cs.ExpiryTime, cs.Reset,
  601. cs.LastOnline, cs.Email,
  602. ).Error; err != nil {
  603. return false, err
  604. }
  605. if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon.Up, canon.Down); err != nil {
  606. return false, err
  607. }
  608. nodeBaselines[cs.Email] = nodeTrafficCounter{Up: canon.Up, Down: canon.Down}
  609. }
  610. for k, existing := range centralCS {
  611. if dirty {
  612. continue
  613. }
  614. if k.inboundID != c.Id {
  615. continue
  616. }
  617. if _, kept := snapEmails[k.email]; kept {
  618. continue
  619. }
  620. // Gone from this inbound's stats but still reported by the node under
  621. // a sibling inbound: both the shared accumulator row and the (node,
  622. // email) baseline must survive, or the sibling's next delta would
  623. // compute against nothing and freeze the counter (#5202).
  624. if _, still := snapEmailsAll[k.email]; still {
  625. continue
  626. }
  627. if err := tx.Where("node_id = ? AND email = ?", nodeID, existing.Email).
  628. Delete(&model.NodeClientTraffic{}).Error; err != nil {
  629. return false, err
  630. }
  631. // Same shared-accumulator rule as the inbound-removal sweep above:
  632. // keep the row while another inbound still references the email.
  633. stillUsed, uErr := s.emailUsedByOtherInbounds(existing.Email, c.Id)
  634. if uErr != nil {
  635. return false, uErr
  636. }
  637. if !stillUsed {
  638. if err := tx.Where("inbound_id = ? AND email = ?", c.Id, existing.Email).
  639. Delete(&xray.ClientTraffic{}).Error; err != nil {
  640. return false, err
  641. }
  642. }
  643. structuralChange = true
  644. }
  645. }
  646. type oldSet struct {
  647. inboundID int
  648. emails map[string]struct{}
  649. }
  650. var perInboundOld []oldSet
  651. for _, snapIb := range snap.Inbounds {
  652. if snapIb == nil {
  653. continue
  654. }
  655. c, ok := tagToCentral[snapIb.Tag]
  656. if !ok {
  657. continue
  658. }
  659. if dirty {
  660. continue
  661. }
  662. var oldEmailsRows []string
  663. if err := tx.Table("clients").
  664. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  665. Where("client_inbounds.inbound_id = ?", c.Id).
  666. Pluck("email", &oldEmailsRows).Error; err == nil {
  667. oldEmails := make(map[string]struct{}, len(oldEmailsRows))
  668. for _, e := range oldEmailsRows {
  669. if e != "" {
  670. oldEmails[e] = struct{}{}
  671. }
  672. }
  673. perInboundOld = append(perInboundOld, oldSet{inboundID: c.Id, emails: oldEmails})
  674. }
  675. clients, gcErr := s.GetClients(snapIb)
  676. if gcErr != nil {
  677. logger.Warningf("setRemoteTraffic: parse clients for tag %q failed: %v", snapIb.Tag, gcErr)
  678. continue
  679. }
  680. csEnableByEmail := make(map[string]bool, len(snapIb.ClientStats))
  681. for _, cs := range snapIb.ClientStats {
  682. csEnableByEmail[cs.Email] = cs.Enable
  683. }
  684. filtered := clients[:0]
  685. for i := range clients {
  686. if isClientEmailTombstoned(clients[i].Email) {
  687. continue
  688. }
  689. if cse, hit := csEnableByEmail[clients[i].Email]; hit && !cse {
  690. clients[i].Enable = false
  691. }
  692. filtered = append(filtered, clients[i])
  693. }
  694. localEmails := make([]string, 0, len(filtered))
  695. for i := range filtered {
  696. if filtered[i].Email != "" {
  697. localEmails = append(localEmails, filtered[i].Email)
  698. }
  699. }
  700. if len(localEmails) > 0 {
  701. var localMeta []struct {
  702. Email string
  703. Comment string `gorm:"column:comment"`
  704. }
  705. if err := tx.Table("clients").
  706. Select("email, comment").
  707. Where("email IN ?", localEmails).
  708. Find(&localMeta).Error; err == nil {
  709. commentByEmail := make(map[string]string, len(localMeta))
  710. for _, m := range localMeta {
  711. commentByEmail[m.Email] = m.Comment
  712. }
  713. for i := range filtered {
  714. if cmt, ok := commentByEmail[filtered[i].Email]; ok {
  715. filtered[i].Comment = cmt
  716. }
  717. }
  718. }
  719. }
  720. if err := s.clientService.SyncInbound(tx, c.Id, filtered); err != nil {
  721. logger.Warningf("setRemoteTraffic: sync clients for tag %q failed: %v", snapIb.Tag, err)
  722. }
  723. }
  724. for _, old := range perInboundOld {
  725. var stillAttached []string
  726. if err := tx.Table("clients").
  727. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  728. Where("client_inbounds.inbound_id = ?", old.inboundID).
  729. Pluck("email", &stillAttached).Error; err != nil {
  730. continue
  731. }
  732. stillSet := make(map[string]struct{}, len(stillAttached))
  733. for _, e := range stillAttached {
  734. stillSet[e] = struct{}{}
  735. }
  736. for email := range old.emails {
  737. if _, kept := stillSet[email]; kept {
  738. continue
  739. }
  740. var attachmentCount int64
  741. if err := tx.Table("client_inbounds").
  742. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  743. Where("clients.email = ?", email).
  744. Count(&attachmentCount).Error; err != nil {
  745. continue
  746. }
  747. if attachmentCount > 0 {
  748. continue
  749. }
  750. if err := tx.Where("email = ?", email).Delete(&model.ClientRecord{}).Error; err != nil {
  751. logger.Warningf("setRemoteTraffic: delete ClientRecord %q failed: %v", email, err)
  752. }
  753. if err := tx.Where("email = ?", email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  754. logger.Warningf("setRemoteTraffic: delete ClientTraffic %q failed: %v", email, err)
  755. }
  756. if err := tx.Where("email = ?", email).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  757. logger.Warningf("setRemoteTraffic: delete NodeClientTraffic %q failed: %v", email, err)
  758. }
  759. structuralChange = true
  760. }
  761. }
  762. if err := tx.Commit().Error; err != nil {
  763. return false, err
  764. }
  765. committed = true
  766. if p != nil {
  767. tree := snap.OnlineTree
  768. if len(tree) == 0 && len(snap.OnlineEmails) > 0 {
  769. // Old-build node (no GUID tree): key its flat online list under its
  770. // own effective identity so attribution still works for that branch.
  771. effectiveGuid := nodeRow.Guid
  772. if effectiveGuid == "" {
  773. effectiveGuid = synthNodeGuid(nodeID)
  774. }
  775. tree = map[string][]string{effectiveGuid: snap.OnlineEmails}
  776. }
  777. p.SetNodeOnlineTree(nodeID, tree)
  778. }
  779. return structuralChange, nil
  780. }
  781. func (s *InboundService) restartRemoteNodesOnDisable(nodeIDs []int) {
  782. restartOnDisable, err := (&SettingService{}).GetRestartXrayOnClientDisable()
  783. if err != nil {
  784. logger.Warning("disableInvalidClients: get RestartXrayOnClientDisable failed:", err)
  785. return
  786. }
  787. if !restartOnDisable {
  788. return
  789. }
  790. for _, nodeID := range nodeIDs {
  791. nodeIDCopy := nodeID
  792. rt, rtErr := runtime.GetManager().RuntimeFor(&nodeIDCopy)
  793. if rtErr != nil {
  794. logger.Warning("disableInvalidClients: get runtime for node", nodeID, "failed:", rtErr)
  795. continue
  796. }
  797. if rtErr = rt.RestartXray(context.Background()); rtErr != nil {
  798. logger.Warning("disableInvalidClients: restart xray on node", nodeID, "failed:", rtErr)
  799. }
  800. }
  801. }
  802. func (s *InboundService) GetOnlineClients() []string {
  803. if p == nil {
  804. return []string{}
  805. }
  806. return p.GetOnlineClients()
  807. }
  808. // GetOnlineClientsByGuid returns online emails keyed by the panelGuid of the
  809. // node that physically hosts each set: this panel's own clients under its own
  810. // GUID, plus every node in the tree under its GUID (#4983). Replaces the old
  811. // node-id keying so a client three hops down is attributed to its real node,
  812. // not the intermediate one it was synced through.
  813. func (s *InboundService) GetOnlineClientsByGuid() map[string][]string {
  814. if p == nil {
  815. return map[string][]string{}
  816. }
  817. out := p.GetMergedNodeTrees()
  818. if local := p.GetLocalOnlineClients(); len(local) > 0 {
  819. if guid := s.panelGuid(); guid != "" {
  820. out[guid] = mergeEmails(out[guid], local)
  821. }
  822. }
  823. return out
  824. }
  825. // GetActiveInboundsByGuid returns the inbound tags that carried traffic within
  826. // the grace window for THIS panel, under its own GUID. Remote nodes don't
  827. // report per-inbound activity, so a GUID missing from the map means "don't
  828. // gate" for that node's inbounds.
  829. func (s *InboundService) GetActiveInboundsByGuid() map[string][]string {
  830. if p == nil {
  831. return map[string][]string{}
  832. }
  833. active := p.GetLocalActiveInbounds()
  834. if len(active) == 0 {
  835. return map[string][]string{}
  836. }
  837. guid := s.panelGuid()
  838. if guid == "" {
  839. return map[string][]string{}
  840. }
  841. return map[string][]string{guid: active}
  842. }
  843. func (s *InboundService) SetNodeOnlineTree(nodeID int, tree map[string][]string) {
  844. if p != nil {
  845. p.SetNodeOnlineTree(nodeID, tree)
  846. }
  847. }
  848. func (s *InboundService) ClearNodeOnlineClients(nodeID int) {
  849. if p != nil {
  850. p.ClearNodeOnlineClients(nodeID)
  851. }
  852. }
  853. // panelGuid returns this panel's stable self-identifier, used to key the local
  854. // panel's own clients in the per-node online maps (#4983).
  855. func (s *InboundService) panelGuid() string {
  856. guid, _ := (&SettingService{}).GetPanelGuid()
  857. return guid
  858. }
  859. // synthNodeGuid is the stable per-node fallback identity for a directly-attached
  860. // node whose panel hasn't reported a panelGuid yet (old build). Node ids are
  861. // master-local, so this only composes for direct nodes — exactly the pre-#4983
  862. // flat-topology case where an old-build node appears.
  863. func synthNodeGuid(nodeID int) string {
  864. return fmt.Sprintf("node:%d", nodeID)
  865. }
  866. // mergeEmails returns the deduped union of two email slices.
  867. func mergeEmails(a, b []string) []string {
  868. if len(a) == 0 {
  869. return b
  870. }
  871. seen := make(map[string]struct{}, len(a)+len(b))
  872. out := make([]string, 0, len(a)+len(b))
  873. for _, e := range a {
  874. if _, ok := seen[e]; !ok {
  875. seen[e] = struct{}{}
  876. out = append(out, e)
  877. }
  878. }
  879. for _, e := range b {
  880. if _, ok := seen[e]; !ok {
  881. seen[e] = struct{}{}
  882. out = append(out, e)
  883. }
  884. }
  885. return out
  886. }
  887. func (s *InboundService) GetClientsLastOnline() (map[string]int64, error) {
  888. db := database.GetDB()
  889. var rows []xray.ClientTraffic
  890. err := db.Model(&xray.ClientTraffic{}).Select("email, last_online").Find(&rows).Error
  891. if err != nil && err != gorm.ErrRecordNotFound {
  892. return nil, err
  893. }
  894. result := make(map[string]int64, len(rows))
  895. for _, r := range rows {
  896. result[r.Email] = r.LastOnline
  897. }
  898. return result, nil
  899. }
  900. // RefreshLocalOnlineClients folds the emails and inbound tags active on this
  901. // panel's own xray this poll into the local online/active sets, applying the
  902. // grace window and pruning stale entries. Pass nil to only prune. See
  903. // xray.Process for why the local sets are kept separate from the shared
  904. // last_online column.
  905. func (s *InboundService) RefreshLocalOnlineClients(activeEmails, activeInboundTags []string) {
  906. if p != nil {
  907. p.RefreshLocalOnline(activeEmails, activeInboundTags, time.Now().UnixMilli(), onlineGracePeriodMs)
  908. }
  909. }
  910. func (s *InboundService) FilterAndSortClientEmails(emails []string) ([]string, []string, error) {
  911. db := database.GetDB()
  912. // Step 1: Get ClientTraffic records for emails in the input list.
  913. // Chunked to stay under SQLite's bind-variable limit on huge inputs.
  914. uniqEmails := uniqueNonEmptyStrings(emails)
  915. clients := make([]xray.ClientTraffic, 0, len(uniqEmails))
  916. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  917. var page []xray.ClientTraffic
  918. if err := db.Where("email IN ?", batch).Find(&page).Error; err != nil && err != gorm.ErrRecordNotFound {
  919. return nil, nil, err
  920. }
  921. clients = append(clients, page...)
  922. }
  923. // Step 2: Sort clients by (Up + Down) descending
  924. sort.Slice(clients, func(i, j int) bool {
  925. return (clients[i].Up + clients[i].Down) > (clients[j].Up + clients[j].Down)
  926. })
  927. // Step 3: Extract sorted valid emails and track found ones
  928. validEmails := make([]string, 0, len(clients))
  929. found := make(map[string]bool)
  930. for _, client := range clients {
  931. validEmails = append(validEmails, client.Email)
  932. found[client.Email] = true
  933. }
  934. // Step 4: Identify emails that were not found in the database
  935. extraEmails := make([]string, 0)
  936. for _, email := range emails {
  937. if !found[email] {
  938. extraEmails = append(extraEmails, email)
  939. }
  940. }
  941. return validEmails, extraEmails, nil
  942. }