inbound_node.go 42 KB

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