1
0

inbound_node.go 54 KB

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