1
0

inbound_node.go 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070
  1. package service
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "sort"
  7. "strings"
  8. "sync"
  9. "time"
  10. "github.com/mhsanaei/3x-ui/v3/internal/database"
  11. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  12. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  13. "github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
  14. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  15. "gorm.io/gorm"
  16. "gorm.io/gorm/clause"
  17. )
  18. var reportedRemoteTagConflict sync.Map
  19. // nodeBulkPushThreshold caps how many per-client RPCs a single operation will
  20. // stream to a remote node. Above it, the panel marks the node dirty instead and
  21. // lets one ReconcileNode push converge the whole inbound — far cheaper than M
  22. // sequential round-trips. Small ops stay on the live per-client path.
  23. const nodeBulkPushThreshold = 32
  24. func (s *InboundService) runtimeFor(ib *model.Inbound) (runtime.Runtime, error) {
  25. mgr := runtime.GetManager()
  26. if mgr == nil {
  27. return nil, fmt.Errorf("runtime manager not initialised")
  28. }
  29. return mgr.RuntimeFor(ib.NodeID)
  30. }
  31. func (s *InboundService) nodePushPlan(ib *model.Inbound) (runtime.Runtime, bool, bool, error) {
  32. if ib.NodeID == nil {
  33. rt, err := s.runtimeFor(ib)
  34. if err != nil {
  35. return nil, false, false, nil
  36. }
  37. return rt, true, false, nil
  38. }
  39. nodeSvc := NodeService{}
  40. enabled, status, _, _, err := nodeSvc.NodeSyncState(*ib.NodeID)
  41. if err != nil {
  42. return nil, false, false, err
  43. }
  44. if !enabled || status == "offline" {
  45. return nil, false, true, nil
  46. }
  47. rt, err := s.runtimeFor(ib)
  48. if err != nil {
  49. return nil, false, true, nil
  50. }
  51. return rt, true, false, nil
  52. }
  53. func (s *InboundService) NodeIsPending(nodeID *int) bool {
  54. if nodeID == nil {
  55. return false
  56. }
  57. return (&NodeService{}).IsNodePending(*nodeID)
  58. }
  59. func (s *InboundService) AnyNodePending(inboundIds []int) bool {
  60. if len(inboundIds) == 0 {
  61. return false
  62. }
  63. nodeSvc := NodeService{}
  64. for _, id := range inboundIds {
  65. ib, err := s.GetInbound(id)
  66. if err != nil || ib.NodeID == nil {
  67. continue
  68. }
  69. if nodeSvc.IsNodePending(*ib.NodeID) {
  70. return true
  71. }
  72. }
  73. return false
  74. }
  75. func (s *InboundService) ReconcileNode(ctx context.Context, rt *runtime.Remote, n *model.Node) error {
  76. if rt == nil || n == nil || n.Id <= 0 {
  77. return nil
  78. }
  79. nodeID := n.Id
  80. db := database.GetDB()
  81. var inbounds []*model.Inbound
  82. if err := db.Model(model.Inbound{}).Where("node_id = ?", nodeID).Find(&inbounds).Error; err != nil {
  83. return err
  84. }
  85. remoteTags, err := rt.ListRemoteTags(ctx)
  86. if err != nil {
  87. return err
  88. }
  89. remoteTagSet := make(map[string]struct{}, len(remoteTags))
  90. for _, tag := range remoteTags {
  91. remoteTagSet[tag] = struct{}{}
  92. }
  93. prefix := nodeTagPrefix(&nodeID)
  94. desiredTags := make(map[string]struct{}, len(inbounds)*2)
  95. for _, ib := range inbounds {
  96. desiredTags[ib.Tag] = struct{}{}
  97. // existsOnNode: does the node already report this inbound under any of the
  98. // tag forms it may be stored as? If so, an unchanged push can be skipped.
  99. _, existsOnNode := remoteTagSet[ib.Tag]
  100. if prefix != "" {
  101. if stripped, found := strings.CutPrefix(ib.Tag, prefix); found {
  102. desiredTags[stripped] = struct{}{}
  103. if _, ok := remoteTagSet[stripped]; ok {
  104. existsOnNode = true
  105. }
  106. } else {
  107. desiredTags[prefix+ib.Tag] = struct{}{}
  108. if _, ok := remoteTagSet[prefix+ib.Tag]; ok {
  109. existsOnNode = true
  110. }
  111. }
  112. }
  113. if _, err := rt.ReconcileInbound(ctx, ib, existsOnNode); err != nil {
  114. return fmt.Errorf("reconcile inbound %q: %w", ib.Tag, err)
  115. }
  116. }
  117. // In "selected" sync mode the panel only manages the selected tags: the
  118. // rest were never imported, so their absence from the local DB must not
  119. // delete them from the node. Only a selected tag missing locally (the
  120. // panel deleted it while the node was unreachable) may be swept.
  121. var selected map[string]struct{}
  122. if n.InboundSyncMode == "selected" {
  123. selected = make(map[string]struct{}, len(n.InboundTags))
  124. for _, tag := range n.InboundTags {
  125. selected[tag] = struct{}{}
  126. }
  127. }
  128. for _, tag := range remoteTags {
  129. if _, want := desiredTags[tag]; want {
  130. continue
  131. }
  132. if selected != nil {
  133. if _, managed := selected[tag]; !managed {
  134. continue
  135. }
  136. }
  137. if err := rt.DelInbound(ctx, &model.Inbound{Tag: tag}); err != nil {
  138. return fmt.Errorf("reconcile delete %q: %w", tag, err)
  139. }
  140. }
  141. return nil
  142. }
  143. const resetGracePeriodMs int64 = 30000
  144. // onlineGracePeriodMs must comfortably exceed the 5s traffic-poll interval —
  145. // Xray's stats counters often report a zero delta for an active session across
  146. // a single poll, so a 5s grace would still drop the client on the next tick.
  147. // ~4 polls of slack keeps idle-but-connected clients visible without lingering
  148. // long after a real disconnect.
  149. const onlineGracePeriodMs int64 = 20000
  150. type nodeTrafficCounter struct {
  151. Up int64
  152. Down int64
  153. }
  154. func (s *InboundService) upsertNodeBaseline(tx *gorm.DB, nodeID int, email string, up, down int64) error {
  155. return tx.Clauses(clause.OnConflict{
  156. Columns: []clause.Column{{Name: "node_id"}, {Name: "email"}},
  157. DoUpdates: clause.AssignmentColumns([]string{"up", "down"}),
  158. }).Create(&model.NodeClientTraffic{NodeId: nodeID, Email: email, Up: up, Down: down}).Error
  159. }
  160. // mergeActivationExpiry reconciles a node-reported client expiry with the value
  161. // already stored on the master. "Start after first connect" persists a negative
  162. // duration that each node converts to an absolute deadline (now+duration) the
  163. // first time the client connects there. The per-email client_traffics row is
  164. // shared across every node, so a node that has not yet seen a first connection
  165. // keeps reporting the negative duration — which must never reset a deadline
  166. // another node already activated.
  167. //
  168. // A node may legitimately move an already-activated deadline forward (traffic
  169. // reset / auto-renew extends it), so any positive node value is still adopted —
  170. // only an un-activated (<= 0) value is rejected once an absolute deadline
  171. // exists. Kept in lockstep with the SQL CASE in setRemoteTrafficLocked.
  172. func mergeActivationExpiry(existing, node int64) int64 {
  173. if existing > 0 && node <= 0 {
  174. return existing
  175. }
  176. return node
  177. }
  178. // liftActivatedClientRecordExpiries copies a node-activated deadline from
  179. // client_traffics onto client records still holding the negative duration (#5714).
  180. func liftActivatedClientRecordExpiries(tx *gorm.DB) error {
  181. return tx.Exec(
  182. `UPDATE clients
  183. SET expiry_time = (SELECT ct.expiry_time FROM client_traffics ct WHERE ct.email = clients.email AND ct.expiry_time > 0 LIMIT 1)
  184. WHERE clients.expiry_time < 0
  185. AND EXISTS (SELECT 1 FROM client_traffics ct WHERE ct.email = clients.email AND ct.expiry_time > 0)`,
  186. ).Error
  187. }
  188. func (s *InboundService) SetRemoteTraffic(nodeID int, snap *runtime.TrafficSnapshot, dirty bool) (bool, error) {
  189. var structuralChange bool
  190. err := submitTrafficWrite(func() error {
  191. var inner error
  192. structuralChange, inner = s.setRemoteTrafficLocked(nodeID, snap, dirty)
  193. return inner
  194. })
  195. return structuralChange, err
  196. }
  197. // GetNodeInboundTrafficTotals returns the current cumulative up/down for every
  198. // node-hosted inbound, keyed by tag. The node sync diffs successive snapshots of
  199. // this to derive per-inbound speed for the dashboard — node inbounds have no
  200. // local Xray poll to produce live deltas the way local inbounds do.
  201. func (s *InboundService) GetNodeInboundTrafficTotals() (map[string][2]int64, error) {
  202. var rows []struct {
  203. Tag string
  204. Up int64
  205. Down int64
  206. }
  207. if err := database.GetDB().Table("inbounds").
  208. Select("tag, up, down").
  209. Where("node_id IS NOT NULL").
  210. Scan(&rows).Error; err != nil {
  211. return nil, err
  212. }
  213. out := make(map[string][2]int64, len(rows))
  214. for _, r := range rows {
  215. out[r.Tag] = [2]int64{r.Up, r.Down}
  216. }
  217. return out, nil
  218. }
  219. func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.TrafficSnapshot, dirty bool) (bool, error) {
  220. if snap == nil || nodeID <= 0 {
  221. return false, nil
  222. }
  223. db := database.GetDB()
  224. now := time.Now().UnixMilli()
  225. // originGuidFor attributes a synced inbound to the panel that physically
  226. // hosts it. A node's OWN inbounds report either an empty origin or — on
  227. // builds that set it locally — the node's own panelGuid; both resolve to
  228. // selfKey, which is the node's panelGuid unless that GUID is ambiguous
  229. // (shared with another node or the master, i.e. a cloned server), in which
  230. // case it falls back to the node-unique id so #4983 attribution doesn't
  231. // collapse two physical nodes into one bucket. Only a DIFFERENT, non-empty
  232. // origin (an inbound the node forwards from its own sub-node) is kept as-is,
  233. // so a chained Node1->Node2->Node3 still attributes Node3's inbounds to Node3.
  234. var nodeRow model.Node
  235. db.Select("guid").Where("id = ?", nodeID).First(&nodeRow)
  236. selfKey := effectiveNodeKey(&model.Node{Id: nodeID, Guid: nodeRow.Guid})
  237. guidShared := nodeRow.Guid != "" && selfKey != nodeRow.Guid
  238. originGuidFor := func(snapIb *model.Inbound) string {
  239. if snapIb.OriginNodeGuid != "" && snapIb.OriginNodeGuid != nodeRow.Guid {
  240. return snapIb.OriginNodeGuid
  241. }
  242. return selfKey
  243. }
  244. var central []model.Inbound
  245. if err := db.Model(model.Inbound{}).
  246. Where("node_id = ?", nodeID).
  247. Find(&central).Error; err != nil {
  248. return false, err
  249. }
  250. // Index under the stored tag and its prefix-flipped form so a snap matches
  251. // whether the n<id>- prefix lives on the node side, the central side, or
  252. // neither — a mismatch must never spawn a duplicate central inbound.
  253. tagToCentral := make(map[string]*model.Inbound, len(central)*2)
  254. prefix := nodeTagPrefix(&nodeID)
  255. for i := range central {
  256. tagToCentral[central[i].Tag] = &central[i]
  257. if prefix != "" {
  258. if stripped, found := strings.CutPrefix(central[i].Tag, prefix); found {
  259. tagToCentral[stripped] = &central[i]
  260. } else {
  261. tagToCentral[prefix+central[i].Tag] = &central[i]
  262. }
  263. }
  264. }
  265. var centralClientStats []xray.ClientTraffic
  266. if len(central) > 0 {
  267. ids := make([]int, 0, len(central))
  268. for i := range central {
  269. ids = append(ids, central[i].Id)
  270. }
  271. if err := db.Model(xray.ClientTraffic{}).
  272. Where("inbound_id IN ?", ids).
  273. Find(&centralClientStats).Error; err != nil {
  274. return false, err
  275. }
  276. }
  277. type csKey struct {
  278. inboundID int
  279. email string
  280. }
  281. centralCS := make(map[csKey]*xray.ClientTraffic, len(centralClientStats))
  282. centralCSByEmail := make(map[string]*xray.ClientTraffic, len(centralClientStats))
  283. for i := range centralClientStats {
  284. centralCS[csKey{centralClientStats[i].InboundId, centralClientStats[i].Email}] = &centralClientStats[i]
  285. centralCSByEmail[centralClientStats[i].Email] = &centralClientStats[i]
  286. }
  287. nodeBaselines := make(map[string]nodeTrafficCounter)
  288. var baselineRows []model.NodeClientTraffic
  289. if err := db.Model(&model.NodeClientTraffic{}).
  290. Where("node_id = ?", nodeID).
  291. Find(&baselineRows).Error; err != nil {
  292. return false, err
  293. }
  294. for i := range baselineRows {
  295. nodeBaselines[baselineRows[i].Email] = nodeTrafficCounter{Up: baselineRows[i].Up, Down: baselineRows[i].Down}
  296. }
  297. var defaultUserId int
  298. if len(central) > 0 {
  299. defaultUserId = central[0].UserId
  300. } else {
  301. var u model.User
  302. if err := db.Model(model.User{}).Order("id asc").First(&u).Error; err == nil {
  303. defaultUserId = u.Id
  304. } else {
  305. defaultUserId = 1
  306. }
  307. }
  308. // Union of every email the snapshot still reports, across all inbounds.
  309. // The (node, email) baseline rows are keyed per node, not per inbound, so
  310. // the sweeps below must only drop one when the email left the node
  311. // entirely — an email whose stats moved to (or always lived under) a
  312. // sibling inbound still needs its baseline for the sibling's delta
  313. // computation (#5202).
  314. //
  315. // Xray counts traffic per email, not per inbound, so a multi-attached
  316. // client's shared counter is copied onto every inbound it's on. Fold each
  317. // email to its per-field max (nodeEmailTotals) so divergent copies can't make
  318. // the reset clamp re-add a lower sibling as fresh traffic (#5274).
  319. snapEmailsAll := make(map[string]struct{})
  320. nodeEmailTotals := make(map[string]nodeTrafficCounter)
  321. for _, snapIb := range snap.Inbounds {
  322. if snapIb == nil {
  323. continue
  324. }
  325. for i := range snapIb.ClientStats {
  326. email := snapIb.ClientStats[i].Email
  327. snapEmailsAll[email] = struct{}{}
  328. cur := nodeEmailTotals[email]
  329. if snapIb.ClientStats[i].Up > cur.Up {
  330. cur.Up = snapIb.ClientStats[i].Up
  331. }
  332. if snapIb.ClientStats[i].Down > cur.Down {
  333. cur.Down = snapIb.ClientStats[i].Down
  334. }
  335. nodeEmailTotals[email] = cur
  336. }
  337. }
  338. // Membership set for the rowExists checks below. Only the snapshot's emails
  339. // are ever probed, so scope the lookup to those instead of plucking the whole
  340. // client_traffics table (50k+ rows) on every node poll.
  341. existingEmails := make(map[string]struct{}, len(snapEmailsAll))
  342. if len(snapEmailsAll) > 0 {
  343. snapEmailList := make([]string, 0, len(snapEmailsAll))
  344. for email := range snapEmailsAll {
  345. snapEmailList = append(snapEmailList, email)
  346. }
  347. for _, batch := range chunkStrings(snapEmailList, sqliteMaxVars) {
  348. var found []string
  349. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Pluck("email", &found).Error; err != nil {
  350. return false, err
  351. }
  352. for _, e := range found {
  353. existingEmails[e] = struct{}{}
  354. }
  355. }
  356. }
  357. tx := db.Begin()
  358. committed := false
  359. defer func() {
  360. if !committed {
  361. tx.Rollback()
  362. }
  363. }()
  364. structuralChange := false
  365. newInboundIDs := make(map[int]struct{})
  366. snapTags := make(map[string]struct{}, len(snap.Inbounds))
  367. for _, snapIb := range snap.Inbounds {
  368. if snapIb == nil {
  369. continue
  370. }
  371. snapTags[snapIb.Tag] = struct{}{}
  372. // Record the prefix-flipped form too so the orphan sweep below keeps a
  373. // central inbound whether its tag carries the n<id>- prefix or not.
  374. if prefix != "" {
  375. if stripped, found := strings.CutPrefix(snapIb.Tag, prefix); found {
  376. snapTags[stripped] = struct{}{}
  377. } else {
  378. snapTags[prefix+snapIb.Tag] = struct{}{}
  379. }
  380. }
  381. c, ok := tagToCentral[snapIb.Tag]
  382. if !ok {
  383. if dirty {
  384. continue
  385. }
  386. // Try snap.Tag first; on collision fall back to the n<id>-
  387. // prefixed form so local+node can both own the same port.
  388. pickFreeTag := func() (string, error) {
  389. candidates := []string{snapIb.Tag}
  390. if prefix != "" && !strings.HasPrefix(snapIb.Tag, prefix) {
  391. candidates = append(candidates, prefix+snapIb.Tag)
  392. }
  393. for _, t := range candidates {
  394. var owner model.Inbound
  395. err := tx.Where("tag = ?", t).First(&owner).Error
  396. if errors.Is(err, gorm.ErrRecordNotFound) {
  397. return t, nil
  398. }
  399. if err != nil {
  400. return "", err
  401. }
  402. }
  403. return "", nil
  404. }
  405. chosenTag, err := pickFreeTag()
  406. if err != nil {
  407. logger.Warningf("setRemoteTraffic: check tag %q failed: %v", snapIb.Tag, err)
  408. continue
  409. }
  410. if chosenTag == "" {
  411. key := fmt.Sprintf("%d:%s", nodeID, snapIb.Tag)
  412. if _, seen := reportedRemoteTagConflict.LoadOrStore(key, struct{}{}); !seen {
  413. logger.Warningf(
  414. "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)",
  415. snapIb.Tag, nodeID, nodeID,
  416. )
  417. }
  418. continue
  419. }
  420. reportedRemoteTagConflict.Delete(fmt.Sprintf("%d:%s", nodeID, snapIb.Tag))
  421. newIb := model.Inbound{
  422. UserId: defaultUserId,
  423. NodeID: &nodeID,
  424. OriginNodeGuid: originGuidFor(snapIb),
  425. Tag: chosenTag,
  426. Listen: snapIb.Listen,
  427. Port: snapIb.Port,
  428. Protocol: snapIb.Protocol,
  429. Settings: snapIb.Settings,
  430. StreamSettings: snapIb.StreamSettings,
  431. Sniffing: snapIb.Sniffing,
  432. TrafficReset: snapIb.TrafficReset,
  433. LastTrafficResetTime: snapIb.LastTrafficResetTime,
  434. Enable: snapIb.Enable,
  435. Remark: snapIb.Remark,
  436. SubSortIndex: normalizeSubSortIndex(snapIb.SubSortIndex),
  437. Total: snapIb.Total,
  438. ExpiryTime: snapIb.ExpiryTime,
  439. Up: snapIb.Up,
  440. Down: snapIb.Down,
  441. ShareAddrStrategy: "node",
  442. }
  443. if err := tx.Create(&newIb).Error; err != nil {
  444. logger.Warningf("setRemoteTraffic: create central inbound for tag %q failed: %v", snapIb.Tag, err)
  445. continue
  446. }
  447. tagToCentral[snapIb.Tag] = &newIb
  448. if newIb.Tag != snapIb.Tag {
  449. tagToCentral[newIb.Tag] = &newIb
  450. }
  451. newInboundIDs[newIb.Id] = struct{}{}
  452. structuralChange = true
  453. continue
  454. }
  455. inGrace := c.LastTrafficResetTime > 0 && now-c.LastTrafficResetTime < resetGracePeriodMs
  456. // Adopting the node's settings verbatim would re-add a client the master
  457. // deleted moments ago if this snapshot was fetched before the deletion
  458. // push landed — filter just-deleted emails out while their tombstone lives.
  459. adoptedSettings := snapIb.Settings
  460. if stripped, changed := stripTombstonedClients(adoptedSettings); changed {
  461. adoptedSettings = stripped
  462. }
  463. updates := map[string]any{}
  464. if !dirty {
  465. updates["enable"] = snapIb.Enable
  466. updates["remark"] = snapIb.Remark
  467. updates["sub_sort_index"] = normalizeSubSortIndex(snapIb.SubSortIndex)
  468. updates["listen"] = snapIb.Listen
  469. updates["port"] = snapIb.Port
  470. updates["protocol"] = snapIb.Protocol
  471. updates["total"] = snapIb.Total
  472. updates["expiry_time"] = snapIb.ExpiryTime
  473. updates["settings"] = adoptedSettings
  474. updates["stream_settings"] = snapIb.StreamSettings
  475. updates["sniffing"] = snapIb.Sniffing
  476. updates["traffic_reset"] = snapIb.TrafficReset
  477. updates["last_traffic_reset_time"] = snapIb.LastTrafficResetTime
  478. }
  479. if !inGrace || (snapIb.Up+snapIb.Down) <= (c.Up+c.Down) {
  480. updates["up"] = snapIb.Up
  481. updates["down"] = snapIb.Down
  482. }
  483. // Physical-home attribution is independent of config-dirty state, so
  484. // keep it current even while the node has pending offline edits. Writes
  485. // once to backfill an existing row, then stays equal (#4983).
  486. if og := originGuidFor(snapIb); c.OriginNodeGuid != og {
  487. updates["origin_node_guid"] = og
  488. }
  489. if !dirty && (c.Settings != adoptedSettings ||
  490. c.Remark != snapIb.Remark ||
  491. c.Listen != snapIb.Listen ||
  492. c.Port != snapIb.Port ||
  493. c.Total != snapIb.Total ||
  494. c.ExpiryTime != snapIb.ExpiryTime ||
  495. c.Enable != snapIb.Enable) {
  496. structuralChange = true
  497. }
  498. if len(updates) > 0 {
  499. if err := tx.Model(model.Inbound{}).
  500. Where("id = ?", c.Id).
  501. Updates(updates).Error; err != nil {
  502. return false, err
  503. }
  504. }
  505. }
  506. for _, c := range central {
  507. if dirty {
  508. continue
  509. }
  510. if len(snapTags) == 0 {
  511. // A node mid-restart or with a transient DB error can return an empty
  512. // inbound list with success=true. Treat "zero inbounds reported" as
  513. // "nothing to say", not "delete all my inbounds" — otherwise a blip
  514. // wipes the node's central inbounds and every client on them (and
  515. // resets traffic history on re-create). A real per-inbound deletion
  516. // still sweeps, because the node keeps reporting its other inbounds.
  517. continue
  518. }
  519. if _, kept := snapTags[c.Tag]; kept {
  520. continue
  521. }
  522. var goneEmails []string
  523. if err := tx.Model(xray.ClientTraffic{}).
  524. Where("inbound_id = ?", c.Id).
  525. Pluck("email", &goneEmails).Error; err != nil {
  526. return false, err
  527. }
  528. if len(goneEmails) > 0 {
  529. // Baselines are per (node, email), not per inbound: keep them for
  530. // emails the snapshot still reports under a sibling inbound (#5202).
  531. baselineGone := make([]string, 0, len(goneEmails))
  532. for _, e := range goneEmails {
  533. if _, still := snapEmailsAll[e]; !still {
  534. baselineGone = append(baselineGone, e)
  535. }
  536. }
  537. // Chunk to avoid SQLite bind var limit when a node has many clients
  538. // removed (e.g. after API bulk delete or structural change on node inbound).
  539. for _, batch := range chunkStrings(baselineGone, sqliteMaxVars) {
  540. if err := tx.Where("node_id = ? AND email IN ?", nodeID, batch).
  541. Delete(&model.NodeClientTraffic{}).Error; err != nil {
  542. return false, err
  543. }
  544. }
  545. // The per-email row is the shared accumulator across every inbound
  546. // (and node) the email is attached to. Only drop it when this was the
  547. // email's last inbound — wiping it while a sibling still feeds it
  548. // loses the summed history, and the next node sync would re-seed the
  549. // row with that node's counter alone.
  550. sharedEmails, sErr := s.emailsUsedByOtherInbounds(goneEmails, c.Id)
  551. if sErr != nil {
  552. return false, sErr
  553. }
  554. delEmails := make([]string, 0, len(goneEmails))
  555. for _, e := range goneEmails {
  556. if !sharedEmails[strings.ToLower(strings.TrimSpace(e))] {
  557. delEmails = append(delEmails, e)
  558. }
  559. }
  560. for _, batch := range chunkStrings(delEmails, sqliteMaxVars) {
  561. if err := tx.Where("inbound_id = ? AND email IN ?", c.Id, batch).
  562. Delete(&xray.ClientTraffic{}).Error; err != nil {
  563. return false, err
  564. }
  565. }
  566. }
  567. if err := s.clientService.DetachInbound(tx, c.Id); err != nil {
  568. return false, err
  569. }
  570. if err := tx.Where("id = ?", c.Id).
  571. Delete(&model.Inbound{}).Error; err != nil {
  572. return false, err
  573. }
  574. delete(tagToCentral, c.Tag)
  575. structuralChange = true
  576. }
  577. for _, snapIb := range snap.Inbounds {
  578. if snapIb == nil {
  579. continue
  580. }
  581. c, ok := tagToCentral[snapIb.Tag]
  582. if !ok {
  583. continue
  584. }
  585. snapEmails := make(map[string]struct{}, len(snapIb.ClientStats))
  586. for _, cs := range snapIb.ClientStats {
  587. snapEmails[cs.Email] = struct{}{}
  588. // Node-wide total, not this inbound's possibly-stale copy (#5274).
  589. canon := nodeEmailTotals[cs.Email]
  590. base, seen := nodeBaselines[cs.Email]
  591. var deltaUp, deltaDown int64
  592. if seen {
  593. if deltaUp = canon.Up - base.Up; deltaUp < 0 {
  594. deltaUp = 0
  595. }
  596. if deltaDown = canon.Down - base.Down; deltaDown < 0 {
  597. deltaDown = 0
  598. }
  599. }
  600. if _, rowExists := existingEmails[cs.Email]; !rowExists {
  601. if dirty {
  602. continue
  603. }
  604. _, isNewInbound := newInboundIDs[c.Id]
  605. // On a known inbound a missing row plus a live tombstone means the
  606. // master just deleted this client and the snapshot predates the
  607. // deletion push — recreating the row (at zero) would resurrect the
  608. // client. A freshly adopted inbound still gets its row (seeded at
  609. // zero) so adoption semantics stay intact.
  610. if !isNewInbound && isClientEmailTombstoned(cs.Email) {
  611. continue
  612. }
  613. var seedUp, seedDown int64
  614. if isNewInbound && !isClientEmailTombstoned(cs.Email) {
  615. seedUp, seedDown = canon.Up, canon.Down
  616. }
  617. row := &xray.ClientTraffic{
  618. InboundId: c.Id,
  619. Email: cs.Email,
  620. Enable: cs.Enable,
  621. Total: cs.Total,
  622. ExpiryTime: cs.ExpiryTime,
  623. Reset: cs.Reset,
  624. Up: seedUp,
  625. Down: seedDown,
  626. LastOnline: cs.LastOnline,
  627. }
  628. if err := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "email"}}, DoNothing: true}).
  629. Create(row).Error; err != nil {
  630. return false, err
  631. }
  632. centralCS[csKey{c.Id, cs.Email}] = row
  633. centralCSByEmail[cs.Email] = row
  634. existingEmails[cs.Email] = struct{}{}
  635. structuralChange = true
  636. if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon.Up, canon.Down); err != nil {
  637. return false, err
  638. }
  639. nodeBaselines[cs.Email] = nodeTrafficCounter{Up: canon.Up, Down: canon.Down}
  640. continue
  641. }
  642. if existing := centralCSByEmail[cs.Email]; existing != nil &&
  643. (existing.Enable != cs.Enable ||
  644. existing.Total != cs.Total ||
  645. existing.ExpiryTime != mergeActivationExpiry(existing.ExpiryTime, cs.ExpiryTime) ||
  646. existing.Reset != cs.Reset) {
  647. structuralChange = true
  648. }
  649. enableExpr := database.ClientTrafficEnableMergeExpr()
  650. // expiry_time merge mirrors mergeActivationExpiry: a node that has not
  651. // yet seen the client's first connection keeps reporting the negative
  652. // "start after first connect" duration, which must never reset the
  653. // absolute deadline another node already activated. A positive node
  654. // value is still adopted (e.g. auto-renew moves the deadline forward).
  655. // CAST(? AS BIGINT): in the `<= 0` comparison Postgres would otherwise
  656. // infer int4 from the literal and overflow on real expiry values.
  657. if err := tx.Exec(
  658. fmt.Sprintf(
  659. `UPDATE client_traffics
  660. SET up = up + ?, down = down + ?, enable = %s, total = ?,
  661. expiry_time = CASE WHEN expiry_time > 0 AND CAST(? AS BIGINT) <= 0 THEN expiry_time ELSE CAST(? AS BIGINT) END,
  662. reset = ?, last_online = %s
  663. WHERE email = ?`,
  664. enableExpr,
  665. database.GreatestExpr("last_online", "?"),
  666. ),
  667. deltaUp, deltaDown, cs.Enable, cs.Total,
  668. cs.ExpiryTime, cs.ExpiryTime, cs.Reset,
  669. cs.LastOnline, cs.Email,
  670. ).Error; err != nil {
  671. return false, err
  672. }
  673. if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon.Up, canon.Down); err != nil {
  674. return false, err
  675. }
  676. nodeBaselines[cs.Email] = nodeTrafficCounter{Up: canon.Up, Down: canon.Down}
  677. }
  678. for k, existing := range centralCS {
  679. if dirty {
  680. continue
  681. }
  682. if k.inboundID != c.Id {
  683. continue
  684. }
  685. if _, kept := snapEmails[k.email]; kept {
  686. continue
  687. }
  688. // Gone from this inbound's stats but still reported by the node under
  689. // a sibling inbound: both the shared accumulator row and the (node,
  690. // email) baseline must survive, or the sibling's next delta would
  691. // compute against nothing and freeze the counter (#5202).
  692. if _, still := snapEmailsAll[k.email]; still {
  693. continue
  694. }
  695. if err := tx.Where("node_id = ? AND email = ?", nodeID, existing.Email).
  696. Delete(&model.NodeClientTraffic{}).Error; err != nil {
  697. return false, err
  698. }
  699. // Same shared-accumulator rule as the inbound-removal sweep above:
  700. // keep the row while another inbound still references the email.
  701. stillUsed, uErr := s.emailUsedByOtherInbounds(existing.Email, c.Id)
  702. if uErr != nil {
  703. return false, uErr
  704. }
  705. if !stillUsed {
  706. if err := tx.Where("inbound_id = ? AND email = ?", c.Id, existing.Email).
  707. Delete(&xray.ClientTraffic{}).Error; err != nil {
  708. return false, err
  709. }
  710. }
  711. structuralChange = true
  712. }
  713. }
  714. type oldSet struct {
  715. inboundID int
  716. emails map[string]struct{}
  717. }
  718. var perInboundOld []oldSet
  719. for _, snapIb := range snap.Inbounds {
  720. if snapIb == nil {
  721. continue
  722. }
  723. c, ok := tagToCentral[snapIb.Tag]
  724. if !ok {
  725. continue
  726. }
  727. if dirty {
  728. continue
  729. }
  730. var oldEmailsRows []string
  731. if err := tx.Table("clients").
  732. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  733. Where("client_inbounds.inbound_id = ?", c.Id).
  734. Pluck("email", &oldEmailsRows).Error; err == nil {
  735. oldEmails := make(map[string]struct{}, len(oldEmailsRows))
  736. for _, e := range oldEmailsRows {
  737. if e != "" {
  738. oldEmails[e] = struct{}{}
  739. }
  740. }
  741. perInboundOld = append(perInboundOld, oldSet{inboundID: c.Id, emails: oldEmails})
  742. }
  743. clients, gcErr := s.GetClients(snapIb)
  744. if gcErr != nil {
  745. logger.Warningf("setRemoteTraffic: parse clients for tag %q failed: %v", snapIb.Tag, gcErr)
  746. continue
  747. }
  748. csEnableByEmail := make(map[string]bool, len(snapIb.ClientStats))
  749. for _, cs := range snapIb.ClientStats {
  750. csEnableByEmail[cs.Email] = cs.Enable
  751. }
  752. filtered := clients[:0]
  753. for i := range clients {
  754. if isClientEmailTombstoned(clients[i].Email) {
  755. continue
  756. }
  757. if cse, hit := csEnableByEmail[clients[i].Email]; hit && !cse {
  758. clients[i].Enable = false
  759. }
  760. filtered = append(filtered, clients[i])
  761. }
  762. localEmails := make([]string, 0, len(filtered))
  763. for i := range filtered {
  764. if filtered[i].Email != "" {
  765. localEmails = append(localEmails, filtered[i].Email)
  766. }
  767. }
  768. if len(localEmails) > 0 {
  769. var localMeta []struct {
  770. Email string
  771. Comment string `gorm:"column:comment"`
  772. }
  773. if err := tx.Table("clients").
  774. Select("email, comment").
  775. Where("email IN ?", localEmails).
  776. Find(&localMeta).Error; err == nil {
  777. commentByEmail := make(map[string]string, len(localMeta))
  778. for _, m := range localMeta {
  779. commentByEmail[m.Email] = m.Comment
  780. }
  781. for i := range filtered {
  782. if cmt, ok := commentByEmail[filtered[i].Email]; ok {
  783. filtered[i].Comment = cmt
  784. }
  785. }
  786. }
  787. }
  788. if err := s.clientService.SyncInbound(tx, c.Id, filtered); err != nil {
  789. logger.Warningf("setRemoteTraffic: sync clients for tag %q failed: %v", snapIb.Tag, err)
  790. }
  791. }
  792. for _, old := range perInboundOld {
  793. var stillAttached []string
  794. if err := tx.Table("clients").
  795. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  796. Where("client_inbounds.inbound_id = ?", old.inboundID).
  797. Pluck("email", &stillAttached).Error; err != nil {
  798. continue
  799. }
  800. stillSet := make(map[string]struct{}, len(stillAttached))
  801. for _, e := range stillAttached {
  802. stillSet[e] = struct{}{}
  803. }
  804. for email := range old.emails {
  805. if _, kept := stillSet[email]; kept {
  806. continue
  807. }
  808. var attachmentCount int64
  809. if err := tx.Table("client_inbounds").
  810. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  811. Where("clients.email = ?", email).
  812. Count(&attachmentCount).Error; err != nil {
  813. continue
  814. }
  815. if attachmentCount > 0 {
  816. continue
  817. }
  818. if err := tx.Where("email = ?", email).Delete(&model.ClientRecord{}).Error; err != nil {
  819. logger.Warningf("setRemoteTraffic: delete ClientRecord %q failed: %v", email, err)
  820. }
  821. if err := tx.Where("email = ?", email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  822. logger.Warningf("setRemoteTraffic: delete ClientTraffic %q failed: %v", email, err)
  823. }
  824. if err := tx.Where("email = ?", email).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  825. logger.Warningf("setRemoteTraffic: delete NodeClientTraffic %q failed: %v", email, err)
  826. }
  827. structuralChange = true
  828. }
  829. }
  830. if err := liftActivatedClientRecordExpiries(tx); err != nil {
  831. logger.Warning("setRemoteTraffic: lift activated expiries failed:", err)
  832. }
  833. if err := tx.Commit().Error; err != nil {
  834. return false, err
  835. }
  836. committed = true
  837. if p != nil {
  838. tree := snap.OnlineTree
  839. switch {
  840. case len(tree) == 0 && len(snap.OnlineEmails) > 0:
  841. // Old-build node (no GUID tree): key its flat online list under its
  842. // own effective identity so attribution still works for that branch.
  843. tree = map[string][]string{selfKey: snap.OnlineEmails}
  844. case guidShared && len(tree) > 0:
  845. // Newer cloned node: its own clients arrive keyed under the shared
  846. // panelGuid. Remap just that entry to the node-unique key so the
  847. // clones don't merge; descendant subtrees keep their distinct GUIDs.
  848. if _, ok := tree[nodeRow.Guid]; ok {
  849. remapped := make(map[string][]string, len(tree))
  850. for g, emails := range tree {
  851. if g == nodeRow.Guid {
  852. g = selfKey
  853. }
  854. remapped[g] = emails
  855. }
  856. tree = remapped
  857. }
  858. }
  859. p.SetNodeOnlineTree(nodeID, tree)
  860. }
  861. return structuralChange, nil
  862. }
  863. func (s *InboundService) GetOnlineClients() []string {
  864. if p == nil {
  865. return []string{}
  866. }
  867. return p.GetOnlineClients()
  868. }
  869. // GetOnlineClientsByGuid returns online emails keyed by the panelGuid of the
  870. // node that physically hosts each set: this panel's own clients under its own
  871. // GUID, plus every node in the tree under its GUID (#4983). Replaces the old
  872. // node-id keying so a client three hops down is attributed to its real node,
  873. // not the intermediate one it was synced through.
  874. func (s *InboundService) GetOnlineClientsByGuid() map[string][]string {
  875. if p == nil {
  876. return map[string][]string{}
  877. }
  878. out := p.GetMergedNodeTrees()
  879. if local := p.GetLocalOnlineClients(); len(local) > 0 {
  880. if guid := s.panelGuid(); guid != "" {
  881. out[guid] = mergeEmails(out[guid], local)
  882. }
  883. }
  884. return out
  885. }
  886. // GetActiveInboundsByGuid returns the inbound tags that carried traffic within
  887. // the grace window for THIS panel, under its own GUID. Remote nodes don't
  888. // report per-inbound activity, so a GUID missing from the map means "don't
  889. // gate" for that node's inbounds.
  890. func (s *InboundService) GetActiveInboundsByGuid() map[string][]string {
  891. if p == nil {
  892. return map[string][]string{}
  893. }
  894. active := p.GetLocalActiveInbounds()
  895. if len(active) == 0 {
  896. return map[string][]string{}
  897. }
  898. guid := s.panelGuid()
  899. if guid == "" {
  900. return map[string][]string{}
  901. }
  902. return map[string][]string{guid: active}
  903. }
  904. func (s *InboundService) SetNodeOnlineTree(nodeID int, tree map[string][]string) {
  905. if p != nil {
  906. p.SetNodeOnlineTree(nodeID, tree)
  907. }
  908. }
  909. func (s *InboundService) ClearNodeOnlineClients(nodeID int) {
  910. if p != nil {
  911. p.ClearNodeOnlineClients(nodeID)
  912. }
  913. }
  914. // panelGuid returns this panel's stable self-identifier, used to key the local
  915. // panel's own clients in the per-node online maps (#4983).
  916. func (s *InboundService) panelGuid() string {
  917. guid, _ := (&SettingService{}).GetPanelGuid()
  918. return guid
  919. }
  920. // synthNodeGuid is the stable per-node fallback identity for a directly-attached
  921. // node whose panel hasn't reported a panelGuid yet (old build). Node ids are
  922. // master-local, so this only composes for direct nodes — exactly the pre-#4983
  923. // flat-topology case where an old-build node appears.
  924. func synthNodeGuid(nodeID int) string {
  925. return fmt.Sprintf("node:%d", nodeID)
  926. }
  927. // mergeEmails returns the deduped union of two email slices.
  928. func mergeEmails(a, b []string) []string {
  929. if len(a) == 0 {
  930. return b
  931. }
  932. seen := make(map[string]struct{}, len(a)+len(b))
  933. out := make([]string, 0, len(a)+len(b))
  934. for _, e := range a {
  935. if _, ok := seen[e]; !ok {
  936. seen[e] = struct{}{}
  937. out = append(out, e)
  938. }
  939. }
  940. for _, e := range b {
  941. if _, ok := seen[e]; !ok {
  942. seen[e] = struct{}{}
  943. out = append(out, e)
  944. }
  945. }
  946. return out
  947. }
  948. func (s *InboundService) GetClientsLastOnline() (map[string]int64, error) {
  949. db := database.GetDB()
  950. var rows []xray.ClientTraffic
  951. err := db.Model(&xray.ClientTraffic{}).Select("email, last_online").Find(&rows).Error
  952. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  953. return nil, err
  954. }
  955. result := make(map[string]int64, len(rows))
  956. for _, r := range rows {
  957. result[r.Email] = r.LastOnline
  958. }
  959. return result, nil
  960. }
  961. // RefreshLocalOnlineClients folds the emails and inbound tags active on this
  962. // panel's own xray this poll into the local online/active sets, applying the
  963. // grace window and pruning stale entries. Pass nil to only prune. See
  964. // xray.Process for why the local sets are kept separate from the shared
  965. // last_online column.
  966. func (s *InboundService) RefreshLocalOnlineClients(activeEmails, activeInboundTags []string) {
  967. if p != nil {
  968. p.RefreshLocalOnline(activeEmails, activeInboundTags, time.Now().UnixMilli(), onlineGracePeriodMs)
  969. }
  970. }
  971. func (s *InboundService) FilterAndSortClientEmails(emails []string) ([]string, []string, error) {
  972. db := database.GetDB()
  973. // Step 1: Get ClientTraffic records for emails in the input list.
  974. // Chunked to stay under SQLite's bind-variable limit on huge inputs.
  975. uniqEmails := uniqueNonEmptyStrings(emails)
  976. clients := make([]xray.ClientTraffic, 0, len(uniqEmails))
  977. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  978. var page []xray.ClientTraffic
  979. if err := db.Where("email IN ?", batch).Find(&page).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  980. return nil, nil, err
  981. }
  982. clients = append(clients, page...)
  983. }
  984. // Step 2: Sort clients by (Up + Down) descending
  985. sort.Slice(clients, func(i, j int) bool {
  986. return (clients[i].Up + clients[i].Down) > (clients[j].Up + clients[j].Down)
  987. })
  988. // Step 3: Extract sorted valid emails and track found ones
  989. validEmails := make([]string, 0, len(clients))
  990. found := make(map[string]bool)
  991. for _, client := range clients {
  992. validEmails = append(validEmails, client.Email)
  993. found[client.Email] = true
  994. }
  995. // Step 4: Identify emails that were not found in the database
  996. extraEmails := make([]string, 0)
  997. for _, email := range emails {
  998. if !found[email] {
  999. extraEmails = append(extraEmails, email)
  1000. }
  1001. }
  1002. return validEmails, extraEmails, nil
  1003. }