inbound_node.go 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  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 key. That
  197. // key is the node's panelGuid, unless another of this master's nodes reports
  198. // the same GUID (cloned server — the panelGuid ships in the copied settings),
  199. // in which case it would collapse both nodes into one #4983 bucket, so fall
  200. // back to the node-unique id. Old-build nodes with no GUID use the id too.
  201. var nodeRow model.Node
  202. db.Select("guid").Where("id = ?", nodeID).First(&nodeRow)
  203. guidShared := false
  204. if nodeRow.Guid != "" {
  205. var sameGuid int64
  206. db.Model(&model.Node{}).Where("guid = ?", nodeRow.Guid).Count(&sameGuid)
  207. guidShared = sameGuid > 1
  208. }
  209. selfKey := nodeRow.Guid
  210. if selfKey == "" || guidShared {
  211. selfKey = synthNodeGuid(nodeID)
  212. }
  213. originGuidFor := func(snapIb *model.Inbound) string {
  214. if snapIb.OriginNodeGuid != "" {
  215. return snapIb.OriginNodeGuid
  216. }
  217. return selfKey
  218. }
  219. var central []model.Inbound
  220. if err := db.Model(model.Inbound{}).
  221. Where("node_id = ?", nodeID).
  222. Find(&central).Error; err != nil {
  223. return false, err
  224. }
  225. // Index under the stored tag and its prefix-flipped form so a snap matches
  226. // whether the n<id>- prefix lives on the node side, the central side, or
  227. // neither — a mismatch must never spawn a duplicate central inbound.
  228. tagToCentral := make(map[string]*model.Inbound, len(central)*2)
  229. prefix := nodeTagPrefix(&nodeID)
  230. for i := range central {
  231. tagToCentral[central[i].Tag] = &central[i]
  232. if prefix != "" {
  233. if stripped, found := strings.CutPrefix(central[i].Tag, prefix); found {
  234. tagToCentral[stripped] = &central[i]
  235. } else {
  236. tagToCentral[prefix+central[i].Tag] = &central[i]
  237. }
  238. }
  239. }
  240. var centralClientStats []xray.ClientTraffic
  241. if len(central) > 0 {
  242. ids := make([]int, 0, len(central))
  243. for i := range central {
  244. ids = append(ids, central[i].Id)
  245. }
  246. if err := db.Model(xray.ClientTraffic{}).
  247. Where("inbound_id IN ?", ids).
  248. Find(&centralClientStats).Error; err != nil {
  249. return false, err
  250. }
  251. }
  252. type csKey struct {
  253. inboundID int
  254. email string
  255. }
  256. centralCS := make(map[csKey]*xray.ClientTraffic, len(centralClientStats))
  257. centralCSByEmail := make(map[string]*xray.ClientTraffic, len(centralClientStats))
  258. for i := range centralClientStats {
  259. centralCS[csKey{centralClientStats[i].InboundId, centralClientStats[i].Email}] = &centralClientStats[i]
  260. centralCSByEmail[centralClientStats[i].Email] = &centralClientStats[i]
  261. }
  262. nodeBaselines := make(map[string]nodeTrafficCounter)
  263. var baselineRows []model.NodeClientTraffic
  264. if err := db.Model(&model.NodeClientTraffic{}).
  265. Where("node_id = ?", nodeID).
  266. Find(&baselineRows).Error; err != nil {
  267. return false, err
  268. }
  269. for i := range baselineRows {
  270. nodeBaselines[baselineRows[i].Email] = nodeTrafficCounter{Up: baselineRows[i].Up, Down: baselineRows[i].Down}
  271. }
  272. var defaultUserId int
  273. if len(central) > 0 {
  274. defaultUserId = central[0].UserId
  275. } else {
  276. var u model.User
  277. if err := db.Model(model.User{}).Order("id asc").First(&u).Error; err == nil {
  278. defaultUserId = u.Id
  279. } else {
  280. defaultUserId = 1
  281. }
  282. }
  283. // Union of every email the snapshot still reports, across all inbounds.
  284. // The (node, email) baseline rows are keyed per node, not per inbound, so
  285. // the sweeps below must only drop one when the email left the node
  286. // entirely — an email whose stats moved to (or always lived under) a
  287. // sibling inbound still needs its baseline for the sibling's delta
  288. // computation (#5202).
  289. //
  290. // Xray counts traffic per email, not per inbound, so a multi-attached
  291. // client's shared counter is copied onto every inbound it's on. Fold each
  292. // email to its per-field max (nodeEmailTotals) so divergent copies can't make
  293. // the reset clamp re-add a lower sibling as fresh traffic (#5274).
  294. snapEmailsAll := make(map[string]struct{})
  295. nodeEmailTotals := make(map[string]nodeTrafficCounter)
  296. for _, snapIb := range snap.Inbounds {
  297. if snapIb == nil {
  298. continue
  299. }
  300. for i := range snapIb.ClientStats {
  301. email := snapIb.ClientStats[i].Email
  302. snapEmailsAll[email] = struct{}{}
  303. cur := nodeEmailTotals[email]
  304. if snapIb.ClientStats[i].Up > cur.Up {
  305. cur.Up = snapIb.ClientStats[i].Up
  306. }
  307. if snapIb.ClientStats[i].Down > cur.Down {
  308. cur.Down = snapIb.ClientStats[i].Down
  309. }
  310. nodeEmailTotals[email] = cur
  311. }
  312. }
  313. // Membership set for the rowExists checks below. Only the snapshot's emails
  314. // are ever probed, so scope the lookup to those instead of plucking the whole
  315. // client_traffics table (50k+ rows) on every node poll.
  316. existingEmails := make(map[string]struct{}, len(snapEmailsAll))
  317. if len(snapEmailsAll) > 0 {
  318. snapEmailList := make([]string, 0, len(snapEmailsAll))
  319. for email := range snapEmailsAll {
  320. snapEmailList = append(snapEmailList, email)
  321. }
  322. for _, batch := range chunkStrings(snapEmailList, sqliteMaxVars) {
  323. var found []string
  324. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Pluck("email", &found).Error; err != nil {
  325. return false, err
  326. }
  327. for _, e := range found {
  328. existingEmails[e] = struct{}{}
  329. }
  330. }
  331. }
  332. tx := db.Begin()
  333. committed := false
  334. defer func() {
  335. if !committed {
  336. tx.Rollback()
  337. }
  338. }()
  339. structuralChange := false
  340. snapTags := make(map[string]struct{}, len(snap.Inbounds))
  341. for _, snapIb := range snap.Inbounds {
  342. if snapIb == nil {
  343. continue
  344. }
  345. snapTags[snapIb.Tag] = struct{}{}
  346. // Record the prefix-flipped form too so the orphan sweep below keeps a
  347. // central inbound whether its tag carries the n<id>- prefix or not.
  348. if prefix != "" {
  349. if stripped, found := strings.CutPrefix(snapIb.Tag, prefix); found {
  350. snapTags[stripped] = struct{}{}
  351. } else {
  352. snapTags[prefix+snapIb.Tag] = struct{}{}
  353. }
  354. }
  355. c, ok := tagToCentral[snapIb.Tag]
  356. if !ok {
  357. if dirty {
  358. continue
  359. }
  360. // Try snap.Tag first; on collision fall back to the n<id>-
  361. // prefixed form so local+node can both own the same port.
  362. pickFreeTag := func() (string, error) {
  363. candidates := []string{snapIb.Tag}
  364. if prefix != "" && !strings.HasPrefix(snapIb.Tag, prefix) {
  365. candidates = append(candidates, prefix+snapIb.Tag)
  366. }
  367. for _, t := range candidates {
  368. var owner model.Inbound
  369. err := tx.Where("tag = ?", t).First(&owner).Error
  370. if errors.Is(err, gorm.ErrRecordNotFound) {
  371. return t, nil
  372. }
  373. if err != nil {
  374. return "", err
  375. }
  376. }
  377. return "", nil
  378. }
  379. chosenTag, err := pickFreeTag()
  380. if err != nil {
  381. logger.Warningf("setRemoteTraffic: check tag %q failed: %v", snapIb.Tag, err)
  382. continue
  383. }
  384. if chosenTag == "" {
  385. key := fmt.Sprintf("%d:%s", nodeID, snapIb.Tag)
  386. if _, seen := reportedRemoteTagConflict.LoadOrStore(key, struct{}{}); !seen {
  387. logger.Warningf(
  388. "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)",
  389. snapIb.Tag, nodeID, nodeID,
  390. )
  391. }
  392. continue
  393. }
  394. reportedRemoteTagConflict.Delete(fmt.Sprintf("%d:%s", nodeID, snapIb.Tag))
  395. newIb := model.Inbound{
  396. UserId: defaultUserId,
  397. NodeID: &nodeID,
  398. OriginNodeGuid: originGuidFor(snapIb),
  399. Tag: chosenTag,
  400. Listen: snapIb.Listen,
  401. Port: snapIb.Port,
  402. Protocol: snapIb.Protocol,
  403. Settings: snapIb.Settings,
  404. StreamSettings: snapIb.StreamSettings,
  405. Sniffing: snapIb.Sniffing,
  406. TrafficReset: snapIb.TrafficReset,
  407. LastTrafficResetTime: snapIb.LastTrafficResetTime,
  408. Enable: snapIb.Enable,
  409. Remark: snapIb.Remark,
  410. SubSortIndex: normalizeSubSortIndex(snapIb.SubSortIndex),
  411. Total: snapIb.Total,
  412. ExpiryTime: snapIb.ExpiryTime,
  413. Up: snapIb.Up,
  414. Down: snapIb.Down,
  415. ShareAddrStrategy: "node",
  416. }
  417. if err := tx.Create(&newIb).Error; err != nil {
  418. logger.Warningf("setRemoteTraffic: create central inbound for tag %q failed: %v", snapIb.Tag, err)
  419. continue
  420. }
  421. tagToCentral[snapIb.Tag] = &newIb
  422. if newIb.Tag != snapIb.Tag {
  423. tagToCentral[newIb.Tag] = &newIb
  424. }
  425. structuralChange = true
  426. continue
  427. }
  428. inGrace := c.LastTrafficResetTime > 0 && now-c.LastTrafficResetTime < resetGracePeriodMs
  429. updates := map[string]any{}
  430. if !dirty {
  431. updates["enable"] = snapIb.Enable
  432. updates["remark"] = snapIb.Remark
  433. updates["sub_sort_index"] = normalizeSubSortIndex(snapIb.SubSortIndex)
  434. updates["listen"] = snapIb.Listen
  435. updates["port"] = snapIb.Port
  436. updates["protocol"] = snapIb.Protocol
  437. updates["total"] = snapIb.Total
  438. updates["expiry_time"] = snapIb.ExpiryTime
  439. updates["settings"] = snapIb.Settings
  440. updates["stream_settings"] = snapIb.StreamSettings
  441. updates["sniffing"] = snapIb.Sniffing
  442. updates["traffic_reset"] = snapIb.TrafficReset
  443. updates["last_traffic_reset_time"] = snapIb.LastTrafficResetTime
  444. }
  445. if !inGrace || (snapIb.Up+snapIb.Down) <= (c.Up+c.Down) {
  446. updates["up"] = snapIb.Up
  447. updates["down"] = snapIb.Down
  448. }
  449. // Physical-home attribution is independent of config-dirty state, so
  450. // keep it current even while the node has pending offline edits. Writes
  451. // once to backfill an existing row, then stays equal (#4983).
  452. if og := originGuidFor(snapIb); c.OriginNodeGuid != og {
  453. updates["origin_node_guid"] = og
  454. }
  455. if !dirty && (c.Settings != snapIb.Settings ||
  456. c.Remark != snapIb.Remark ||
  457. c.Listen != snapIb.Listen ||
  458. c.Port != snapIb.Port ||
  459. c.Total != snapIb.Total ||
  460. c.ExpiryTime != snapIb.ExpiryTime ||
  461. c.Enable != snapIb.Enable) {
  462. structuralChange = true
  463. }
  464. if len(updates) > 0 {
  465. if err := tx.Model(model.Inbound{}).
  466. Where("id = ?", c.Id).
  467. Updates(updates).Error; err != nil {
  468. return false, err
  469. }
  470. }
  471. }
  472. for _, c := range central {
  473. if dirty {
  474. continue
  475. }
  476. if _, kept := snapTags[c.Tag]; kept {
  477. continue
  478. }
  479. var goneEmails []string
  480. if err := tx.Model(xray.ClientTraffic{}).
  481. Where("inbound_id = ?", c.Id).
  482. Pluck("email", &goneEmails).Error; err != nil {
  483. return false, err
  484. }
  485. if len(goneEmails) > 0 {
  486. // Baselines are per (node, email), not per inbound: keep them for
  487. // emails the snapshot still reports under a sibling inbound (#5202).
  488. baselineGone := make([]string, 0, len(goneEmails))
  489. for _, e := range goneEmails {
  490. if _, still := snapEmailsAll[e]; !still {
  491. baselineGone = append(baselineGone, e)
  492. }
  493. }
  494. // Chunk to avoid SQLite bind var limit when a node has many clients
  495. // removed (e.g. after API bulk delete or structural change on node inbound).
  496. for _, batch := range chunkStrings(baselineGone, sqliteMaxVars) {
  497. if err := tx.Where("node_id = ? AND email IN ?", nodeID, batch).
  498. Delete(&model.NodeClientTraffic{}).Error; err != nil {
  499. return false, err
  500. }
  501. }
  502. // The per-email row is the shared accumulator across every inbound
  503. // (and node) the email is attached to. Only drop it when this was the
  504. // email's last inbound — wiping it while a sibling still feeds it
  505. // loses the summed history, and the next node sync would re-seed the
  506. // row with that node's counter alone.
  507. sharedEmails, sErr := s.emailsUsedByOtherInbounds(goneEmails, c.Id)
  508. if sErr != nil {
  509. return false, sErr
  510. }
  511. delEmails := make([]string, 0, len(goneEmails))
  512. for _, e := range goneEmails {
  513. if !sharedEmails[strings.ToLower(strings.TrimSpace(e))] {
  514. delEmails = append(delEmails, e)
  515. }
  516. }
  517. for _, batch := range chunkStrings(delEmails, sqliteMaxVars) {
  518. if err := tx.Where("inbound_id = ? AND email IN ?", c.Id, batch).
  519. Delete(&xray.ClientTraffic{}).Error; err != nil {
  520. return false, err
  521. }
  522. }
  523. }
  524. if err := s.clientService.DetachInbound(tx, c.Id); err != nil {
  525. return false, err
  526. }
  527. if err := tx.Where("id = ?", c.Id).
  528. Delete(&model.Inbound{}).Error; err != nil {
  529. return false, err
  530. }
  531. delete(tagToCentral, c.Tag)
  532. structuralChange = true
  533. }
  534. for _, snapIb := range snap.Inbounds {
  535. if snapIb == nil {
  536. continue
  537. }
  538. c, ok := tagToCentral[snapIb.Tag]
  539. if !ok {
  540. continue
  541. }
  542. snapEmails := make(map[string]struct{}, len(snapIb.ClientStats))
  543. for _, cs := range snapIb.ClientStats {
  544. snapEmails[cs.Email] = struct{}{}
  545. // Node-wide total, not this inbound's possibly-stale copy (#5274).
  546. canon := nodeEmailTotals[cs.Email]
  547. base, seen := nodeBaselines[cs.Email]
  548. var deltaUp, deltaDown int64
  549. if seen {
  550. if deltaUp = canon.Up - base.Up; deltaUp < 0 {
  551. deltaUp = 0
  552. }
  553. if deltaDown = canon.Down - base.Down; deltaDown < 0 {
  554. deltaDown = 0
  555. }
  556. }
  557. if _, rowExists := existingEmails[cs.Email]; !rowExists {
  558. if dirty {
  559. continue
  560. }
  561. row := &xray.ClientTraffic{
  562. InboundId: c.Id,
  563. Email: cs.Email,
  564. Enable: cs.Enable,
  565. Total: cs.Total,
  566. ExpiryTime: cs.ExpiryTime,
  567. Reset: cs.Reset,
  568. Up: 0,
  569. Down: 0,
  570. LastOnline: cs.LastOnline,
  571. }
  572. if err := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "email"}}, DoNothing: true}).
  573. Create(row).Error; err != nil {
  574. return false, err
  575. }
  576. centralCS[csKey{c.Id, cs.Email}] = row
  577. centralCSByEmail[cs.Email] = row
  578. existingEmails[cs.Email] = struct{}{}
  579. structuralChange = true
  580. if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon.Up, canon.Down); err != nil {
  581. return false, err
  582. }
  583. nodeBaselines[cs.Email] = nodeTrafficCounter{Up: canon.Up, Down: canon.Down}
  584. continue
  585. }
  586. if existing := centralCSByEmail[cs.Email]; existing != nil &&
  587. (existing.Enable != cs.Enable ||
  588. existing.Total != cs.Total ||
  589. existing.ExpiryTime != mergeActivationExpiry(existing.ExpiryTime, cs.ExpiryTime) ||
  590. existing.Reset != cs.Reset) {
  591. structuralChange = true
  592. }
  593. enableExpr := database.ClientTrafficEnableMergeExpr()
  594. // expiry_time merge mirrors mergeActivationExpiry: a node that has not
  595. // yet seen the client's first connection keeps reporting the negative
  596. // "start after first connect" duration, which must never reset the
  597. // absolute deadline another node already activated. A positive node
  598. // value is still adopted (e.g. auto-renew moves the deadline forward).
  599. // CAST(? AS BIGINT): in the `<= 0` comparison Postgres would otherwise
  600. // infer int4 from the literal and overflow on real expiry values.
  601. if err := tx.Exec(
  602. fmt.Sprintf(
  603. `UPDATE client_traffics
  604. SET up = up + ?, down = down + ?, enable = %s, total = ?,
  605. expiry_time = CASE WHEN expiry_time > 0 AND CAST(? AS BIGINT) <= 0 THEN expiry_time ELSE CAST(? AS BIGINT) END,
  606. reset = ?, last_online = %s
  607. WHERE email = ?`,
  608. enableExpr,
  609. database.GreatestExpr("last_online", "?"),
  610. ),
  611. deltaUp, deltaDown, cs.Enable, cs.Total,
  612. cs.ExpiryTime, cs.ExpiryTime, cs.Reset,
  613. cs.LastOnline, cs.Email,
  614. ).Error; err != nil {
  615. return false, err
  616. }
  617. if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon.Up, canon.Down); err != nil {
  618. return false, err
  619. }
  620. nodeBaselines[cs.Email] = nodeTrafficCounter{Up: canon.Up, Down: canon.Down}
  621. }
  622. for k, existing := range centralCS {
  623. if dirty {
  624. continue
  625. }
  626. if k.inboundID != c.Id {
  627. continue
  628. }
  629. if _, kept := snapEmails[k.email]; kept {
  630. continue
  631. }
  632. // Gone from this inbound's stats but still reported by the node under
  633. // a sibling inbound: both the shared accumulator row and the (node,
  634. // email) baseline must survive, or the sibling's next delta would
  635. // compute against nothing and freeze the counter (#5202).
  636. if _, still := snapEmailsAll[k.email]; still {
  637. continue
  638. }
  639. if err := tx.Where("node_id = ? AND email = ?", nodeID, existing.Email).
  640. Delete(&model.NodeClientTraffic{}).Error; err != nil {
  641. return false, err
  642. }
  643. // Same shared-accumulator rule as the inbound-removal sweep above:
  644. // keep the row while another inbound still references the email.
  645. stillUsed, uErr := s.emailUsedByOtherInbounds(existing.Email, c.Id)
  646. if uErr != nil {
  647. return false, uErr
  648. }
  649. if !stillUsed {
  650. if err := tx.Where("inbound_id = ? AND email = ?", c.Id, existing.Email).
  651. Delete(&xray.ClientTraffic{}).Error; err != nil {
  652. return false, err
  653. }
  654. }
  655. structuralChange = true
  656. }
  657. }
  658. type oldSet struct {
  659. inboundID int
  660. emails map[string]struct{}
  661. }
  662. var perInboundOld []oldSet
  663. for _, snapIb := range snap.Inbounds {
  664. if snapIb == nil {
  665. continue
  666. }
  667. c, ok := tagToCentral[snapIb.Tag]
  668. if !ok {
  669. continue
  670. }
  671. if dirty {
  672. continue
  673. }
  674. var oldEmailsRows []string
  675. if err := tx.Table("clients").
  676. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  677. Where("client_inbounds.inbound_id = ?", c.Id).
  678. Pluck("email", &oldEmailsRows).Error; err == nil {
  679. oldEmails := make(map[string]struct{}, len(oldEmailsRows))
  680. for _, e := range oldEmailsRows {
  681. if e != "" {
  682. oldEmails[e] = struct{}{}
  683. }
  684. }
  685. perInboundOld = append(perInboundOld, oldSet{inboundID: c.Id, emails: oldEmails})
  686. }
  687. clients, gcErr := s.GetClients(snapIb)
  688. if gcErr != nil {
  689. logger.Warningf("setRemoteTraffic: parse clients for tag %q failed: %v", snapIb.Tag, gcErr)
  690. continue
  691. }
  692. csEnableByEmail := make(map[string]bool, len(snapIb.ClientStats))
  693. for _, cs := range snapIb.ClientStats {
  694. csEnableByEmail[cs.Email] = cs.Enable
  695. }
  696. filtered := clients[:0]
  697. for i := range clients {
  698. if isClientEmailTombstoned(clients[i].Email) {
  699. continue
  700. }
  701. if cse, hit := csEnableByEmail[clients[i].Email]; hit && !cse {
  702. clients[i].Enable = false
  703. }
  704. filtered = append(filtered, clients[i])
  705. }
  706. localEmails := make([]string, 0, len(filtered))
  707. for i := range filtered {
  708. if filtered[i].Email != "" {
  709. localEmails = append(localEmails, filtered[i].Email)
  710. }
  711. }
  712. if len(localEmails) > 0 {
  713. var localMeta []struct {
  714. Email string
  715. Comment string `gorm:"column:comment"`
  716. }
  717. if err := tx.Table("clients").
  718. Select("email, comment").
  719. Where("email IN ?", localEmails).
  720. Find(&localMeta).Error; err == nil {
  721. commentByEmail := make(map[string]string, len(localMeta))
  722. for _, m := range localMeta {
  723. commentByEmail[m.Email] = m.Comment
  724. }
  725. for i := range filtered {
  726. if cmt, ok := commentByEmail[filtered[i].Email]; ok {
  727. filtered[i].Comment = cmt
  728. }
  729. }
  730. }
  731. }
  732. if err := s.clientService.SyncInbound(tx, c.Id, filtered); err != nil {
  733. logger.Warningf("setRemoteTraffic: sync clients for tag %q failed: %v", snapIb.Tag, err)
  734. }
  735. }
  736. for _, old := range perInboundOld {
  737. var stillAttached []string
  738. if err := tx.Table("clients").
  739. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  740. Where("client_inbounds.inbound_id = ?", old.inboundID).
  741. Pluck("email", &stillAttached).Error; err != nil {
  742. continue
  743. }
  744. stillSet := make(map[string]struct{}, len(stillAttached))
  745. for _, e := range stillAttached {
  746. stillSet[e] = struct{}{}
  747. }
  748. for email := range old.emails {
  749. if _, kept := stillSet[email]; kept {
  750. continue
  751. }
  752. var attachmentCount int64
  753. if err := tx.Table("client_inbounds").
  754. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  755. Where("clients.email = ?", email).
  756. Count(&attachmentCount).Error; err != nil {
  757. continue
  758. }
  759. if attachmentCount > 0 {
  760. continue
  761. }
  762. if err := tx.Where("email = ?", email).Delete(&model.ClientRecord{}).Error; err != nil {
  763. logger.Warningf("setRemoteTraffic: delete ClientRecord %q failed: %v", email, err)
  764. }
  765. if err := tx.Where("email = ?", email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  766. logger.Warningf("setRemoteTraffic: delete ClientTraffic %q failed: %v", email, err)
  767. }
  768. if err := tx.Where("email = ?", email).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  769. logger.Warningf("setRemoteTraffic: delete NodeClientTraffic %q failed: %v", email, err)
  770. }
  771. structuralChange = true
  772. }
  773. }
  774. if err := tx.Commit().Error; err != nil {
  775. return false, err
  776. }
  777. committed = true
  778. if p != nil {
  779. tree := snap.OnlineTree
  780. switch {
  781. case len(tree) == 0 && len(snap.OnlineEmails) > 0:
  782. // Old-build node (no GUID tree): key its flat online list under its
  783. // own effective identity so attribution still works for that branch.
  784. tree = map[string][]string{selfKey: snap.OnlineEmails}
  785. case guidShared && len(tree) > 0:
  786. // Newer cloned node: its own clients arrive keyed under the shared
  787. // panelGuid. Remap just that entry to the node-unique key so the
  788. // clones don't merge; descendant subtrees keep their distinct GUIDs.
  789. if _, ok := tree[nodeRow.Guid]; ok {
  790. remapped := make(map[string][]string, len(tree))
  791. for g, emails := range tree {
  792. if g == nodeRow.Guid {
  793. g = selfKey
  794. }
  795. remapped[g] = emails
  796. }
  797. tree = remapped
  798. }
  799. }
  800. p.SetNodeOnlineTree(nodeID, tree)
  801. }
  802. return structuralChange, nil
  803. }
  804. func (s *InboundService) restartRemoteNodesOnDisable(nodeIDs []int) {
  805. restartOnDisable, err := (&SettingService{}).GetRestartXrayOnClientDisable()
  806. if err != nil {
  807. logger.Warning("disableInvalidClients: get RestartXrayOnClientDisable failed:", err)
  808. return
  809. }
  810. if !restartOnDisable {
  811. return
  812. }
  813. for _, nodeID := range nodeIDs {
  814. nodeIDCopy := nodeID
  815. rt, rtErr := runtime.GetManager().RuntimeFor(&nodeIDCopy)
  816. if rtErr != nil {
  817. logger.Warning("disableInvalidClients: get runtime for node", nodeID, "failed:", rtErr)
  818. continue
  819. }
  820. if rtErr = rt.RestartXray(context.Background()); rtErr != nil {
  821. logger.Warning("disableInvalidClients: restart xray on node", nodeID, "failed:", rtErr)
  822. }
  823. }
  824. }
  825. func (s *InboundService) GetOnlineClients() []string {
  826. if p == nil {
  827. return []string{}
  828. }
  829. return p.GetOnlineClients()
  830. }
  831. // GetOnlineClientsByGuid returns online emails keyed by the panelGuid of the
  832. // node that physically hosts each set: this panel's own clients under its own
  833. // GUID, plus every node in the tree under its GUID (#4983). Replaces the old
  834. // node-id keying so a client three hops down is attributed to its real node,
  835. // not the intermediate one it was synced through.
  836. func (s *InboundService) GetOnlineClientsByGuid() map[string][]string {
  837. if p == nil {
  838. return map[string][]string{}
  839. }
  840. out := p.GetMergedNodeTrees()
  841. if local := p.GetLocalOnlineClients(); len(local) > 0 {
  842. if guid := s.panelGuid(); guid != "" {
  843. out[guid] = mergeEmails(out[guid], local)
  844. }
  845. }
  846. return out
  847. }
  848. // GetActiveInboundsByGuid returns the inbound tags that carried traffic within
  849. // the grace window for THIS panel, under its own GUID. Remote nodes don't
  850. // report per-inbound activity, so a GUID missing from the map means "don't
  851. // gate" for that node's inbounds.
  852. func (s *InboundService) GetActiveInboundsByGuid() map[string][]string {
  853. if p == nil {
  854. return map[string][]string{}
  855. }
  856. active := p.GetLocalActiveInbounds()
  857. if len(active) == 0 {
  858. return map[string][]string{}
  859. }
  860. guid := s.panelGuid()
  861. if guid == "" {
  862. return map[string][]string{}
  863. }
  864. return map[string][]string{guid: active}
  865. }
  866. func (s *InboundService) SetNodeOnlineTree(nodeID int, tree map[string][]string) {
  867. if p != nil {
  868. p.SetNodeOnlineTree(nodeID, tree)
  869. }
  870. }
  871. func (s *InboundService) ClearNodeOnlineClients(nodeID int) {
  872. if p != nil {
  873. p.ClearNodeOnlineClients(nodeID)
  874. }
  875. }
  876. // panelGuid returns this panel's stable self-identifier, used to key the local
  877. // panel's own clients in the per-node online maps (#4983).
  878. func (s *InboundService) panelGuid() string {
  879. guid, _ := (&SettingService{}).GetPanelGuid()
  880. return guid
  881. }
  882. // synthNodeGuid is the stable per-node fallback identity for a directly-attached
  883. // node whose panel hasn't reported a panelGuid yet (old build). Node ids are
  884. // master-local, so this only composes for direct nodes — exactly the pre-#4983
  885. // flat-topology case where an old-build node appears.
  886. func synthNodeGuid(nodeID int) string {
  887. return fmt.Sprintf("node:%d", nodeID)
  888. }
  889. // mergeEmails returns the deduped union of two email slices.
  890. func mergeEmails(a, b []string) []string {
  891. if len(a) == 0 {
  892. return b
  893. }
  894. seen := make(map[string]struct{}, len(a)+len(b))
  895. out := make([]string, 0, len(a)+len(b))
  896. for _, e := range a {
  897. if _, ok := seen[e]; !ok {
  898. seen[e] = struct{}{}
  899. out = append(out, e)
  900. }
  901. }
  902. for _, e := range b {
  903. if _, ok := seen[e]; !ok {
  904. seen[e] = struct{}{}
  905. out = append(out, e)
  906. }
  907. }
  908. return out
  909. }
  910. func (s *InboundService) GetClientsLastOnline() (map[string]int64, error) {
  911. db := database.GetDB()
  912. var rows []xray.ClientTraffic
  913. err := db.Model(&xray.ClientTraffic{}).Select("email, last_online").Find(&rows).Error
  914. if err != nil && err != gorm.ErrRecordNotFound {
  915. return nil, err
  916. }
  917. result := make(map[string]int64, len(rows))
  918. for _, r := range rows {
  919. result[r.Email] = r.LastOnline
  920. }
  921. return result, nil
  922. }
  923. // RefreshLocalOnlineClients folds the emails and inbound tags active on this
  924. // panel's own xray this poll into the local online/active sets, applying the
  925. // grace window and pruning stale entries. Pass nil to only prune. See
  926. // xray.Process for why the local sets are kept separate from the shared
  927. // last_online column.
  928. func (s *InboundService) RefreshLocalOnlineClients(activeEmails, activeInboundTags []string) {
  929. if p != nil {
  930. p.RefreshLocalOnline(activeEmails, activeInboundTags, time.Now().UnixMilli(), onlineGracePeriodMs)
  931. }
  932. }
  933. func (s *InboundService) FilterAndSortClientEmails(emails []string) ([]string, []string, error) {
  934. db := database.GetDB()
  935. // Step 1: Get ClientTraffic records for emails in the input list.
  936. // Chunked to stay under SQLite's bind-variable limit on huge inputs.
  937. uniqEmails := uniqueNonEmptyStrings(emails)
  938. clients := make([]xray.ClientTraffic, 0, len(uniqEmails))
  939. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  940. var page []xray.ClientTraffic
  941. if err := db.Where("email IN ?", batch).Find(&page).Error; err != nil && err != gorm.ErrRecordNotFound {
  942. return nil, nil, err
  943. }
  944. clients = append(clients, page...)
  945. }
  946. // Step 2: Sort clients by (Up + Down) descending
  947. sort.Slice(clients, func(i, j int) bool {
  948. return (clients[i].Up + clients[i].Down) > (clients[j].Up + clients[j].Down)
  949. })
  950. // Step 3: Extract sorted valid emails and track found ones
  951. validEmails := make([]string, 0, len(clients))
  952. found := make(map[string]bool)
  953. for _, client := range clients {
  954. validEmails = append(validEmails, client.Email)
  955. found[client.Email] = true
  956. }
  957. // Step 4: Identify emails that were not found in the database
  958. extraEmails := make([]string, 0)
  959. for _, email := range emails {
  960. if !found[email] {
  961. extraEmails = append(extraEmails, email)
  962. }
  963. }
  964. return validEmails, extraEmails, nil
  965. }