1
0

inbound_node.go 35 KB

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