inbound_node.go 37 KB

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