1
0

inbound_node.go 54 KB

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