1
0

inbound_node.go 58 KB

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