package service import ( "cmp" "context" "encoding/json" "errors" "slices" "sort" "time" "github.com/mhsanaei/3x-ui/v3/internal/database" "github.com/mhsanaei/3x-ui/v3/internal/database/model" "gorm.io/gorm" "gorm.io/gorm/clause" ) // node_client_ips.go implements per-node client-IP attribution. The flat // inbound_client_ips table is a cluster-wide union (used for IP-limit counting // and pushed back to every node), so it cannot tell which node a given IP is // on. NodeClientIp keeps that attribution: each panel records its own Xray // observations under its panelGuid, and the master merges every node's // guid-keyed report — never mixing in IPs a parent pushed down. // Attribution excludes empty addresses and keeps each fresh IP's maximum timestamp. func mergeModelClientIpEntries(old, incoming []model.ClientIpEntry, cutoff int64) []model.ClientIpEntry { ipMap := make(map[string]int64, len(old)+len(incoming)) for _, e := range old { if e.IP == "" || e.Timestamp < cutoff { continue } ipMap[e.IP] = e.Timestamp } for _, e := range incoming { if e.IP == "" || e.Timestamp < cutoff { continue } if cur, ok := ipMap[e.IP]; !ok || e.Timestamp > cur { ipMap[e.IP] = e.Timestamp } } out := make([]model.ClientIpEntry, 0, len(ipMap)) for ip, ts := range ipMap { out = append(out, model.ClientIpEntry{IP: ip, Timestamp: ts}) } return out } // Stay under SQLite's 999-parameter limit with up to five binds per row, // including the compare-and-set predicate. const nodeClientIpWriteBatch = 190 var errNodeClientIpConflict = errors.New("node client IP attribution changed during merge") type nodeClientIpChange struct { email string ips string previous *model.NodeClientIp } // upsertNodeClientIps merges fresh observations in email order and retries // the whole GUID after a concurrent write so no partial merge is committed. func upsertNodeClientIps(guid string, perEmail map[string][]model.ClientIpEntry) error { return mergeNodeClientIpAttribution(database.GetDB(), nil, guid, perEmail) } func mergeNodeClientIpAttribution(db *gorm.DB, reporter *model.Node, guid string, perEmail map[string][]model.ClientIpEntry) error { if guid == "" || len(perEmail) == 0 { return nil } emails := make([]string, 0, len(perEmail)) for email := range perEmail { if email != "" { emails = append(emails, email) } } sort.Strings(emails) cutoff := time.Now().Unix() - clientIpStaleAfterSeconds for range ClientIpCasRetries { changes, err := planNodeClientIpChanges(db, guid, emails, perEmail, cutoff) if err != nil || len(changes) == 0 { return err } err = db.Transaction(func(tx *gorm.DB) error { if reporter != nil { if err := lockOnlineNodeIPReporter(tx, reporter); err != nil { return err } } return applyNodeClientIpChanges(tx, guid, changes) }) if !errors.Is(err, errNodeClientIpConflict) { return err } } return errNodeClientIpConflict } func planNodeClientIpChanges(db *gorm.DB, guid string, emails []string, perEmail map[string][]model.ClientIpEntry, cutoff int64) ([]nodeClientIpChange, error) { var existing []model.NodeClientIp if err := db.Where("node_guid = ?", guid).Find(&existing).Error; err != nil { return nil, err } existingByEmail := make(map[string]*model.NodeClientIp, len(existing)) for i := range existing { existingByEmail[existing[i].Email] = &existing[i] } changes := make([]nodeClientIpChange, 0, len(emails)) for _, email := range emails { previous := existingByEmail[email] var old []model.ClientIpEntry if previous != nil && previous.Ips != "" { _ = json.Unmarshal([]byte(previous.Ips), &old) } merged := mergeModelClientIpEntries(old, perEmail[email], cutoff) if len(merged) == 0 { if previous != nil { changes = append(changes, nodeClientIpChange{email: email, previous: previous}) } continue } encoded, err := model.MarshalClientIpEntries(merged) if err != nil { return nil, err } if previous == nil || previous.Ips != encoded { changes = append(changes, nodeClientIpChange{email: email, ips: encoded, previous: previous}) } } return changes, nil } func applyNodeClientIpChanges(tx *gorm.DB, guid string, changes []nodeClientIpChange) error { for start := 0; start < len(changes); { deleting := changes[start].ips == "" end := start + 1 // A multi-row DELETE does not guarantee row-lock order on PostgreSQL. for !deleting && end < min(start+nodeClientIpWriteBatch, len(changes)) && changes[end].ips != "" { end++ } batch := changes[start:end] expected := make([]clause.Expression, 0, len(batch)) previousIDs := make(map[string]int, len(batch)) for _, change := range batch { if change.previous != nil { expected = append(expected, nodeClientIpSnapshot(*change.previous)) previousIDs[change.email] = change.previous.Id } } var result *gorm.DB var rows []model.NodeClientIp if deleting { result = tx.Where(expected[0]).Delete(&model.NodeClientIp{}) } else { rows = make([]model.NodeClientIp, 0, len(batch)) for _, change := range batch { rows = append(rows, model.NodeClientIp{NodeGuid: guid, Email: change.email, Ips: change.ips}) } conflict := clause.OnConflict{ Columns: []clause.Column{{Name: "node_guid"}, {Name: "email"}}, DoNothing: len(expected) == 0, } // For DO NOTHING, GORM skips nonzero RETURNING fields in the // input slice. Only the generated ID starts out unset. returning := clause.Returning{Columns: []clause.Column{{Name: "id"}}} if !conflict.DoNothing { conflict.DoUpdates = clause.AssignmentColumns([]string{"ips"}) conflict.Where = clause.Where{Exprs: []clause.Expression{clause.Or(expected...)}} returning.Columns = append(returning.Columns, clause.Column{Name: "email"}) } result = tx.Clauses(conflict, returning).Create(&rows) } if result.Error != nil { return result.Error } if result.RowsAffected != int64(len(batch)) { return errNodeClientIpConflict } // An existing row can be deleted after the read. A replacement ID // requires a retry so the new row cannot inherit the deleted IPs. for _, row := range rows { if id, existed := previousIDs[row.Email]; existed && row.Id != id { return errNodeClientIpConflict } } start = end } return nil } func nodeClientIpSnapshot(row model.NodeClientIp) clause.Expression { id := clause.Column{Table: clause.CurrentTable, Name: "id"} ips := clause.Column{Table: clause.CurrentTable, Name: "ips"} content := clause.Expression(clause.Eq{Column: ips, Value: row.Ips}) if row.Ips == "" { content = clause.Or(content, clause.Eq{Column: ips, Value: nil}) } return clause.And(clause.Eq{Column: id, Value: row.Id}, content) } // ErrIneligibleNodeIPReport identifies work invalidated while in flight. var ErrIneligibleNodeIPReport = errors.New("node IP report is no longer eligible") // Keep the reporter stable through commit. The flat PostgreSQL merge calls // this after its IP writes. Attribution and node deletion lock the node first. func lockOnlineNodeIPReporter(tx *gorm.DB, reporter *model.Node) error { var current model.Node query := tx.Select("id", "guid", "scheme", "address", "port", "base_path"). Where("id = ? AND enable = ? AND status = ?", reporter.Id, true, "online") if tx.Name() == database.DialectPostgres { query = query.Clauses(clause.Locking{Strength: "SHARE"}) } if err := query.Take(¤t).Error; err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return ErrIneligibleNodeIPReport } return err } if current.Guid != reporter.Guid || current.Scheme != reporter.Scheme || current.Address != reporter.Address || current.Port != reporter.Port || current.BasePath != reporter.BasePath { return ErrIneligibleNodeIPReport } return nil } // RecordLocalClientIps stores the scanner's local observations under this panel's GUID. func (s *InboundService) RecordLocalClientIps(panelGuid string, observed map[string][]model.ClientIpEntry) error { return upsertNodeClientIps(panelGuid, observed) } // MergeClientIpsByGuid folds a node's guid-keyed attribution report (its own // panelGuid subtree plus any descendants) into the local table, preserving which // physical node each IP is on across a chain. When node is non-nil and its own // panelGuid is ambiguous (shared with another node or the master — a cloned // server), the node's own subtree is remapped to its node-unique key so two // clones don't collapse into one attribution row; descendant subtrees keep their // distinct GUIDs. A nil node merges the report verbatim. func (s *InboundService) MergeClientIpsByGuid(node *model.Node, trees map[string]map[string][]model.ClientIpEntry) error { return mergeClientIpsByGuid(database.GetDB(), node, trees, false) } // MergePolledClientIpsByGuid commits a node report only while its reporter is eligible. func (s *InboundService) MergePolledClientIpsByGuid(ctx context.Context, node *model.Node, trees map[string]map[string][]model.ClientIpEntry) error { return mergeClientIpsByGuid(database.GetDB().WithContext(ctx), node, trees, true) } func mergeClientIpsByGuid(db *gorm.DB, node *model.Node, trees map[string]map[string][]model.ClientIpEntry, checkReporter bool) error { if node != nil && node.Guid != "" { if eff := effectiveNodeKey(node); eff != node.Guid { if sub, ok := trees[node.Guid]; ok { delete(trees, node.Guid) if existing, ok := trees[eff]; ok { for email, ips := range sub { existing[email] = append(existing[email], ips...) } } else { trees[eff] = sub } } } } if node != nil { scoped, err := scopeNodeClientIps(db, node, trees) if err != nil { return err } trees = scoped } var reporter *model.Node if checkReporter { reporter = node } for guid, perEmail := range trees { // Stored once per email: an oversized key would multiply into every row. if len(guid) > maxPanelGuidLen { continue } if err := mergeNodeClientIpAttribution(db, reporter, guid, perEmail); err != nil { return err } } return nil } // GetClientIpsByGuid returns this panel's full attribution subtree (guid -> email // -> fresh IPs), dropping stale entries. It is what the clientIpsByGuid endpoint // serves to a parent panel. func (s *InboundService) GetClientIpsByGuid() (map[string]map[string][]model.ClientIpEntry, error) { db := database.GetDB() var rows []model.NodeClientIp if err := db.Find(&rows).Error; err != nil { return nil, err } cutoff := time.Now().Unix() - clientIpStaleAfterSeconds out := make(map[string]map[string][]model.ClientIpEntry) for _, row := range rows { if row.NodeGuid == "" || row.Email == "" || row.Ips == "" { continue } var entries []model.ClientIpEntry if err := json.Unmarshal([]byte(row.Ips), &entries); err != nil { continue } fresh := mergeModelClientIpEntries(nil, entries, cutoff) if len(fresh) == 0 { continue } model.SortClientIpEntries(fresh) if out[row.NodeGuid] == nil { out[row.NodeGuid] = make(map[string][]model.ClientIpEntry) } out[row.NodeGuid][row.Email] = fresh } return out, nil } // GetClientIpNodeAttribution returns, for one client email, a map of IP -> the // guid that most recently observed it (within the stale window). Used to label // each IP in the panel with the node it is connecting to. func (s *InboundService) GetClientIpNodeAttribution(email string) (map[string]string, error) { db := database.GetDB() var rows []model.NodeClientIp if err := db.Where("email = ?", email).Find(&rows).Error; err != nil { return nil, err } cutoff := time.Now().Unix() - clientIpStaleAfterSeconds ipGuid := make(map[string]string) ipTs := make(map[string]int64) for _, row := range rows { if row.NodeGuid == "" || row.Ips == "" { continue } var entries []model.ClientIpEntry if err := json.Unmarshal([]byte(row.Ips), &entries); err != nil { continue } for _, e := range entries { if e.IP == "" || e.Timestamp < cutoff { continue } if cur, ok := ipTs[e.IP]; !ok || e.Timestamp > cur { ipTs[e.IP] = e.Timestamp ipGuid[e.IP] = row.NodeGuid } } } return ipGuid, nil } // ClientIpInfo is one IP shown in the panel's per-client IP log, labelled with // the node it is connecting through ("" = this local panel). type ClientIpInfo struct { IP string `json:"ip"` Time string `json:"time"` Node string `json:"node"` } // GetClientIpsWithNodes returns a client's recorded IPs (from the flat // inbound_client_ips display set) annotated with the node each IP is on, using // the per-node attribution table. Local IPs (and any IP without attribution) // carry an empty Node. func (s *InboundService) GetClientIpsWithNodes(email string) ([]ClientIpInfo, error) { raw, err := s.GetInboundClientIps(email) if err != nil || raw == "" { // Record-not-found (or empty) is "no IPs", not an error for the UI. return []ClientIpInfo{}, nil } var entries []model.ClientIpEntry if jerr := json.Unmarshal([]byte(raw), &entries); jerr != nil || len(entries) == 0 { // Legacy shape: a plain JSON array of IP strings. var oldIps []string if json.Unmarshal([]byte(raw), &oldIps) == nil { entries = entries[:0] for _, ip := range oldIps { entries = append(entries, model.ClientIpEntry{IP: ip}) } } } if len(entries) == 0 { return []ClientIpInfo{}, nil } attr, _ := s.GetClientIpNodeAttribution(email) guidName := s.nodeGuidNameMap() localGuid, _ := (&SettingService{}).GetPanelGuid() out := make([]ClientIpInfo, 0, len(entries)) for _, e := range entries { if e.IP == "" { continue } info := ClientIpInfo{IP: e.IP} if e.Timestamp > 0 { info.Time = time.Unix(e.Timestamp, 0).Local().Format("2006-01-02 15:04:05") } if guid, ok := attr[e.IP]; ok && guid != "" && guid != localGuid { info.Node = guidName[guid] } out = append(out, info) } return out, nil } // nodeGuidNameMap maps each known node's attribution key to its display name, // keyed by effectiveNodeGuid so a cloned node's IPs (stored under its node-unique // key) still resolve to the right name instead of colliding under a shared GUID. func (s *InboundService) nodeGuidNameMap() map[string]string { db := database.GetDB() var nodes []model.Node if err := db.Model(&model.Node{}).Find(&nodes).Error; err != nil { return map[string]string{} } ptrs := make([]*model.Node, len(nodes)) for i := range nodes { ptrs[i] = &nodes[i] } selfGuid, _ := (&SettingService{}).GetPanelGuid() ambiguous := ambiguousNodeGuids(ptrs, selfGuid) m := make(map[string]string, len(nodes)) for i := range nodes { m[effectiveNodeGuid(&nodes[i], ambiguous)] = nodes[i].Name } return m } // DeleteNodeClientIpsByGuid removes all attribution rows for a guid (e.g. when a // node is deleted) so its IPs stop being reported and counted. func (s *InboundService) DeleteNodeClientIpsByGuid(guid string) error { if guid == "" { return nil } db := database.GetDB() return db.Where("node_guid = ?", guid).Delete(&model.NodeClientIp{}).Error } // pruneStaleNodeClientIps sweeps every attribution row: upsertNodeClientIps // only revisits emails present in a scan, so unobserved rows never expire there. func pruneStaleNodeClientIps(cutoff int64) error { db := database.GetDB() var rows []model.NodeClientIp if err := db.Find(&rows).Error; err != nil { return err } for _, row := range rows { var entries []model.ClientIpEntry if row.Ips != "" { if err := json.Unmarshal([]byte(row.Ips), &entries); err != nil { continue } } kept := mergeModelClientIpEntries(nil, entries, cutoff) if len(kept) == 0 { if err := db.Where(nodeClientIpSnapshot(row)).Delete(&model.NodeClientIp{}).Error; err != nil { return err } continue } if len(kept) == len(entries) { continue } encoded, _ := model.MarshalClientIpEntries(kept) if err := db.Model(&model.NodeClientIp{}).Where(nodeClientIpSnapshot(row)).Update("ips", encoded).Error; err != nil { return err } } return nil } // maxReportedIpsPerClient bounds one (node, client) list; the newest entries are kept. const maxReportedIpsPerClient = 256 // scopeNodeClientIps keeps only what a node may report: its own key and its sub-nodes' // origins (never this panel's or another node's), its own clients, and no future dates. func scopeNodeClientIps(db *gorm.DB, node *model.Node, trees map[string]map[string][]model.ClientIpEntry) (map[string]map[string][]model.ClientIpEntry, error) { allowed := map[string]struct{}{effectiveNodeKey(node): {}} var origins []string if err := db.Model(&model.Inbound{}).Where("node_id = ? AND origin_node_guid <> ''", node.Id). Distinct().Pluck("origin_node_guid", &origins).Error; err != nil { return nil, err } for _, origin := range origins { allowed[origin] = struct{}{} } var others []*model.Node if err := db.Where("id <> ?", node.Id).Find(&others).Error; err != nil { return nil, err } for _, other := range others { delete(allowed, effectiveNodeKey(other)) delete(allowed, other.Guid) } if panelGuid, err := (&SettingService{}).GetPanelGuid(); err == nil { delete(allowed, panelGuid) } attached, err := nodeAttachedEmails(db, node.Id) if err != nil { return nil, err } now := time.Now().Unix() scoped := make(map[string]map[string][]model.ClientIpEntry, len(trees)) for guid, perEmail := range trees { if _, ok := allowed[guid]; !ok { continue } kept := make(map[string][]model.ClientIpEntry, len(perEmail)) for email, entries := range perEmail { if _, ok := attached[email]; !ok { continue } clampClientIpEntries(entries, now) if len(entries) > maxReportedIpsPerClient { slices.SortFunc(entries, func(a, b model.ClientIpEntry) int { return cmp.Compare(b.Timestamp, a.Timestamp) }) entries = entries[:maxReportedIpsPerClient] } kept[email] = entries } if len(kept) > 0 { scoped[guid] = kept } } return scoped, nil }