inbound_node.go 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128
  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 = %s, down = %s, 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. database.ClampedAddExpr("up"),
  706. database.ClampedAddExpr("down"),
  707. enableExpr,
  708. database.GreatestExpr("last_online", "?"),
  709. ),
  710. deltaUp, deltaDown, cs.Enable, cs.Total,
  711. cs.ExpiryTime, cs.ExpiryTime, cs.Reset,
  712. cs.LastOnline, cs.Email,
  713. ).Error; err != nil {
  714. return false, err
  715. }
  716. if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon.Up, canon.Down); err != nil {
  717. return false, err
  718. }
  719. nodeBaselines[cs.Email] = nodeTrafficCounter{Up: canon.Up, Down: canon.Down}
  720. }
  721. for k, existing := range centralCS {
  722. if dirty {
  723. continue
  724. }
  725. if k.inboundID != c.Id {
  726. continue
  727. }
  728. if _, kept := snapEmails[k.email]; kept {
  729. continue
  730. }
  731. // Gone from this inbound's stats but still reported by the node under
  732. // a sibling inbound: both the shared accumulator row and the (node,
  733. // email) baseline must survive, or the sibling's next delta would
  734. // compute against nothing and freeze the counter (#5202).
  735. if _, still := snapEmailsAll[k.email]; still {
  736. continue
  737. }
  738. if err := tx.Where("node_id = ? AND email = ?", nodeID, existing.Email).
  739. Delete(&model.NodeClientTraffic{}).Error; err != nil {
  740. return false, err
  741. }
  742. // Same shared-accumulator rule as the inbound-removal sweep above:
  743. // keep the row while another inbound still references the email.
  744. stillUsed, uErr := s.emailUsedByOtherInbounds(existing.Email, c.Id)
  745. if uErr != nil {
  746. return false, uErr
  747. }
  748. if !stillUsed {
  749. if err := tx.Where("inbound_id = ? AND email = ?", c.Id, existing.Email).
  750. Delete(&xray.ClientTraffic{}).Error; err != nil {
  751. return false, err
  752. }
  753. }
  754. structuralChange = true
  755. }
  756. }
  757. type oldSet struct {
  758. inboundID int
  759. emails map[string]struct{}
  760. }
  761. var perInboundOld []oldSet
  762. for _, snapIb := range snap.Inbounds {
  763. if snapIb == nil {
  764. continue
  765. }
  766. c, ok := tagToCentral[snapIb.Tag]
  767. if !ok {
  768. continue
  769. }
  770. if dirty {
  771. continue
  772. }
  773. var oldEmailsRows []string
  774. if err := tx.Table("clients").
  775. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  776. Where("client_inbounds.inbound_id = ?", c.Id).
  777. Pluck("email", &oldEmailsRows).Error; err == nil {
  778. oldEmails := make(map[string]struct{}, len(oldEmailsRows))
  779. for _, e := range oldEmailsRows {
  780. if e != "" {
  781. oldEmails[e] = struct{}{}
  782. }
  783. }
  784. perInboundOld = append(perInboundOld, oldSet{inboundID: c.Id, emails: oldEmails})
  785. }
  786. clients, gcErr := s.GetClients(snapIb)
  787. if gcErr != nil {
  788. logger.Warningf("setRemoteTraffic: parse clients for tag %q failed: %v", snapIb.Tag, gcErr)
  789. continue
  790. }
  791. csEnableByEmail := make(map[string]bool, len(snapIb.ClientStats))
  792. for _, cs := range snapIb.ClientStats {
  793. csEnableByEmail[cs.Email] = cs.Enable
  794. }
  795. filtered := clients[:0]
  796. for i := range clients {
  797. if isClientEmailTombstoned(clients[i].Email) {
  798. continue
  799. }
  800. if cse, hit := csEnableByEmail[clients[i].Email]; hit && !cse {
  801. clients[i].Enable = false
  802. }
  803. filtered = append(filtered, clients[i])
  804. }
  805. localEmails := make([]string, 0, len(filtered))
  806. for i := range filtered {
  807. if filtered[i].Email != "" {
  808. localEmails = append(localEmails, filtered[i].Email)
  809. }
  810. }
  811. if len(localEmails) > 0 {
  812. var localMeta []struct {
  813. Email string
  814. Comment string `gorm:"column:comment"`
  815. }
  816. if err := tx.Table("clients").
  817. Select("email, comment").
  818. Where("email IN ?", localEmails).
  819. Find(&localMeta).Error; err == nil {
  820. commentByEmail := make(map[string]string, len(localMeta))
  821. for _, m := range localMeta {
  822. commentByEmail[m.Email] = m.Comment
  823. }
  824. for i := range filtered {
  825. if cmt, ok := commentByEmail[filtered[i].Email]; ok {
  826. filtered[i].Comment = cmt
  827. }
  828. }
  829. }
  830. }
  831. if err := s.clientService.SyncInbound(tx, c.Id, filtered); err != nil {
  832. logger.Warningf("setRemoteTraffic: sync clients for tag %q failed: %v", snapIb.Tag, err)
  833. }
  834. }
  835. for _, old := range perInboundOld {
  836. var stillAttached []string
  837. if err := tx.Table("clients").
  838. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  839. Where("client_inbounds.inbound_id = ?", old.inboundID).
  840. Pluck("email", &stillAttached).Error; err != nil {
  841. continue
  842. }
  843. stillSet := make(map[string]struct{}, len(stillAttached))
  844. for _, e := range stillAttached {
  845. stillSet[e] = struct{}{}
  846. }
  847. for email := range old.emails {
  848. if _, kept := stillSet[email]; kept {
  849. continue
  850. }
  851. var attachmentCount int64
  852. if err := tx.Table("client_inbounds").
  853. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  854. Where("clients.email = ?", email).
  855. Count(&attachmentCount).Error; err != nil {
  856. continue
  857. }
  858. if attachmentCount > 0 {
  859. continue
  860. }
  861. if err := tx.Where("email = ?", email).Delete(&model.ClientRecord{}).Error; err != nil {
  862. logger.Warningf("setRemoteTraffic: delete ClientRecord %q failed: %v", email, err)
  863. }
  864. if err := tx.Where("email = ?", email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  865. logger.Warningf("setRemoteTraffic: delete ClientTraffic %q failed: %v", email, err)
  866. }
  867. if err := tx.Where("email = ?", email).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  868. logger.Warningf("setRemoteTraffic: delete NodeClientTraffic %q failed: %v", email, err)
  869. }
  870. structuralChange = true
  871. }
  872. }
  873. if err := liftActivatedClientRecordExpiries(tx); err != nil {
  874. logger.Warning("setRemoteTraffic: lift activated expiries failed:", err)
  875. }
  876. if err := tx.Commit().Error; err != nil {
  877. return false, err
  878. }
  879. committed = true
  880. if len(adoptedInbounds) > 0 {
  881. if mgr := runtime.GetManager(); mgr != nil {
  882. if rt, rtErr := mgr.RuntimeFor(&nodeID); rtErr == nil {
  883. if rem, ok := rt.(*runtime.Remote); ok {
  884. for _, ib := range adoptedInbounds {
  885. rem.RecordAdoptedInbound(ib)
  886. }
  887. }
  888. }
  889. }
  890. }
  891. if p != nil {
  892. tree := snap.OnlineTree
  893. switch {
  894. case len(tree) == 0 && len(snap.OnlineEmails) > 0:
  895. // Old-build node (no GUID tree): key its flat online list under its
  896. // own effective identity so attribution still works for that branch.
  897. tree = map[string][]string{selfKey: snap.OnlineEmails}
  898. case guidShared && len(tree) > 0:
  899. // Newer cloned node: its own clients arrive keyed under the shared
  900. // panelGuid. Remap just that entry to the node-unique key so the
  901. // clones don't merge; descendant subtrees keep their distinct GUIDs.
  902. if _, ok := tree[nodeRow.Guid]; ok {
  903. remapped := make(map[string][]string, len(tree))
  904. for g, emails := range tree {
  905. if g == nodeRow.Guid {
  906. g = selfKey
  907. }
  908. remapped[g] = emails
  909. }
  910. tree = remapped
  911. }
  912. }
  913. p.SetNodeOnlineTree(nodeID, tree)
  914. }
  915. return structuralChange, nil
  916. }
  917. func (s *InboundService) GetOnlineClients() []string {
  918. if p == nil {
  919. return []string{}
  920. }
  921. return p.GetOnlineClients()
  922. }
  923. // GetOnlineClientsByGuid returns online emails keyed by the panelGuid of the
  924. // node that physically hosts each set: this panel's own clients under its own
  925. // GUID, plus every node in the tree under its GUID (#4983). Replaces the old
  926. // node-id keying so a client three hops down is attributed to its real node,
  927. // not the intermediate one it was synced through.
  928. func (s *InboundService) GetOnlineClientsByGuid() map[string][]string {
  929. if p == nil {
  930. return map[string][]string{}
  931. }
  932. out := p.GetMergedNodeTrees()
  933. if local := p.GetLocalOnlineClients(); len(local) > 0 {
  934. if guid := s.panelGuid(); guid != "" {
  935. out[guid] = mergeEmails(out[guid], local)
  936. }
  937. }
  938. return out
  939. }
  940. // GetActiveInboundsByGuid returns the inbound tags that carried traffic within
  941. // the grace window for THIS panel, under its own GUID. Remote nodes don't
  942. // report per-inbound activity, so a GUID missing from the map means "don't
  943. // gate" for that node's inbounds.
  944. func (s *InboundService) GetActiveInboundsByGuid() map[string][]string {
  945. if p == nil {
  946. return map[string][]string{}
  947. }
  948. active := p.GetLocalActiveInbounds()
  949. if len(active) == 0 {
  950. return map[string][]string{}
  951. }
  952. guid := s.panelGuid()
  953. if guid == "" {
  954. return map[string][]string{}
  955. }
  956. return map[string][]string{guid: active}
  957. }
  958. func (s *InboundService) SetNodeOnlineTree(nodeID int, tree map[string][]string) {
  959. if p != nil {
  960. p.SetNodeOnlineTree(nodeID, tree)
  961. }
  962. }
  963. func (s *InboundService) ClearNodeOnlineClients(nodeID int) {
  964. if p != nil {
  965. p.ClearNodeOnlineClients(nodeID)
  966. }
  967. }
  968. // panelGuid returns this panel's stable self-identifier, used to key the local
  969. // panel's own clients in the per-node online maps (#4983).
  970. func (s *InboundService) panelGuid() string {
  971. guid, _ := (&SettingService{}).GetPanelGuid()
  972. return guid
  973. }
  974. // synthNodeGuid is the stable per-node fallback identity for a directly-attached
  975. // node whose panel hasn't reported a panelGuid yet (old build). Node ids are
  976. // master-local, so this only composes for direct nodes — exactly the pre-#4983
  977. // flat-topology case where an old-build node appears.
  978. func synthNodeGuid(nodeID int) string {
  979. return fmt.Sprintf("node:%d", nodeID)
  980. }
  981. // mergeEmails returns the deduped union of two email slices.
  982. func mergeEmails(a, b []string) []string {
  983. if len(a) == 0 {
  984. return b
  985. }
  986. seen := make(map[string]struct{}, len(a)+len(b))
  987. out := make([]string, 0, len(a)+len(b))
  988. for _, e := range a {
  989. if _, ok := seen[e]; !ok {
  990. seen[e] = struct{}{}
  991. out = append(out, e)
  992. }
  993. }
  994. for _, e := range b {
  995. if _, ok := seen[e]; !ok {
  996. seen[e] = struct{}{}
  997. out = append(out, e)
  998. }
  999. }
  1000. return out
  1001. }
  1002. func (s *InboundService) GetClientsLastOnline() (map[string]int64, error) {
  1003. db := database.GetDB()
  1004. var rows []xray.ClientTraffic
  1005. err := db.Model(&xray.ClientTraffic{}).Select("email, last_online").Find(&rows).Error
  1006. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1007. return nil, err
  1008. }
  1009. result := make(map[string]int64, len(rows))
  1010. for _, r := range rows {
  1011. result[r.Email] = r.LastOnline
  1012. }
  1013. return result, nil
  1014. }
  1015. // RefreshLocalOnlineClients folds the emails and inbound tags active on this
  1016. // panel's own xray this poll into the local online/active sets, applying the
  1017. // grace window and pruning stale entries. Pass nil to only prune. See
  1018. // xray.Process for why the local sets are kept separate from the shared
  1019. // last_online column.
  1020. func (s *InboundService) RefreshLocalOnlineClients(activeEmails, activeInboundTags []string) {
  1021. if p != nil {
  1022. p.RefreshLocalOnline(activeEmails, activeInboundTags, time.Now().UnixMilli(), onlineGracePeriodMs)
  1023. }
  1024. }
  1025. func (s *InboundService) FilterAndSortClientEmails(emails []string) ([]string, []string, error) {
  1026. db := database.GetDB()
  1027. // Step 1: Get ClientTraffic records for emails in the input list.
  1028. // Chunked to stay under SQLite's bind-variable limit on huge inputs.
  1029. uniqEmails := uniqueNonEmptyStrings(emails)
  1030. clients := make([]xray.ClientTraffic, 0, len(uniqEmails))
  1031. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  1032. var page []xray.ClientTraffic
  1033. if err := db.Where("email IN ?", batch).Find(&page).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1034. return nil, nil, err
  1035. }
  1036. clients = append(clients, page...)
  1037. }
  1038. // Step 2: Sort clients by (Up + Down) descending
  1039. sort.Slice(clients, func(i, j int) bool {
  1040. return (clients[i].Up + clients[i].Down) > (clients[j].Up + clients[j].Down)
  1041. })
  1042. // Step 3: Extract sorted valid emails and track found ones
  1043. validEmails := make([]string, 0, len(clients))
  1044. found := make(map[string]bool)
  1045. for _, client := range clients {
  1046. validEmails = append(validEmails, client.Email)
  1047. found[client.Email] = true
  1048. }
  1049. // Step 4: Identify emails that were not found in the database
  1050. extraEmails := make([]string, 0)
  1051. for _, email := range emails {
  1052. if !found[email] {
  1053. extraEmails = append(extraEmails, email)
  1054. }
  1055. }
  1056. return validEmails, extraEmails, nil
  1057. }