inbound_node.go 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  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. newIb := model.Inbound{
  383. UserId: defaultUserId,
  384. NodeID: &nodeID,
  385. OriginNodeGuid: originGuidFor(snapIb),
  386. Tag: chosenTag,
  387. Listen: snapIb.Listen,
  388. Port: snapIb.Port,
  389. Protocol: snapIb.Protocol,
  390. Settings: snapIb.Settings,
  391. StreamSettings: snapIb.StreamSettings,
  392. Sniffing: snapIb.Sniffing,
  393. TrafficReset: snapIb.TrafficReset,
  394. LastTrafficResetTime: snapIb.LastTrafficResetTime,
  395. Enable: snapIb.Enable,
  396. Remark: snapIb.Remark,
  397. SubSortIndex: normalizeSubSortIndex(snapIb.SubSortIndex),
  398. Total: snapIb.Total,
  399. ExpiryTime: snapIb.ExpiryTime,
  400. Up: snapIb.Up,
  401. Down: snapIb.Down,
  402. ShareAddrStrategy: "node",
  403. }
  404. if err := tx.Create(&newIb).Error; err != nil {
  405. logger.Warningf("setRemoteTraffic: create central inbound for tag %q failed: %v", snapIb.Tag, err)
  406. continue
  407. }
  408. tagToCentral[snapIb.Tag] = &newIb
  409. if newIb.Tag != snapIb.Tag {
  410. tagToCentral[newIb.Tag] = &newIb
  411. }
  412. structuralChange = true
  413. continue
  414. }
  415. inGrace := c.LastTrafficResetTime > 0 && now-c.LastTrafficResetTime < resetGracePeriodMs
  416. updates := map[string]any{}
  417. if !dirty {
  418. updates["enable"] = snapIb.Enable
  419. updates["remark"] = snapIb.Remark
  420. updates["sub_sort_index"] = normalizeSubSortIndex(snapIb.SubSortIndex)
  421. updates["listen"] = snapIb.Listen
  422. updates["port"] = snapIb.Port
  423. updates["protocol"] = snapIb.Protocol
  424. updates["total"] = snapIb.Total
  425. updates["expiry_time"] = snapIb.ExpiryTime
  426. updates["settings"] = snapIb.Settings
  427. updates["stream_settings"] = snapIb.StreamSettings
  428. updates["sniffing"] = snapIb.Sniffing
  429. updates["traffic_reset"] = snapIb.TrafficReset
  430. updates["last_traffic_reset_time"] = snapIb.LastTrafficResetTime
  431. }
  432. if !inGrace || (snapIb.Up+snapIb.Down) <= (c.Up+c.Down) {
  433. updates["up"] = snapIb.Up
  434. updates["down"] = snapIb.Down
  435. }
  436. // Physical-home attribution is independent of config-dirty state, so
  437. // keep it current even while the node has pending offline edits. Writes
  438. // once to backfill an existing row, then stays equal (#4983).
  439. if og := originGuidFor(snapIb); c.OriginNodeGuid != og {
  440. updates["origin_node_guid"] = og
  441. }
  442. if !dirty && (c.Settings != snapIb.Settings ||
  443. c.Remark != snapIb.Remark ||
  444. c.Listen != snapIb.Listen ||
  445. c.Port != snapIb.Port ||
  446. c.Total != snapIb.Total ||
  447. c.ExpiryTime != snapIb.ExpiryTime ||
  448. c.Enable != snapIb.Enable) {
  449. structuralChange = true
  450. }
  451. if len(updates) > 0 {
  452. if err := tx.Model(model.Inbound{}).
  453. Where("id = ?", c.Id).
  454. Updates(updates).Error; err != nil {
  455. return false, err
  456. }
  457. }
  458. }
  459. for _, c := range central {
  460. if dirty {
  461. continue
  462. }
  463. if _, kept := snapTags[c.Tag]; kept {
  464. continue
  465. }
  466. var goneEmails []string
  467. if err := tx.Model(xray.ClientTraffic{}).
  468. Where("inbound_id = ?", c.Id).
  469. Pluck("email", &goneEmails).Error; err != nil {
  470. return false, err
  471. }
  472. if len(goneEmails) > 0 {
  473. // Baselines are per (node, email), not per inbound: keep them for
  474. // emails the snapshot still reports under a sibling inbound (#5202).
  475. baselineGone := make([]string, 0, len(goneEmails))
  476. for _, e := range goneEmails {
  477. if _, still := snapEmailsAll[e]; !still {
  478. baselineGone = append(baselineGone, e)
  479. }
  480. }
  481. // Chunk to avoid SQLite bind var limit when a node has many clients
  482. // removed (e.g. after API bulk delete or structural change on node inbound).
  483. for _, batch := range chunkStrings(baselineGone, sqliteMaxVars) {
  484. if err := tx.Where("node_id = ? AND email IN ?", nodeID, batch).
  485. Delete(&model.NodeClientTraffic{}).Error; err != nil {
  486. return false, err
  487. }
  488. }
  489. // The per-email row is the shared accumulator across every inbound
  490. // (and node) the email is attached to. Only drop it when this was the
  491. // email's last inbound — wiping it while a sibling still feeds it
  492. // loses the summed history, and the next node sync would re-seed the
  493. // row with that node's counter alone.
  494. sharedEmails, sErr := s.emailsUsedByOtherInbounds(goneEmails, c.Id)
  495. if sErr != nil {
  496. return false, sErr
  497. }
  498. delEmails := make([]string, 0, len(goneEmails))
  499. for _, e := range goneEmails {
  500. if !sharedEmails[strings.ToLower(strings.TrimSpace(e))] {
  501. delEmails = append(delEmails, e)
  502. }
  503. }
  504. for _, batch := range chunkStrings(delEmails, sqliteMaxVars) {
  505. if err := tx.Where("inbound_id = ? AND email IN ?", c.Id, batch).
  506. Delete(&xray.ClientTraffic{}).Error; err != nil {
  507. return false, err
  508. }
  509. }
  510. }
  511. if err := s.clientService.DetachInbound(tx, c.Id); err != nil {
  512. return false, err
  513. }
  514. if err := tx.Where("id = ?", c.Id).
  515. Delete(&model.Inbound{}).Error; err != nil {
  516. return false, err
  517. }
  518. delete(tagToCentral, c.Tag)
  519. structuralChange = true
  520. }
  521. for _, snapIb := range snap.Inbounds {
  522. if snapIb == nil {
  523. continue
  524. }
  525. c, ok := tagToCentral[snapIb.Tag]
  526. if !ok {
  527. continue
  528. }
  529. snapEmails := make(map[string]struct{}, len(snapIb.ClientStats))
  530. for _, cs := range snapIb.ClientStats {
  531. snapEmails[cs.Email] = struct{}{}
  532. // Node-wide total, not this inbound's possibly-stale copy (#5274).
  533. canon := nodeEmailTotals[cs.Email]
  534. base, seen := nodeBaselines[cs.Email]
  535. var deltaUp, deltaDown int64
  536. if seen {
  537. if deltaUp = canon.Up - base.Up; deltaUp < 0 {
  538. deltaUp = canon.Up
  539. }
  540. if deltaDown = canon.Down - base.Down; deltaDown < 0 {
  541. deltaDown = canon.Down
  542. }
  543. }
  544. if _, rowExists := existingEmails[cs.Email]; !rowExists {
  545. if dirty {
  546. continue
  547. }
  548. row := &xray.ClientTraffic{
  549. InboundId: c.Id,
  550. Email: cs.Email,
  551. Enable: cs.Enable,
  552. Total: cs.Total,
  553. ExpiryTime: cs.ExpiryTime,
  554. Reset: cs.Reset,
  555. Up: 0,
  556. Down: 0,
  557. LastOnline: cs.LastOnline,
  558. }
  559. if err := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "email"}}, DoNothing: true}).
  560. Create(row).Error; err != nil {
  561. return false, err
  562. }
  563. centralCS[csKey{c.Id, cs.Email}] = row
  564. centralCSByEmail[cs.Email] = row
  565. existingEmails[cs.Email] = struct{}{}
  566. structuralChange = true
  567. if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon.Up, canon.Down); err != nil {
  568. return false, err
  569. }
  570. nodeBaselines[cs.Email] = nodeTrafficCounter{Up: canon.Up, Down: canon.Down}
  571. continue
  572. }
  573. if existing := centralCSByEmail[cs.Email]; existing != nil &&
  574. (existing.Enable != cs.Enable ||
  575. existing.Total != cs.Total ||
  576. existing.ExpiryTime != mergeActivationExpiry(existing.ExpiryTime, cs.ExpiryTime) ||
  577. existing.Reset != cs.Reset) {
  578. structuralChange = true
  579. }
  580. enableExpr := database.ClientTrafficEnableMergeExpr()
  581. // expiry_time merge mirrors mergeActivationExpiry: a node that has not
  582. // yet seen the client's first connection keeps reporting the negative
  583. // "start after first connect" duration, which must never reset the
  584. // absolute deadline another node already activated. A positive node
  585. // value is still adopted (e.g. auto-renew moves the deadline forward).
  586. // CAST(? AS BIGINT): in the `<= 0` comparison Postgres would otherwise
  587. // infer int4 from the literal and overflow on real expiry values.
  588. if err := tx.Exec(
  589. fmt.Sprintf(
  590. `UPDATE client_traffics
  591. SET up = up + ?, down = down + ?, enable = %s, total = ?,
  592. expiry_time = CASE WHEN expiry_time > 0 AND CAST(? AS BIGINT) <= 0 THEN expiry_time ELSE CAST(? AS BIGINT) END,
  593. reset = ?, last_online = %s
  594. WHERE email = ?`,
  595. enableExpr,
  596. database.GreatestExpr("last_online", "?"),
  597. ),
  598. deltaUp, deltaDown, cs.Enable, cs.Total,
  599. cs.ExpiryTime, cs.ExpiryTime, cs.Reset,
  600. cs.LastOnline, cs.Email,
  601. ).Error; err != nil {
  602. return false, err
  603. }
  604. if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon.Up, canon.Down); err != nil {
  605. return false, err
  606. }
  607. nodeBaselines[cs.Email] = nodeTrafficCounter{Up: canon.Up, Down: canon.Down}
  608. }
  609. for k, existing := range centralCS {
  610. if dirty {
  611. continue
  612. }
  613. if k.inboundID != c.Id {
  614. continue
  615. }
  616. if _, kept := snapEmails[k.email]; kept {
  617. continue
  618. }
  619. // Gone from this inbound's stats but still reported by the node under
  620. // a sibling inbound: both the shared accumulator row and the (node,
  621. // email) baseline must survive, or the sibling's next delta would
  622. // compute against nothing and freeze the counter (#5202).
  623. if _, still := snapEmailsAll[k.email]; still {
  624. continue
  625. }
  626. if err := tx.Where("node_id = ? AND email = ?", nodeID, existing.Email).
  627. Delete(&model.NodeClientTraffic{}).Error; err != nil {
  628. return false, err
  629. }
  630. // Same shared-accumulator rule as the inbound-removal sweep above:
  631. // keep the row while another inbound still references the email.
  632. stillUsed, uErr := s.emailUsedByOtherInbounds(existing.Email, c.Id)
  633. if uErr != nil {
  634. return false, uErr
  635. }
  636. if !stillUsed {
  637. if err := tx.Where("inbound_id = ? AND email = ?", c.Id, existing.Email).
  638. Delete(&xray.ClientTraffic{}).Error; err != nil {
  639. return false, err
  640. }
  641. }
  642. structuralChange = true
  643. }
  644. }
  645. type oldSet struct {
  646. inboundID int
  647. emails map[string]struct{}
  648. }
  649. var perInboundOld []oldSet
  650. for _, snapIb := range snap.Inbounds {
  651. if snapIb == nil {
  652. continue
  653. }
  654. c, ok := tagToCentral[snapIb.Tag]
  655. if !ok {
  656. continue
  657. }
  658. if dirty {
  659. continue
  660. }
  661. var oldEmailsRows []string
  662. if err := tx.Table("clients").
  663. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  664. Where("client_inbounds.inbound_id = ?", c.Id).
  665. Pluck("email", &oldEmailsRows).Error; err == nil {
  666. oldEmails := make(map[string]struct{}, len(oldEmailsRows))
  667. for _, e := range oldEmailsRows {
  668. if e != "" {
  669. oldEmails[e] = struct{}{}
  670. }
  671. }
  672. perInboundOld = append(perInboundOld, oldSet{inboundID: c.Id, emails: oldEmails})
  673. }
  674. clients, gcErr := s.GetClients(snapIb)
  675. if gcErr != nil {
  676. logger.Warningf("setRemoteTraffic: parse clients for tag %q failed: %v", snapIb.Tag, gcErr)
  677. continue
  678. }
  679. csEnableByEmail := make(map[string]bool, len(snapIb.ClientStats))
  680. for _, cs := range snapIb.ClientStats {
  681. csEnableByEmail[cs.Email] = cs.Enable
  682. }
  683. filtered := clients[:0]
  684. for i := range clients {
  685. if isClientEmailTombstoned(clients[i].Email) {
  686. continue
  687. }
  688. if cse, hit := csEnableByEmail[clients[i].Email]; hit && !cse {
  689. clients[i].Enable = false
  690. }
  691. filtered = append(filtered, clients[i])
  692. }
  693. localEmails := make([]string, 0, len(filtered))
  694. for i := range filtered {
  695. if filtered[i].Email != "" {
  696. localEmails = append(localEmails, filtered[i].Email)
  697. }
  698. }
  699. if len(localEmails) > 0 {
  700. var localMeta []struct {
  701. Email string
  702. Comment string `gorm:"column:comment"`
  703. }
  704. if err := tx.Table("clients").
  705. Select("email, comment").
  706. Where("email IN ?", localEmails).
  707. Find(&localMeta).Error; err == nil {
  708. commentByEmail := make(map[string]string, len(localMeta))
  709. for _, m := range localMeta {
  710. commentByEmail[m.Email] = m.Comment
  711. }
  712. for i := range filtered {
  713. if cmt, ok := commentByEmail[filtered[i].Email]; ok {
  714. filtered[i].Comment = cmt
  715. }
  716. }
  717. }
  718. }
  719. if err := s.clientService.SyncInbound(tx, c.Id, filtered); err != nil {
  720. logger.Warningf("setRemoteTraffic: sync clients for tag %q failed: %v", snapIb.Tag, err)
  721. }
  722. }
  723. for _, old := range perInboundOld {
  724. var stillAttached []string
  725. if err := tx.Table("clients").
  726. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  727. Where("client_inbounds.inbound_id = ?", old.inboundID).
  728. Pluck("email", &stillAttached).Error; err != nil {
  729. continue
  730. }
  731. stillSet := make(map[string]struct{}, len(stillAttached))
  732. for _, e := range stillAttached {
  733. stillSet[e] = struct{}{}
  734. }
  735. for email := range old.emails {
  736. if _, kept := stillSet[email]; kept {
  737. continue
  738. }
  739. var attachmentCount int64
  740. if err := tx.Table("client_inbounds").
  741. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  742. Where("clients.email = ?", email).
  743. Count(&attachmentCount).Error; err != nil {
  744. continue
  745. }
  746. if attachmentCount > 0 {
  747. continue
  748. }
  749. if err := tx.Where("email = ?", email).Delete(&model.ClientRecord{}).Error; err != nil {
  750. logger.Warningf("setRemoteTraffic: delete ClientRecord %q failed: %v", email, err)
  751. }
  752. if err := tx.Where("email = ?", email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  753. logger.Warningf("setRemoteTraffic: delete ClientTraffic %q failed: %v", email, err)
  754. }
  755. if err := tx.Where("email = ?", email).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  756. logger.Warningf("setRemoteTraffic: delete NodeClientTraffic %q failed: %v", email, err)
  757. }
  758. structuralChange = true
  759. }
  760. }
  761. if err := tx.Commit().Error; err != nil {
  762. return false, err
  763. }
  764. committed = true
  765. if p != nil {
  766. tree := snap.OnlineTree
  767. if len(tree) == 0 && len(snap.OnlineEmails) > 0 {
  768. // Old-build node (no GUID tree): key its flat online list under its
  769. // own effective identity so attribution still works for that branch.
  770. effectiveGuid := nodeRow.Guid
  771. if effectiveGuid == "" {
  772. effectiveGuid = synthNodeGuid(nodeID)
  773. }
  774. tree = map[string][]string{effectiveGuid: snap.OnlineEmails}
  775. }
  776. p.SetNodeOnlineTree(nodeID, tree)
  777. }
  778. return structuralChange, nil
  779. }
  780. func (s *InboundService) restartRemoteNodesOnDisable(nodeIDs []int) {
  781. restartOnDisable, err := (&SettingService{}).GetRestartXrayOnClientDisable()
  782. if err != nil {
  783. logger.Warning("disableInvalidClients: get RestartXrayOnClientDisable failed:", err)
  784. return
  785. }
  786. if !restartOnDisable {
  787. return
  788. }
  789. for _, nodeID := range nodeIDs {
  790. nodeIDCopy := nodeID
  791. rt, rtErr := runtime.GetManager().RuntimeFor(&nodeIDCopy)
  792. if rtErr != nil {
  793. logger.Warning("disableInvalidClients: get runtime for node", nodeID, "failed:", rtErr)
  794. continue
  795. }
  796. if rtErr = rt.RestartXray(context.Background()); rtErr != nil {
  797. logger.Warning("disableInvalidClients: restart xray on node", nodeID, "failed:", rtErr)
  798. }
  799. }
  800. }
  801. func (s *InboundService) GetOnlineClients() []string {
  802. if p == nil {
  803. return []string{}
  804. }
  805. return p.GetOnlineClients()
  806. }
  807. // GetOnlineClientsByGuid returns online emails keyed by the panelGuid of the
  808. // node that physically hosts each set: this panel's own clients under its own
  809. // GUID, plus every node in the tree under its GUID (#4983). Replaces the old
  810. // node-id keying so a client three hops down is attributed to its real node,
  811. // not the intermediate one it was synced through.
  812. func (s *InboundService) GetOnlineClientsByGuid() map[string][]string {
  813. if p == nil {
  814. return map[string][]string{}
  815. }
  816. out := p.GetMergedNodeTrees()
  817. if local := p.GetLocalOnlineClients(); len(local) > 0 {
  818. if guid := s.panelGuid(); guid != "" {
  819. out[guid] = mergeEmails(out[guid], local)
  820. }
  821. }
  822. return out
  823. }
  824. // GetActiveInboundsByGuid returns the inbound tags that carried traffic within
  825. // the grace window for THIS panel, under its own GUID. Remote nodes don't
  826. // report per-inbound activity, so a GUID missing from the map means "don't
  827. // gate" for that node's inbounds.
  828. func (s *InboundService) GetActiveInboundsByGuid() map[string][]string {
  829. if p == nil {
  830. return map[string][]string{}
  831. }
  832. active := p.GetLocalActiveInbounds()
  833. if len(active) == 0 {
  834. return map[string][]string{}
  835. }
  836. guid := s.panelGuid()
  837. if guid == "" {
  838. return map[string][]string{}
  839. }
  840. return map[string][]string{guid: active}
  841. }
  842. func (s *InboundService) SetNodeOnlineTree(nodeID int, tree map[string][]string) {
  843. if p != nil {
  844. p.SetNodeOnlineTree(nodeID, tree)
  845. }
  846. }
  847. func (s *InboundService) ClearNodeOnlineClients(nodeID int) {
  848. if p != nil {
  849. p.ClearNodeOnlineClients(nodeID)
  850. }
  851. }
  852. // panelGuid returns this panel's stable self-identifier, used to key the local
  853. // panel's own clients in the per-node online maps (#4983).
  854. func (s *InboundService) panelGuid() string {
  855. guid, _ := (&SettingService{}).GetPanelGuid()
  856. return guid
  857. }
  858. // synthNodeGuid is the stable per-node fallback identity for a directly-attached
  859. // node whose panel hasn't reported a panelGuid yet (old build). Node ids are
  860. // master-local, so this only composes for direct nodes — exactly the pre-#4983
  861. // flat-topology case where an old-build node appears.
  862. func synthNodeGuid(nodeID int) string {
  863. return fmt.Sprintf("node:%d", nodeID)
  864. }
  865. // mergeEmails returns the deduped union of two email slices.
  866. func mergeEmails(a, b []string) []string {
  867. if len(a) == 0 {
  868. return b
  869. }
  870. seen := make(map[string]struct{}, len(a)+len(b))
  871. out := make([]string, 0, len(a)+len(b))
  872. for _, e := range a {
  873. if _, ok := seen[e]; !ok {
  874. seen[e] = struct{}{}
  875. out = append(out, e)
  876. }
  877. }
  878. for _, e := range b {
  879. if _, ok := seen[e]; !ok {
  880. seen[e] = struct{}{}
  881. out = append(out, e)
  882. }
  883. }
  884. return out
  885. }
  886. func (s *InboundService) GetClientsLastOnline() (map[string]int64, error) {
  887. db := database.GetDB()
  888. var rows []xray.ClientTraffic
  889. err := db.Model(&xray.ClientTraffic{}).Select("email, last_online").Find(&rows).Error
  890. if err != nil && err != gorm.ErrRecordNotFound {
  891. return nil, err
  892. }
  893. result := make(map[string]int64, len(rows))
  894. for _, r := range rows {
  895. result[r.Email] = r.LastOnline
  896. }
  897. return result, nil
  898. }
  899. // RefreshLocalOnlineClients folds the emails and inbound tags active on this
  900. // panel's own xray this poll into the local online/active sets, applying the
  901. // grace window and pruning stale entries. Pass nil to only prune. See
  902. // xray.Process for why the local sets are kept separate from the shared
  903. // last_online column.
  904. func (s *InboundService) RefreshLocalOnlineClients(activeEmails, activeInboundTags []string) {
  905. if p != nil {
  906. p.RefreshLocalOnline(activeEmails, activeInboundTags, time.Now().UnixMilli(), onlineGracePeriodMs)
  907. }
  908. }
  909. func (s *InboundService) FilterAndSortClientEmails(emails []string) ([]string, []string, error) {
  910. db := database.GetDB()
  911. // Step 1: Get ClientTraffic records for emails in the input list.
  912. // Chunked to stay under SQLite's bind-variable limit on huge inputs.
  913. uniqEmails := uniqueNonEmptyStrings(emails)
  914. clients := make([]xray.ClientTraffic, 0, len(uniqEmails))
  915. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  916. var page []xray.ClientTraffic
  917. if err := db.Where("email IN ?", batch).Find(&page).Error; err != nil && err != gorm.ErrRecordNotFound {
  918. return nil, nil, err
  919. }
  920. clients = append(clients, page...)
  921. }
  922. // Step 2: Sort clients by (Up + Down) descending
  923. sort.Slice(clients, func(i, j int) bool {
  924. return (clients[i].Up + clients[i].Down) > (clients[j].Up + clients[j].Down)
  925. })
  926. // Step 3: Extract sorted valid emails and track found ones
  927. validEmails := make([]string, 0, len(clients))
  928. found := make(map[string]bool)
  929. for _, client := range clients {
  930. validEmails = append(validEmails, client.Email)
  931. found[client.Email] = true
  932. }
  933. // Step 4: Identify emails that were not found in the database
  934. extraEmails := make([]string, 0)
  935. for _, email := range emails {
  936. if !found[email] {
  937. extraEmails = append(extraEmails, email)
  938. }
  939. }
  940. return validEmails, extraEmails, nil
  941. }