1
0

inbound_node.go 46 KB

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