inbound_node.go 54 KB

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