Files
mirror-3x-ui/internal/web/service/client_bulk.go
T
Benjamin Mitchell 45f6596663 fix(clients): generate unique subIds in Bulk Add (#7360)
Fixes the Bulk Add regression where a manually entered subscription ID was copied to every generated client, causing all but the first client to be rejected as duplicates. For multi-client batches, treat the entered value as a readable prefix and append an independent cryptographically random suffix; preserve the exact value for a single client and independent random IDs when the field is empty. Remove the process-wide allocation lock to avoid blocking unrelated requests during remote-node dispatch, and cover concurrent BulkCreate/Create, deleted-ID reuse, and uniqueness regressions. Document subIdPrefix in the API contract and regenerate the OpenAPI/API reference artifacts. Validation: CI 12/12 and Docs CI passed on the reviewed head.
2026-12-03 13:57:47 +03:30

2190 lines
66 KiB
Go

package service
import (
"cmp"
"context"
"crypto/rand"
"encoding/json"
"errors"
"fmt"
"slices"
"strings"
"time"
"github.com/google/uuid"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/logger"
"github.com/mhsanaei/3x-ui/v3/internal/util/common"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
"gorm.io/gorm"
)
// BulkAttachResult reports the outcome of a bulk attach across target inbounds.
type BulkAttachResult struct {
ClientNodeApplyResponse
Attached []string `json:"attached"`
Skipped []string `json:"skipped"`
Errors []string `json:"errors"`
}
// BulkAttach attaches the given existing clients (by email) to each target inbound,
// reusing their identity (email/UUID/password/subId) and a shared traffic row. It adds
// all clients to a target in a single AddInboundClient call, and reports clients already
// present on a target as skipped.
func (s *ClientService) BulkAttach(inboundSvc *InboundService, emails []string, inboundIds []int) (*BulkAttachResult, bool, error) {
inboundIds = uniqueInts(inboundIds)
result := &BulkAttachResult{}
if len(emails) == 0 || len(inboundIds) == 0 {
return result, false, nil
}
records := make([]*model.ClientRecord, 0, len(emails))
seenEmail := make(map[string]struct{}, len(emails))
for _, email := range emails {
if email == "" {
continue
}
key := strings.ToLower(email)
if _, ok := seenEmail[key]; ok {
continue
}
seenEmail[key] = struct{}{}
rec, err := s.GetRecordByEmail(nil, email)
if err != nil {
logAttachError(result, "%s: %v", email, err)
continue
}
records = append(records, rec)
}
return s.bulkAttachRecords(inboundSvc, records, inboundIds, result)
}
func logAttachError(result *BulkAttachResult, format string, args ...any) {
msg := fmt.Sprintf(format, args...)
result.Errors = append(result.Errors, msg)
logger.Warningf("[BulkAttach] %s", msg)
}
func (s *ClientService) bulkAttachRecords(inboundSvc *InboundService, records []*model.ClientRecord, inboundIds []int, result *BulkAttachResult) (*BulkAttachResult, bool, error) {
// Same rule as Attach (#4834): clients.flow is unreliable when a non-flow
// inbound synced last, so seed from EffectiveFlow before clientWithInboundFlow.
emailsForFlow := make([]string, 0, len(records))
for _, rec := range records {
emailsForFlow = append(emailsForFlow, rec.Email)
}
flowsByEmail, err := s.EffectiveFlowsByEmails(nil, emailsForFlow)
if err != nil {
return result, false, err
}
needRestart := false
// Prepared in order first, as in Create: fillProtocolDefaults mints the
// shared credentials, so only the node pushes below may overlap.
attachIds := make([]int, 0, len(inboundIds))
attachPayloads := make([]string, 0, len(inboundIds))
attachClients := make([][]model.Client, 0, len(inboundIds))
attachAnyTunnel := false
// A repeated id used to be caught by the second pass seeing the client
// already attached; the applies no longer run before the next prep.
seenInbound := make(map[int]struct{}, len(inboundIds))
for _, ibId := range inboundIds {
if _, dup := seenInbound[ibId]; dup {
continue
}
seenInbound[ibId] = struct{}{}
inbound, err := inboundSvc.GetInbound(ibId)
if err != nil {
logAttachError(result, "inbound %d: %v", ibId, err)
continue
}
if inbound.Protocol == model.WireGuard || inbound.Protocol == model.AmneziaWG {
attachAnyTunnel = true
}
existingClients, err := inboundSvc.GetClients(inbound)
if err != nil {
logAttachError(result, "inbound %d: %v", ibId, err)
continue
}
have := make(map[string]struct{}, len(existingClients))
for _, c := range existingClients {
have[strings.ToLower(c.Email)] = struct{}{}
}
clientsToAdd := make([]model.Client, 0, len(records))
for _, rec := range records {
if _, attached := have[strings.ToLower(rec.Email)]; attached {
result.Skipped = append(result.Skipped, rec.Email)
continue
}
client := *rec.ToClient()
// Forwards are set per inbound; see Attach.
client.ForwardedPorts = nil
prepareWireguardDeviceAddresses(&client, inbound)
if flow, ok := flowsByEmail[rec.Email]; ok && flow != "" {
client.Flow = flow
}
client.UpdatedAt = time.Now().UnixMilli()
if err := s.fillProtocolDefaults(&client, inbound); err != nil {
logAttachError(result, "%s -> inbound %d: %v", rec.Email, ibId, err)
continue
}
clientsToAdd = append(clientsToAdd, clientWithInboundFlow(client, inbound))
}
if len(clientsToAdd) == 0 {
continue
}
payload, err := json.Marshal(map[string][]model.Client{"clients": clientsToAdd})
if err != nil {
logAttachError(result, "inbound %d: %v", ibId, err)
continue
}
attachIds = append(attachIds, ibId)
attachPayloads = append(attachPayloads, string(payload))
attachClients = append(attachClients, clientsToAdd)
}
attachResults, attachPanics := fanoutClientInboundResults(attachIds, addFanoutLimit(attachAnyTunnel), func(i int) inboundApplyOutcome {
nr, err := s.AddInboundClient(inboundSvc, &model.Inbound{Id: attachIds[i], Settings: attachPayloads[i]})
return inboundApplyOutcome{needRestart: nr, err: err}
})
for i, out := range attachResults {
err := out.err
if attachPanics[i] != nil {
// The apply may already have committed, so ask for the restart the
// lost return value can no longer report.
needRestart = true
err = attachPanics[i]
}
if err != nil {
logAttachError(result, "inbound %d: %v", attachIds[i], err)
continue
}
if out.needRestart {
needRestart = true
}
for _, c := range attachClients[i] {
result.Attached = append(result.Attached, c.Email)
}
}
return result, needRestart, nil
}
// BulkDetachResult reports the outcome of a bulk detach across target inbounds.
type BulkDetachResult struct {
ClientNodeApplyResponse
Detached []string `json:"detached"`
Skipped []string `json:"skipped"`
Errors []string `json:"errors"`
}
// BulkDetach detaches the given existing clients (by email) from each target inbound.
// (email, inbound) pairs where the client is not currently attached are silently skipped
// at the inbound level; emails that aren't attached to any of the requested inbounds
// are reported under skipped. ClientRecord rows are kept even when they become orphaned
// (matches single-client detach semantics); callers should use bulkDelete for full removal.
func (s *ClientService) BulkDetach(inboundSvc *InboundService, emails []string, inboundIds []int) (*BulkDetachResult, bool, error) {
result := &BulkDetachResult{}
if len(emails) == 0 || len(inboundIds) == 0 {
return result, false, nil
}
recordErr := func(format string, args ...any) {
msg := fmt.Sprintf(format, args...)
result.Errors = append(result.Errors, msg)
logger.Warningf("[BulkDetach] %s", msg)
}
requested := make(map[int]struct{}, len(inboundIds))
for _, id := range inboundIds {
requested[id] = struct{}{}
}
recsByInbound := make(map[int][]*model.ClientRecord)
emailOrder := make([]string, 0, len(emails))
emailRepr := make(map[string]string, len(emails))
emailFailed := make(map[string]bool, len(emails))
seenEmail := make(map[string]struct{}, len(emails))
for _, email := range emails {
if email == "" {
continue
}
key := strings.ToLower(email)
if _, ok := seenEmail[key]; ok {
continue
}
seenEmail[key] = struct{}{}
rec, err := s.GetRecordByEmail(nil, email)
if err != nil {
recordErr("%s: %v", email, err)
continue
}
currentIds, err := s.GetInboundIdsForRecord(rec.Id)
if err != nil {
recordErr("%s: %v", email, err)
continue
}
matched := false
for _, id := range currentIds {
if _, ok := requested[id]; ok {
recsByInbound[id] = append(recsByInbound[id], rec)
matched = true
}
}
if !matched {
result.Skipped = append(result.Skipped, rec.Email)
continue
}
emailOrder = append(emailOrder, key)
emailRepr[key] = rec.Email
}
needRestart := false
// Ordered and de-duplicated up front: the sequential loop dropped each map
// entry as it went, which the concurrent applies can no longer do.
detachIds := make([]int, 0, len(recsByInbound))
detachRecs := make([][]*model.ClientRecord, 0, len(recsByInbound))
for _, ibId := range inboundIds {
recs, ok := recsByInbound[ibId]
if !ok {
continue
}
delete(recsByInbound, ibId)
detachIds = append(detachIds, ibId)
detachRecs = append(detachRecs, recs)
}
detachResults, detachPanics := fanoutClientInboundResults(detachIds, inboundFanoutConcurrency, func(i int) inboundApplyOutcome {
nr, err := s.delInboundClients(inboundSvc, detachIds[i], detachRecs[i], true)
return inboundApplyOutcome{needRestart: nr, err: err}
})
for i, out := range detachResults {
err := out.err
if detachPanics[i] != nil {
// See BulkAttach: a panicking apply may already have committed.
needRestart = true
err = detachPanics[i]
}
if err != nil {
recordErr("inbound %d: %v", detachIds[i], err)
for _, rec := range detachRecs[i] {
emailFailed[strings.ToLower(rec.Email)] = true
}
continue
}
if out.needRestart {
needRestart = true
}
}
for _, key := range emailOrder {
if emailFailed[key] {
continue
}
result.Detached = append(result.Detached, emailRepr[key])
}
return result, needRestart, nil
}
// inboundApplyOutcome carries one inbound's apply result out of the fanout.
type inboundApplyOutcome struct {
needRestart bool
err error
}
// BulkAdjustResult reports changed clients and per-client skip reasons.
// ExternalLinks contains row counts only for append requests.
type BulkAdjustResult struct {
ClientNodeApplyResponse
SkippedCount int `json:"skippedCount,omitempty" example:"0"`
Adjusted int `json:"adjusted" example:"2"`
Skipped []BulkAdjustReport `json:"skipped,omitempty" example:"[]"`
ExternalLinks *BulkExternalLinksResult `json:"externalLinks,omitempty"`
}
type BulkAdjustReport struct {
Email string `json:"email" example:"carol"`
Reason string `json:"reason" example:"client not found"`
}
type bulkAdjustEntry struct {
record *model.ClientRecord
applyExpiry bool
newExpiry int64
applyTotal bool
newTotal int64
}
// bulkFlowClear is the directive that strips the XTLS flow from every selected
// client. The vision values are the only positive flows xray accepts.
const bulkFlowClear = "none"
var errGroupAdjustLimitsChanged = errors.New("client limits changed during the group adjustment")
// bulkFlowAllowed whitelists the flow directives BulkAdjust accepts. Anything
// outside this set is treated as "" (leave flow untouched) so a malformed or
// hostile value can never be injected into a client's settings. The dropdown in
// ClientBulkAdjustModal.tsx offers the same set ("" / "none" / TLS_FLOW_CONTROL);
// keep the two in sync.
var bulkFlowAllowed = map[string]struct{}{
"": {},
bulkFlowClear: {},
"xtls-rprx-vision": {},
"xtls-rprx-vision-udp443": {},
}
// BulkAdjust shifts ExpiryTime by addDays (days) and TotalGB by addBytes
// for every email in the list. Clients whose corresponding field is
// unlimited (0) are skipped — bulk extend should not accidentally
// limit an unlimited client. addDays and addBytes may be negative.
// flow sets the XTLS flow, limitHwid the max registered devices (0 = unlimited)
// and adTag the MTProto sponsor channel; "none" clears flow or adTag.
//
// Like BulkDelete, the work is grouped by inbound so each inbound's
// settings JSON is parsed and written exactly once regardless of how
// many target emails it contains.
func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string, addDays int, addBytes int64, flow string, limitHwid *int, adTag string) (BulkAdjustResult, bool, error) {
return s.bulkAdjust(inboundSvc, emails, nil, addDays, addBytes, flow, limitHwid, adTag)
}
func (s *ClientService) BulkAdjustGroup(inboundSvc *InboundService, scope *GroupBulkScope, addDays int, addBytes int64, flow string, limitHwid *int, adTag string) (BulkAdjustResult, bool, error) {
operation := *scope
operation.committedAdjustments = make(map[string]bool)
return s.bulkAdjust(inboundSvc, scope.emails, &operation, addDays, addBytes, flow, limitHwid, adTag)
}
func (s *ClientService) bulkAdjust(inboundSvc *InboundService, emails []string, scope *GroupBulkScope, addDays int, addBytes int64, flow string, limitHwid *int, adTag string) (BulkAdjustResult, bool, error) {
result := BulkAdjustResult{}
if len(emails) == 0 {
return result, false, nil
}
flow = strings.TrimSpace(flow)
if _, ok := bulkFlowAllowed[flow]; !ok {
flow = "" // ignore unknown directives — "" means "leave flow untouched"
}
adTag = strings.TrimSpace(adTag)
if adTag != "" && adTag != bulkFlowClear && !model.ValidMtprotoAdTag(adTag) {
return result, false, common.NewError("mtproto client ad tag must be 32 hex characters")
}
if limitHwid != nil && *limitHwid < 0 {
zero := 0
limitHwid = &zero
}
adjustFlow := flow != ""
adjustHwid := limitHwid != nil
adjustAdTag := adTag != ""
if addDays == 0 && addBytes == 0 && !adjustFlow && !adjustHwid && !adjustAdTag {
return result, false, common.NewError("no adjustment specified")
}
addExpiryMs := int64(addDays) * 24 * 60 * 60 * 1000
cleanEmails := trimmedUniqueEmails(emails)
if len(cleanEmails) == 0 {
return result, false, nil
}
defer watchClientChanges(clientChangeSourcePanel, cleanEmails...).record()
db := database.GetDB()
recordsByEmail, err := scope.records(db, cleanEmails, false)
if err != nil {
return result, false, err
}
skippedReasons := map[string]string{}
for _, email := range cleanEmails {
if _, ok := recordsByEmail[email]; !ok {
skippedReasons[email] = scope.skipReason()
}
}
plan := map[string]*bulkAdjustEntry{}
for email, rec := range recordsByEmail {
entry := &bulkAdjustEntry{record: rec}
if addDays != 0 {
switch {
case rec.ExpiryTime == 0:
if _, exists := skippedReasons[email]; !exists {
skippedReasons[email] = "unlimited expiry"
}
case rec.ExpiryTime > 0:
next := rec.ExpiryTime + addExpiryMs
if next <= 0 {
if _, exists := skippedReasons[email]; !exists {
skippedReasons[email] = "reduction exceeds remaining time"
}
} else {
entry.applyExpiry = true
entry.newExpiry = next
}
default:
next := rec.ExpiryTime - addExpiryMs
if next >= 0 {
if _, exists := skippedReasons[email]; !exists {
skippedReasons[email] = "reduction exceeds delay window"
}
} else {
entry.applyExpiry = true
entry.newExpiry = next
}
}
}
if addBytes != 0 {
if rec.TotalGB == 0 {
if _, exists := skippedReasons[email]; !exists {
skippedReasons[email] = "unlimited traffic"
}
} else {
next := rec.TotalGB + addBytes
if next <= 0 {
if _, exists := skippedReasons[email]; !exists {
skippedReasons[email] = "reduction exceeds remaining quota"
}
} else {
entry.applyTotal = true
entry.newTotal = next
}
}
}
if entry.applyExpiry || entry.applyTotal || adjustFlow || adjustHwid || adjustAdTag {
plan[email] = entry
}
}
if len(plan) == 0 {
for email, reason := range skippedReasons {
result.Skipped = append(result.Skipped, BulkAdjustReport{Email: email, Reason: reason})
}
return result, false, nil
}
plannedIds := make([]int, 0, len(plan))
recordIdToEmail := make(map[int]string, len(plan))
for email, entry := range plan {
if entry.applyExpiry || entry.applyTotal || adjustFlow || adjustAdTag {
plannedIds = append(plannedIds, entry.record.Id)
recordIdToEmail[entry.record.Id] = email
}
}
var mappings []model.ClientInbound
for _, batch := range chunkInts(plannedIds, sqlInChunk) {
var rows []model.ClientInbound
if err := db.Where("client_id IN ?", batch).Find(&rows).Error; err != nil {
return result, false, err
}
mappings = append(mappings, rows...)
}
emailsByInbound := map[int][]string{}
for _, m := range mappings {
email, ok := recordIdToEmail[m.ClientId]
if !ok {
continue
}
emailsByInbound[m.InboundId] = append(emailsByInbound[m.InboundId], email)
}
needRestart := false
flowHonored := map[string]bool{}
flowIneligible := map[string]bool{}
adTagHonored := map[string]bool{}
adTagIneligible := map[string]bool{}
execFailed := map[string]bool{}
wasDisabledDepleted := map[string]struct{}{}
adjustIds := sortedInboundIds(emailsByInbound)
adjustResults, adjustPanics := fanoutClientInboundResults(adjustIds, inboundFanoutConcurrency, func(i int) bulkInboundAdjustResult {
return s.bulkAdjustInboundClients(inboundSvc, adjustIds[i], emailsByInbound[adjustIds[i]], plan, scope, flow, adTag)
})
for i, ibRes := range adjustResults {
if adjustPanics[i] != nil {
needRestart = true
for _, email := range emailsByInbound[adjustIds[i]] {
execFailed[email] = true
if _, already := skippedReasons[email]; !already {
skippedReasons[email] = adjustPanics[i].Error()
}
}
continue
}
if ibRes.needRestart {
needRestart = true
}
for _, email := range ibRes.disabledDepleted {
wasDisabledDepleted[email] = struct{}{}
}
for email := range ibRes.flowHonored {
flowHonored[email] = true
}
for email := range ibRes.flowIneligible {
flowIneligible[email] = true
}
for email := range ibRes.adTagHonored {
adTagHonored[email] = true
}
for email := range ibRes.adTagIneligible {
adTagIneligible[email] = true
}
for email, reason := range ibRes.perEmailSkipped {
execFailed[email] = true
if _, already := skippedReasons[email]; !already {
skippedReasons[email] = reason
}
}
}
cond, condArgs := depletedCond(db)
candidateEmails := make([]string, 0, len(plan))
for email, entry := range plan {
if (entry.applyExpiry || entry.applyTotal) && (scope == nil || !scope.committedAdjustments[email]) {
candidateEmails = append(candidateEmails, email)
}
}
disabled, err := bulkAdjustDisabledDepleted(db, candidateEmails, cond, condArgs)
if err != nil {
return result, needRestart, err
}
for _, email := range disabled {
wasDisabledDepleted[email] = struct{}{}
}
wantAdTag := ""
if adjustAdTag && adTag != bulkFlowClear {
wantAdTag = strings.ToLower(adTag)
}
adjusted := map[string]struct{}{}
if scope != nil {
for email := range scope.committedAdjustments {
adjusted[email] = struct{}{}
}
}
apply := func(tx *gorm.DB, email string) (bool, error) {
entry := plan[email]
updates := map[string]any{}
if entry.applyExpiry {
updates["expiry_time"] = entry.newExpiry
}
if entry.applyTotal {
updates["total"] = entry.newTotal
}
if len(updates) > 0 && (scope == nil || !scope.committedAdjustments[email]) {
if err := tx.Model(xray.ClientTraffic{}).Where("email = ?", email).Updates(updates).Error; err != nil {
return false, err
}
}
if adjustHwid {
var err error
if scope == nil {
err = s.setClientLimitHwidByEmail(email, *limitHwid)
} else {
err = s.setClientLimitHwidByEmailTx(tx, email, *limitHwid)
}
if err != nil {
return false, err
}
}
if adjustAdTag && adTagHonored[email] {
q := tx.Model(&model.ClientRecord{}).Where("email = ?", email)
if scope != nil {
q = q.Where("id = ?", entry.record.Id)
}
if err := q.UpdateColumn("ad_tag", wantAdTag).Error; err != nil {
return false, err
}
}
return len(updates) > 0 || flowHonored[email] || adTagHonored[email] || adjustHwid, nil
}
var candidates []string
for email := range plan {
if !execFailed[email] && (scope == nil || !scope.committedAdjustments[email] || adjustHwid || adTagHonored[email]) {
candidates = append(candidates, email)
}
}
if scope == nil {
for _, email := range candidates {
changed, err := apply(db, email)
if err != nil {
if _, already := skippedReasons[email]; !already {
skippedReasons[email] = err.Error()
}
} else if changed {
adjusted[email] = struct{}{}
}
}
} else {
slices.SortFunc(candidates, func(a, b string) int { return cmp.Compare(scope.ids[a], scope.ids[b]) })
for _, batch := range chunkStrings(candidates, sqlInChunk) {
var changed []string
err := runSerializedTx(func(tx *gorm.DB) error {
records, err := scope.records(tx, batch, true)
if err != nil {
return err
}
for _, email := range batch {
if records[email] == nil {
skippedReasons[email] = scope.skipReason()
continue
}
applied, err := apply(tx, email)
if err != nil {
return err
}
if applied {
changed = append(changed, email)
}
}
return nil
})
if err != nil {
for _, email := range batch {
skippedReasons[email] = err.Error()
}
continue
}
for _, email := range changed {
adjusted[email] = struct{}{}
scope.committedAdjustments[email] = true
}
}
}
result.Adjusted = len(adjusted)
for email, reason := range skippedReasons {
result.Skipped = append(result.Skipped, BulkAdjustReport{Email: email, Reason: reason})
}
// Report a flow directive that no inbound could carry — only when it was not
// honored anywhere and the client has no other (expiry/total) skip reason.
// The expiry/total part, if any, has already been applied and counted above.
for email := range flowIneligible {
if flowHonored[email] {
continue
}
if _, already := skippedReasons[email]; already {
continue
}
result.Skipped = append(result.Skipped, BulkAdjustReport{Email: email, Reason: "flow not supported on inbound"})
}
for email := range adTagIneligible {
if adTagHonored[email] {
continue
}
if _, already := skippedReasons[email]; already {
continue
}
result.Skipped = append(result.Skipped, BulkAdjustReport{Email: email, Reason: "adTag not supported on inbound"})
}
if len(wasDisabledDepleted) > 0 {
stillDepleted := map[string]struct{}{}
wasList := make([]string, 0, len(wasDisabledDepleted))
for e := range wasDisabledDepleted {
wasList = append(wasList, e)
}
for _, batch := range chunkStrings(wasList, sqlInChunk) {
var rows []string
if err := db.Model(xray.ClientTraffic{}).
Where(cond+" AND email IN ?", append(append([]any{}, condArgs...), batch)...).
Pluck("email", &rows).Error; err != nil {
return result, needRestart, err
}
for _, e := range rows {
stillDepleted[e] = struct{}{}
}
}
reEnable := make([]string, 0, len(wasDisabledDepleted))
for e := range wasDisabledDepleted {
_, wasAdjusted := adjusted[e]
if _, still := stillDepleted[e]; !still && (scope == nil || wasAdjusted) {
reEnable = append(reEnable, e)
}
}
if len(reEnable) > 0 {
reenabled, nr, err := s.bulkSetEnable(inboundSvc, reEnable, scope, true)
for _, skip := range reenabled.Skipped {
if scope != nil {
result.Skipped = append(result.Skipped, BulkAdjustReport(skip))
}
}
if err != nil {
return result, needRestart, err
}
if nr {
needRestart = true
}
}
}
return result, needRestart, nil
}
type bulkInboundAdjustResult struct {
perEmailSkipped map[string]string
disabledDepleted []string
flowHonored map[string]bool
// flowIneligible is tracked apart from perEmailSkipped: a flow directive
// that an inbound cannot carry must not suppress the expiry/total write for
// the same client (which would diverge the inbound JSON / ClientRecord from
// ClientTraffic). It only feeds the final Skipped report.
flowIneligible map[string]bool
adTagHonored map[string]bool
adTagIneligible map[string]bool
needRestart bool
}
// bulkAdjustInboundClients applies expiry/total deltas to multiple clients
// inside a single inbound's settings JSON. The xray runtime is updated
// only for remote-node inbounds; local nodes do not need a notification
// because the AddUser payload does not include totalGB/expiryTime —
// changing those fields is identity-preserving and the panel's traffic
// enforcement loop picks up the new limits from ClientTraffic directly.
func (s *ClientService) bulkAdjustInboundClients(
inboundSvc *InboundService,
inboundId int,
emails []string,
plan map[string]*bulkAdjustEntry,
scope *GroupBulkScope,
flow string,
adTag string,
) bulkInboundAdjustResult {
res := bulkInboundAdjustResult{
perEmailSkipped: map[string]string{},
flowHonored: map[string]bool{},
flowIneligible: map[string]bool{},
adTagHonored: map[string]bool{},
adTagIneligible: map[string]bool{},
}
mutation := beginInboundClientMutation(inboundId)
defer mutation.close()
oldInbound, err := inboundSvc.GetInbound(inboundId)
if err != nil {
logger.Error("Load Old Data Error")
for _, e := range emails {
res.perEmailSkipped[e] = err.Error()
}
return res
}
var settings map[string]any
if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
s.recordClientNodeFailure(oldInbound.NodeID, &err)
for _, e := range emails {
res.perEmailSkipped[e] = err.Error()
}
return res
}
// Match by email — the client's stable identity (see Delete). Credentials
// can drift from the inbound JSON, so they are never used for matching.
wantedEmails := make(map[string]struct{}, len(emails))
for _, email := range emails {
if plan[email] == nil {
res.perEmailSkipped[email] = "client not found"
continue
}
wantedEmails[email] = struct{}{}
}
// Flow eligibility is a property of the inbound (protocol + transport), so
// resolve it once. Clearing flow is always allowed; setting a vision flow
// is only honored on an inbound that can carry it.
flowEligible := flow == bulkFlowClear ||
(!oldInbound.DisableFlow &&
inboundCanEnableTlsFlow(string(oldInbound.Protocol), oldInbound.StreamSettings, oldInbound.Settings))
wantAdTag := ""
if adTag != "" && adTag != bulkFlowClear {
wantAdTag = strings.ToLower(adTag)
}
interfaceClients, _ := settings["clients"].([]any)
foundEmails := map[string]bool{}
flowChanged := false
adTagChanged := false
hasInboundChanges := false
nowMs := time.Now().Unix() * 1000
for i, client := range interfaceClients {
c, ok := client.(map[string]any)
if !ok {
continue
}
targetEmail, _ := c["email"].(string)
if _, want := wantedEmails[targetEmail]; !want || targetEmail == "" {
continue
}
clientChanged := false
entry := plan[targetEmail]
if entry.applyExpiry {
c["expiryTime"] = entry.newExpiry
clientChanged = true
}
if entry.applyTotal {
c["totalGB"] = entry.newTotal
clientChanged = true
}
if flow != "" {
if flowEligible {
want := ""
if flow != bulkFlowClear {
want = flow
}
if cur, _ := c["flow"].(string); cur != want {
c["flow"] = want
flowChanged = true
}
res.flowHonored[targetEmail] = true
clientChanged = true
} else {
// Record separately so this never suppresses the expiry/total
// write for the same client (see flowIneligible doc).
res.flowIneligible[targetEmail] = true
}
}
if adTag != "" {
if oldInbound.Protocol == model.MTProto {
if cur, _ := c["adTag"].(string); cur != wantAdTag {
c["adTag"] = wantAdTag
adTagChanged = true
}
res.adTagHonored[targetEmail] = true
clientChanged = true
} else {
res.adTagIneligible[targetEmail] = true
}
}
if clientChanged {
c["updated_at"] = nowMs
hasInboundChanges = true
}
interfaceClients[i] = c
foundEmails[targetEmail] = true
}
for email := range wantedEmails {
if !foundEmails[email] {
res.perEmailSkipped[email] = "Client Not Found In Inbound"
}
}
if len(foundEmails) == 0 || !hasInboundChanges {
return res
}
settings["clients"] = interfaceClients
newSettings, err := json.MarshalIndent(settings, "", " ")
if err != nil {
for email := range foundEmails {
res.perEmailSkipped[email] = err.Error()
}
return res
}
prevSettings := oldInbound.Settings
oldInbound.Settings = string(newSettings)
// A flow change rewrites the user's xray config, which the lightweight
// UpdateUser push below does not carry. Local nodes reload via restart;
// remote nodes get a full reconcile (MarkNodeDirty) instead of a per-user push.
if flowChanged && oldInbound.NodeID == nil {
res.needRestart = true
}
// Serialize against the traffic poll to avoid the cross-transaction
// lock-order deadlock on inbounds/client_records (runSerializedTx).
var limited, previouslyDepleted []string
txErr := mutation.commitThen(oldInbound, nodeClientDelta, func(tx *gorm.DB) error {
records, err := scope.inboundRecords(tx, inboundId, emails)
if err != nil {
return err
}
for email, current := range records {
entry := plan[email]
total, expiry := entry.record.TotalGB, entry.record.ExpiryTime
if scope.committedAdjustments[email] {
if entry.applyTotal {
total = entry.newTotal
}
if entry.applyExpiry {
expiry = entry.newExpiry
}
}
if (entry.applyTotal && current.TotalGB != total) || (entry.applyExpiry && current.ExpiryTime != expiry) {
return errGroupAdjustLimitsChanged
}
}
if err := commitInboundClientSettings(tx, oldInbound, prevSettings); err != nil {
return err
}
finalClients, gcErr := inboundSvc.GetClients(oldInbound)
if gcErr != nil {
return gcErr
}
if err := s.SyncInbound(tx, inboundId, finalClients); err != nil {
return err
}
if scope == nil {
return nil
}
for email := range foundEmails {
entry := plan[email]
if !scope.committedAdjustments[email] && (entry.applyExpiry || entry.applyTotal) {
limited = append(limited, email)
}
}
if len(limited) == 0 {
return nil
}
// Commit enforcement limits before delivering any runtime changes.
cond, args := depletedCond(tx)
previouslyDepleted, err = bulkAdjustDisabledDepleted(tx, limited, cond, args)
if err != nil {
return err
}
return writeBulkAdjustTrafficLimits(tx, limited, plan)
}, func() {
if scope == nil || scope.committedAdjustments == nil {
return
}
for email := range foundEmails {
entry := plan[email]
if entry.applyExpiry || entry.applyTotal || res.flowHonored[email] || res.adTagHonored[email] {
scope.committedAdjustments[email] = true
}
}
})
if txErr != nil {
if !errors.Is(txErr, errGroupSelectionStale) && !errors.Is(txErr, errGroupAdjustLimitsChanged) {
s.recordClientNodeFailure(oldInbound.NodeID, &txErr)
}
for email := range foundEmails {
if _, skip := res.perEmailSkipped[email]; !skip {
res.perEmailSkipped[email] = txErr.Error()
}
}
} else {
res.disabledDepleted = previouslyDepleted
if adTagChanged && oldInbound.Protocol == model.MTProto && oldInbound.NodeID == nil {
inboundSvc.applyLocalMtproto(oldInbound.Id)
}
if oldInbound.NodeID != nil && !flowChanged && len(foundEmails) <= nodeBulkPushThreshold {
rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound)
if perr != nil {
logger.Warning("BulkAdjust: node runtime lookup after commit failed:", perr)
} else if push {
mutation.push(s, rt, oldInbound, func(ctx context.Context, batch *nodeClientBatch) bool {
for email := range foundEmails {
entry := plan[email]
updated := *entry.record.ToClient()
if entry.applyExpiry {
updated.ExpiryTime = entry.newExpiry
}
if entry.applyTotal {
updated.TotalGB = entry.newTotal
}
if adTag != "" && oldInbound.Protocol == model.MTProto {
updated.AdTag = wantAdTag
}
updated.UpdatedAt = nowMs
if !batch.acknowledge(rt.UpdateUser(ctx, oldInbound, email, updated)) {
return false
}
}
return true
})
}
if perr != nil || !push {
s.recordClientNodeDeferred(oldInbound.NodeID)
}
} else {
s.recordClientNodeDeferred(oldInbound.NodeID)
}
}
return res
}
// BulkDeleteResult mirrors BulkAdjustResult: total deleted plus per-email
// skip reasons when an email could not be processed.
type BulkDeleteResult struct {
ClientNodeApplyResponse
SkippedCount int `json:"skippedCount,omitempty" example:"0"`
Deleted int `json:"deleted"`
Skipped []BulkDeleteReport `json:"skipped,omitempty"`
}
type BulkDeleteReport struct {
Email string `json:"email"`
Reason string `json:"reason"`
}
// BulkDelete removes every client in the list in one optimized pass.
// Instead of running the full single-delete pipeline N times (which would
// re-read, re-parse, and re-write each inbound's settings JSON for every
// email), it groups emails by inbound and performs a single
// read-modify-write per inbound. Per-row DB cleanups are also batched with
// IN-clause queries at the end. Errors on a particular email are recorded
// in the Skipped list and processing continues for the rest.
func (s *ClientService) BulkDelete(inboundSvc *InboundService, emails []string, keepTraffic bool) (BulkDeleteResult, bool, error) {
return s.bulkDelete(inboundSvc, emails, nil, keepTraffic)
}
func (s *ClientService) BulkDeleteGroup(inboundSvc *InboundService, scope *GroupBulkScope, keepTraffic bool) (BulkDeleteResult, bool, error) {
return s.bulkDelete(inboundSvc, scope.emails, scope, keepTraffic)
}
func (s *ClientService) bulkDelete(inboundSvc *InboundService, emails []string, scope *GroupBulkScope, keepTraffic bool) (BulkDeleteResult, bool, error) {
result := BulkDeleteResult{}
cleanEmails := trimmedUniqueEmails(emails)
if len(cleanEmails) == 0 {
return result, false, nil
}
db := database.GetDB()
var recordsByEmail map[string]*model.ClientRecord
var tombstoneEmails []string
planDelete := func(tx *gorm.DB) error {
var err error
recordsByEmail, err = scope.records(tx, cleanEmails, scope != nil)
if err != nil {
return err
}
for _, email := range cleanEmails {
if recordsByEmail[email] != nil {
tombstoneEmails = append(tombstoneEmails, email)
}
}
tombstoneClientEmails(tombstoneEmails)
return nil
}
if scope == nil {
if err := planDelete(db); err != nil {
return result, false, err
}
} else if err := runSerializedTx(planDelete); err != nil {
withdrawClientTombstones(tombstoneEmails...)
return result, false, err
}
skippedReasons := map[string]string{}
for _, email := range cleanEmails {
if _, ok := recordsByEmail[email]; !ok {
skippedReasons[email] = scope.skipReason()
}
}
clientIds := make([]int, 0, len(recordsByEmail))
recordIdToEmail := make(map[int]string, len(recordsByEmail))
for _, r := range recordsByEmail {
clientIds = append(clientIds, r.Id)
recordIdToEmail[r.Id] = r.Email
}
emailsByInbound := map[int][]string{}
if len(clientIds) > 0 {
var mappings []model.ClientInbound
for _, batch := range chunkInts(clientIds, sqlInChunk) {
var rows []model.ClientInbound
if err := db.Where("client_id IN ?", batch).Find(&rows).Error; err != nil {
return result, false, err
}
mappings = append(mappings, rows...)
}
for _, m := range mappings {
email, ok := recordIdToEmail[m.ClientId]
if !ok {
continue
}
emailsByInbound[m.InboundId] = append(emailsByInbound[m.InboundId], email)
}
}
needRestart := false
delIds := sortedInboundIds(emailsByInbound)
delResults, delPanics := fanoutClientInboundResults(delIds, inboundFanoutConcurrency, func(i int) bulkInboundDeleteResult {
return s.bulkDelInboundClients(inboundSvc, delIds[i], emailsByInbound[delIds[i]], recordsByEmail, scope, keepTraffic)
})
for i, ibResult := range delResults {
if delPanics[i] != nil {
needRestart = true
for _, email := range emailsByInbound[delIds[i]] {
if _, already := skippedReasons[email]; !already {
skippedReasons[email] = delPanics[i].Error()
}
}
continue
}
if ibResult.needRestart {
needRestart = true
}
for email, reason := range ibResult.perEmailSkipped {
if _, already := skippedReasons[email]; !already {
skippedReasons[email] = reason
}
}
}
successEmails := make([]string, 0, len(recordsByEmail))
successIds := make([]int, 0, len(recordsByEmail))
failedEmails := make([]string, 0, len(recordsByEmail))
successSubIDs := make([]string, 0, len(recordsByEmail))
for email, rec := range recordsByEmail {
if _, skipped := skippedReasons[email]; skipped {
failedEmails = append(failedEmails, email)
continue
}
successEmails = append(successEmails, email)
successIds = append(successIds, rec.Id)
successSubIDs = append(successSubIDs, rec.SubID)
}
if len(successIds) > 0 {
// Serialize the row cleanup against the traffic poll to avoid the
// cross-transaction lock-order deadlock on client_traffics/inbounds.
if err := runSerializedTx(func(tx *gorm.DB) error {
if scope != nil {
current, err := scope.records(tx, successEmails, true)
if err != nil {
return err
}
linked, err := linkedGroupBulkClients(tx, successIds)
if err != nil {
return err
}
// Fanout detached the original links. Do not delete clients with a new link.
var eligibleEmails []string
successIds, successSubIDs = nil, nil
for _, email := range successEmails {
rec := current[email]
if rec == nil || linked[rec.Id] {
skippedReasons[email] = scope.skipReason()
failedEmails = append(failedEmails, email)
continue
}
eligibleEmails = append(eligibleEmails, email)
successIds = append(successIds, rec.Id)
successSubIDs = append(successSubIDs, rec.SubID)
}
successEmails = eligibleEmails
}
if len(successIds) == 0 {
return nil
}
if e := adjustGroupBaselinesForRemovedTraffic(tx, successEmails); e != nil {
return e
}
if e := clearClientHwidsBySubIDTx(tx, successSubIDs...); e != nil {
return e
}
for _, batch := range chunkInts(successIds, sqlInChunk) {
if e := tx.Where("client_id IN ?", batch).Delete(&model.ClientInbound{}).Error; e != nil {
return e
}
if e := tx.Where("client_id IN ?", batch).Delete(&model.ClientExternalLink{}).Error; e != nil {
return e
}
}
if !keepTraffic && len(successEmails) > 0 {
for _, batch := range chunkStrings(successEmails, sqlInChunk) {
if e := tx.Where("email IN ?", batch).Delete(&xray.ClientTraffic{}).Error; e != nil {
return e
}
}
if e := inboundSvc.delClientIPsByEmails(tx, successEmails); e != nil {
return e
}
}
for _, batch := range chunkInts(successIds, sqlInChunk) {
if e := tx.Where("id IN ?", batch).Delete(&model.ClientRecord{}).Error; e != nil {
return e
}
}
return nil
}); err != nil {
withdrawClientTombstones(tombstoneEmails...)
return result, needRestart, err
}
}
withdrawClientTombstones(failedEmails...)
result.Deleted = len(successEmails)
for email, reason := range skippedReasons {
result.Skipped = append(result.Skipped, BulkDeleteReport{Email: email, Reason: reason})
}
return result, needRestart, nil
}
type bulkInboundDeleteResult struct {
perEmailSkipped map[string]string
needRestart bool
}
// bulkDelInboundClients removes multiple clients from a single inbound's
// settings JSON in one read-modify-write cycle, runs the xray runtime
// RemoveUser/DeleteUser calls, and persists the inbound. The returned map
// holds per-email failure reasons; emails not present in the map are
// considered successful for this inbound.
func (s *ClientService) bulkDelInboundClients(
inboundSvc *InboundService,
inboundId int,
emails []string,
records map[string]*model.ClientRecord,
scope *GroupBulkScope,
keepTraffic bool,
) bulkInboundDeleteResult {
res := bulkInboundDeleteResult{perEmailSkipped: map[string]string{}}
defer InvalidateSubData()
mutation := beginInboundClientMutation(inboundId)
defer mutation.close()
oldInbound, err := inboundSvc.GetInbound(inboundId)
if err != nil {
logger.Error("Load Old Data Error")
for _, e := range emails {
res.perEmailSkipped[e] = err.Error()
}
return res
}
var settings map[string]any
if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
s.recordClientNodeFailure(oldInbound.NodeID, &err)
for _, e := range emails {
res.perEmailSkipped[e] = err.Error()
}
return res
}
// Match by email — the client's stable identity (see Delete). The link-derived
// set is deletion intent: an email already absent from settings is successful,
// while foundEmails tracks entries that still need settings-specific cleanup.
wantedEmails := make(map[string]struct{}, len(emails))
for _, email := range emails {
if records[email] == nil {
res.perEmailSkipped[email] = "client not found"
continue
}
wantedEmails[email] = struct{}{}
}
interfaceClients, _ := settings["clients"].([]any)
newClients := make([]any, 0, len(interfaceClients))
foundEmails := map[string]bool{}
enableByEmail := map[string]bool{}
for _, client := range interfaceClients {
c, ok := client.(map[string]any)
if !ok {
newClients = append(newClients, client)
continue
}
em, _ := c["email"].(string)
if _, found := wantedEmails[em]; found && em != "" {
foundEmails[em] = true
en, _ := c["enable"].(bool)
enableByEmail[em] = en
continue
}
newClients = append(newClients, client)
}
db := database.GetDB()
newClients = compactOrphans(db, newClients)
if newClients == nil {
newClients = []any{}
}
settings["clients"] = newClients
newSettings, err := json.MarshalIndent(settings, "", " ")
if err != nil {
for email := range wantedEmails {
if _, skip := res.perEmailSkipped[email]; !skip {
res.perEmailSkipped[email] = err.Error()
}
}
return res
}
prevSettings := oldInbound.Settings
oldInbound.Settings = string(newSettings)
foundList := make([]string, 0, len(foundEmails))
for email := range foundEmails {
foundList = append(foundList, email)
}
notDepletedByEmail := map[string]bool{}
if len(foundList) > 0 {
type trafficRow struct {
Email string
Enable bool
}
for _, batch := range chunkStrings(foundList, sqlInChunk) {
var rows []trafficRow
if err := db.Model(xray.ClientTraffic{}).
Where("email IN ?", batch).
Select("email, enable").
Scan(&rows).Error; err == nil {
for _, r := range rows {
notDepletedByEmail[r.Email] = r.Enable
}
}
}
}
var sharedSet map[string]bool
if !keepTraffic && scope == nil {
var sharedErr error
sharedSet, sharedErr = inboundSvc.emailsUsedByOtherInbounds(db, foundList, inboundId)
if sharedErr != nil {
for email := range wantedEmails {
res.perEmailSkipped[email] = sharedErr.Error()
}
return res
}
}
if !keepTraffic && scope == nil {
purge := make([]string, 0, len(foundEmails))
for email := range foundEmails {
if !sharedSet[strings.ToLower(strings.TrimSpace(email))] {
purge = append(purge, email)
}
}
if len(purge) > 0 {
// Serialize the IP/stat purge against the traffic poll to avoid the
// cross-transaction lock-order deadlock on client_traffics.
if delErr := runSerializedTx(func(tx *gorm.DB) error {
if e := inboundSvc.delClientIPsByEmails(tx, purge); e != nil {
logger.Error("Error in delete client IPs")
return e
}
if e := inboundSvc.delClientStatsByEmails(tx, purge); e != nil {
logger.Error("Delete stats Data Error")
return e
}
return nil
}); delErr != nil {
for _, email := range purge {
res.perEmailSkipped[email] = delErr.Error()
delete(foundEmails, email)
}
}
}
}
var dispatchEmails []string
if oldInbound.NodeID != nil {
for email := range wantedEmails {
if _, skip := res.perEmailSkipped[email]; !skip {
dispatchEmails = append(dispatchEmails, email)
}
}
slices.Sort(dispatchEmails)
}
var pending []model.NodePendingClientDelete
txErr := mutation.commit(oldInbound, nodeFullClientDelete, func(tx *gorm.DB) error {
if _, err := scope.inboundRecords(tx, inboundId, emails); err != nil {
return err
}
if err := commitInboundClientSettings(tx, oldInbound, prevSettings); err != nil {
return err
}
finalClients, err := inboundSvc.GetClients(oldInbound)
if err != nil {
return err
}
if err := s.SyncInbound(tx, inboundId, finalClients); err != nil {
return err
}
pending, err = queueNodeClientDeletes(tx, oldInbound.NodeID, dispatchEmails)
return err
})
if txErr != nil {
if !errors.Is(txErr, errGroupSelectionStale) {
s.recordClientNodeFailure(oldInbound.NodeID, &txErr)
}
for email := range wantedEmails {
if _, skip := res.perEmailSkipped[email]; !skip {
res.perEmailSkipped[email] = txErr.Error()
}
}
} else if oldInbound.NodeID == nil {
rt, rterr := inboundSvc.runtimeFor(oldInbound)
if rterr != nil {
res.needRestart = true
} else {
for email := range foundEmails {
if !enableByEmail[email] || !notDepletedByEmail[email] {
continue
}
err1 := rt.RemoveUser(context.Background(), oldInbound, email)
if err1 == nil {
logger.Debug("Client deleted on", rt.Name(), ":", email)
if endDroppedClientSessions(oldInbound) {
res.needRestart = true
}
} else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
logger.Debug("User is already deleted. Nothing to do more...")
} else {
logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
res.needRestart = true
}
}
}
} else {
if len(pending) == 0 || len(pending) > nodeBulkPushThreshold {
s.recordClientNodeDeferred(oldInbound.NodeID)
return res
}
rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound)
if perr != nil {
logger.Warning("BulkDelete: node runtime lookup after commit failed:", perr)
} else if push {
mutation.push(s, rt, oldInbound, func(ctx context.Context, batch *nodeClientBatch) bool {
complete := true
for _, row := range pending {
result, attempted, err := applyNodeClientDelete(ctx, rt, row)
if !batch.acknowledge(result, err) {
return false
}
complete = complete && attempted
}
return complete
})
}
if perr != nil || !push {
s.recordClientNodeDeferred(oldInbound.NodeID)
}
}
return res
}
// BulkCreateResult mirrors BulkAdjustResult for the create flow.
type BulkCreateResult struct {
ClientNodeApplyResponse
Created int `json:"created"`
Skipped []BulkCreateReport `json:"skipped,omitempty"`
}
type BulkCreateReport struct {
Email string `json:"email"`
Reason string `json:"reason"`
}
func (s *ClientService) BulkCreate(inboundSvc *InboundService, payloads []ClientCreatePayload) (BulkCreateResult, bool, error) {
if slices.ContainsFunc(payloads, func(payload ClientCreatePayload) bool {
return payload.SubIDPrefix != ""
}) {
var err error
payloads, err = allocateBulkSubIDs(payloads)
if err != nil {
return BulkCreateResult{}, false, err
}
}
result, _, needRestart, err := s.bulkCreate(inboundSvc, payloads)
return result, needRestart, err
}
func allocateBulkSubIDs(payloads []ClientCreatePayload) ([]ClientCreatePayload, error) {
payloads = slices.Clone(payloads)
taken := make(map[string]bool, len(payloads))
for _, item := range payloads {
if item.Client.SubID != "" {
if item.SubIDPrefix != "" {
return nil, common.NewError("subId and subIdPrefix cannot both be set")
}
taken[item.Client.SubID] = true
}
}
for i := range payloads {
prefix := payloads[i].SubIDPrefix
if prefix == "" {
continue
}
if err := validateClientSubID(prefix); err != nil {
return nil, err
}
for {
// The prefix is public. Each subscription gets independent secret entropy.
subID := prefix + "-" + rand.Text()
if !taken[subID] {
payloads[i].Client.SubID = subID
taken[subID] = true
break
}
}
}
return payloads, nil
}
// bulkCreate also returns the payload indexes that inserted a new client record;
// a Created payload whose email already existed only reused that client.
func (s *ClientService) bulkCreate(inboundSvc *InboundService, payloads []ClientCreatePayload) (BulkCreateResult, []int, bool, error) {
result := BulkCreateResult{}
if len(payloads) == 0 {
return result, nil, false, nil
}
skip := func(email, reason string) {
if strings.TrimSpace(email) == "" {
email = "(missing email)"
}
result.Skipped = append(result.Skipped, BulkCreateReport{Email: email, Reason: reason})
}
type prepared struct {
client model.Client
inboundIds []int
limitHwid int
payloadIdx int
reused bool
}
prep := make([]prepared, 0, len(payloads))
emails := make([]string, 0, len(payloads))
subIDs := make([]string, 0, len(payloads))
seenEmail := make(map[string]struct{}, len(payloads))
seenSubID := make(map[string]string, len(payloads))
for i := range payloads {
client := payloads[i].Client
email := strings.TrimSpace(client.Email)
if email == "" {
skip("", "client email is required")
continue
}
if verr := validateClientEmail(email); verr != nil {
skip(email, verr.Error())
continue
}
if verr := validateClientSubID(client.SubID); verr != nil {
skip(email, verr.Error())
continue
}
if verr := validateClientRenewal(client); verr != nil {
skip(email, verr.Error())
continue
}
if verr := validateClientResetMax(client.ResetMax); verr != nil {
skip(email, verr.Error())
continue
}
if verr := validateClientTrafficReset(client.TrafficReset, client.TrafficResetDay); verr != nil {
skip(email, verr.Error())
continue
}
if len(payloads[i].InboundIds) == 0 {
skip(email, "at least one inbound is required")
continue
}
client.Email = email
if client.SubID == "" {
client.SubID = uuid.NewString()
}
// Preserve enable (omit→true in UnmarshalJSON; explicit false kept) (#6478).
now := time.Now().UnixMilli()
if client.CreatedAt == 0 {
client.CreatedAt = now
}
client.UpdatedAt = now
le := strings.ToLower(email)
if _, dup := seenEmail[le]; dup {
skip(email, "email already in use: "+email)
continue
}
if owner, ok := seenSubID[client.SubID]; ok && owner != le {
skip(email, "subId already in use: "+client.SubID)
continue
}
seenEmail[le] = struct{}{}
seenSubID[client.SubID] = le
prep = append(prep, prepared{client: client, inboundIds: uniqueInts(payloads[i].InboundIds), limitHwid: payloads[i].LimitHwid, payloadIdx: i})
emails = append(emails, email)
subIDs = append(subIDs, client.SubID)
}
if len(prep) == 0 {
return result, nil, false, nil
}
db := database.GetDB()
const lookupChunk = 400
existingByEmail := make(map[string]model.ClientRecord, len(emails))
for start := 0; start < len(emails); start += lookupChunk {
end := min(start+lookupChunk, len(emails))
var rows []model.ClientRecord
if e := db.Where("email IN ?", emails[start:end]).Find(&rows).Error; e != nil {
return result, nil, false, e
}
for i := range rows {
existingByEmail[strings.ToLower(rows[i].Email)] = rows[i]
}
}
existingSubOwner := make(map[string]string, len(subIDs))
for start := 0; start < len(subIDs); start += lookupChunk {
end := min(start+lookupChunk, len(subIDs))
var rows []model.ClientRecord
if e := db.Where("sub_id IN ?", subIDs[start:end]).Find(&rows).Error; e != nil {
return result, nil, false, e
}
for i := range rows {
existingSubOwner[rows[i].SubID] = strings.ToLower(rows[i].Email)
}
}
inboundCache := make(map[int]*model.Inbound)
getIb := func(id int) (*model.Inbound, error) {
if ib, ok := inboundCache[id]; ok {
return ib, nil
}
ib, e := inboundSvc.GetInbound(id)
if e != nil {
return nil, e
}
inboundCache[id] = ib
return ib, nil
}
byInbound := make(map[int][]model.Client)
idxByInbound := make(map[int][]int)
inboundOrder := make([]int, 0)
failed := make([]bool, len(prep))
reason := make([]string, len(prep))
createAnyTunnel := false
for idx := range prep {
le := strings.ToLower(prep[idx].client.Email)
if rec, ok := existingByEmail[le]; ok {
if rec.SubID != prep[idx].client.SubID {
failed[idx] = true
reason[idx] = "email already in use: " + prep[idx].client.Email
continue
}
prep[idx].reused = true
if prep[idx].client.ID == "" {
prep[idx].client.ID = rec.UUID
}
if prep[idx].client.Password == "" {
prep[idx].client.Password = rec.Password
}
if prep[idx].client.Auth == "" {
prep[idx].client.Auth = rec.Auth
}
if prep[idx].client.Secret == "" {
prep[idx].client.Secret = rec.Secret
}
}
if owner, ok := existingSubOwner[prep[idx].client.SubID]; ok && owner != le {
failed[idx] = true
reason[idx] = "subId already in use: " + prep[idx].client.SubID
continue
}
ok := true
for _, ibId := range prep[idx].inboundIds {
ib, e := getIb(ibId)
if e != nil {
failed[idx] = true
reason[idx] = e.Error()
ok = false
break
}
if ib.Protocol == model.WireGuard || ib.Protocol == model.AmneziaWG {
createAnyTunnel = true
}
if e := s.fillProtocolDefaults(&prep[idx].client, ib); e != nil {
failed[idx] = true
reason[idx] = e.Error()
ok = false
break
}
}
if !ok {
continue
}
for _, ibId := range prep[idx].inboundIds {
ib, _ := getIb(ibId)
if _, seen := byInbound[ibId]; !seen {
inboundOrder = append(inboundOrder, ibId)
}
byInbound[ibId] = append(byInbound[ibId], clientWithInboundFlow(prep[idx].client, ib))
idxByInbound[ibId] = append(idxByInbound[ibId], idx)
}
}
needRestart := false
createResults, createPanics := fanoutClientInboundResults(inboundOrder, addFanoutLimit(createAnyTunnel), func(i int) inboundApplyOutcome {
ibId := inboundOrder[i]
payload, e := json.Marshal(map[string][]model.Client{"clients": byInbound[ibId]})
if e != nil {
return inboundApplyOutcome{err: e}
}
nr, e := s.AddInboundClient(inboundSvc, &model.Inbound{Id: ibId, Settings: string(payload)})
return inboundApplyOutcome{needRestart: nr, err: e}
})
for i, out := range createResults {
e := out.err
if createPanics[i] != nil {
// See BulkAttach: a panicking apply may already have committed.
needRestart = true
e = createPanics[i]
}
if e != nil {
for _, idx := range idxByInbound[inboundOrder[i]] {
failed[idx] = true
if reason[idx] == "" {
reason[idx] = e.Error()
}
}
continue
}
if out.needRestart {
needRestart = true
}
}
inserted := make([]int, 0, len(prep))
for idx := range prep {
if failed[idx] {
skip(prep[idx].client.Email, reason[idx])
continue
}
if err := s.setClientLimitHwidByEmail(prep[idx].client.Email, prep[idx].limitHwid); err != nil {
skip(prep[idx].client.Email, err.Error())
continue
}
result.Created++
if !prep[idx].reused {
inserted = append(inserted, prep[idx].payloadIdx)
}
}
return result, inserted, needRestart, nil
}
func (s *ClientService) DelDepleted(inboundSvc *InboundService) (int, bool, error) {
db := database.GetDB()
now := time.Now().UnixMilli()
depletedClause := depletedClientsClause
var rows []xray.ClientTraffic
if err := db.Where(depletedClause, now).Find(&rows).Error; err != nil {
return 0, false, err
}
if len(rows) == 0 {
return 0, false, nil
}
seen := make(map[string]struct{}, len(rows))
emails := make([]string, 0, len(rows))
// BulkDelete trims each email, so a padded usage row would resolve to the client it resembles.
for _, r := range rows {
if r.Email == "" || r.Email != strings.TrimSpace(r.Email) {
continue
}
if _, ok := seen[r.Email]; ok {
continue
}
seen[r.Email] = struct{}{}
emails = append(emails, r.Email)
}
if len(emails) == 0 {
return 0, false, nil
}
res, needRestart, err := s.BulkDelete(inboundSvc, emails, false)
if err != nil {
return res.Deleted, needRestart, err
}
return res.Deleted, needRestart, nil
}
type BulkSetEnableResult struct {
ClientNodeApplyResponse
Changed int `json:"changed"`
Skipped []BulkSetEnableReport `json:"skipped,omitempty"`
}
type BulkSetEnableReport struct {
Email string `json:"email"`
Reason string `json:"reason"`
}
func (s *ClientService) BulkSetEnable(inboundSvc *InboundService, emails []string, enable bool) (BulkSetEnableResult, bool, error) {
return s.bulkSetEnable(inboundSvc, emails, nil, enable)
}
func (s *ClientService) bulkSetEnable(inboundSvc *InboundService, emails []string, scope *GroupBulkScope, enable bool) (BulkSetEnableResult, bool, error) {
result := BulkSetEnableResult{}
cleanEmails := trimmedUniqueEmails(emails)
if len(cleanEmails) == 0 {
return result, false, nil
}
defer watchClientChanges(clientChangeSourcePanel, cleanEmails...).record()
db := database.GetDB()
recordsByEmail, err := scope.records(db, cleanEmails, false)
if err != nil {
return result, false, err
}
skippedReasons := map[string]string{}
for _, email := range cleanEmails {
if _, ok := recordsByEmail[email]; !ok {
skippedReasons[email] = scope.skipReason()
}
}
clientIds := make([]int, 0, len(recordsByEmail))
recordIdToEmail := make(map[int]string, len(recordsByEmail))
for _, r := range recordsByEmail {
clientIds = append(clientIds, r.Id)
recordIdToEmail[r.Id] = r.Email
}
emailsByInbound := map[int][]string{}
if len(clientIds) > 0 {
var mappings []model.ClientInbound
for _, batch := range chunkInts(clientIds, sqlInChunk) {
var rows []model.ClientInbound
if err := db.Where("client_id IN ?", batch).Find(&rows).Error; err != nil {
return result, false, err
}
mappings = append(mappings, rows...)
}
for _, m := range mappings {
email, ok := recordIdToEmail[m.ClientId]
if !ok {
continue
}
emailsByInbound[m.InboundId] = append(emailsByInbound[m.InboundId], email)
}
}
needRestart := false
enableIds := sortedInboundIds(emailsByInbound)
enableResults, enablePanics := fanoutClientInboundResults(enableIds, inboundFanoutConcurrency, func(i int) bulkSetEnableInboundResult {
return s.bulkSetEnableInboundClients(inboundSvc, enableIds[i], emailsByInbound[enableIds[i]], scope, enable)
})
for i, ibRes := range enableResults {
if enablePanics[i] != nil {
needRestart = true
for _, email := range emailsByInbound[enableIds[i]] {
if _, already := skippedReasons[email]; !already {
skippedReasons[email] = enablePanics[i].Error()
}
}
continue
}
if ibRes.needRestart {
needRestart = true
}
for email, reason := range ibRes.perEmailSkipped {
if _, already := skippedReasons[email]; !already {
skippedReasons[email] = reason
}
}
}
successEmails := make([]string, 0, len(recordsByEmail))
for email := range recordsByEmail {
if _, skipped := skippedReasons[email]; skipped {
continue
}
successEmails = append(successEmails, email)
}
var trafficErr error
if len(successEmails) > 0 {
now := time.Now().UnixMilli()
trafficErr = runSerializedTx(func(tx *gorm.DB) error {
if scope != nil {
current, err := scope.records(tx, successEmails, true)
if err != nil {
return err
}
successEmails = slices.DeleteFunc(successEmails, func(email string) bool {
if current[email] != nil {
return false
}
skippedReasons[email] = scope.skipReason()
return true
})
}
for _, batch := range chunkStrings(successEmails, sqlInChunk) {
if e := tx.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Update("enable", enable).Error; e != nil {
return e
}
if e := tx.Model(&model.ClientRecord{}).Where("email IN ?", batch).
Updates(map[string]any{"enable": enable, "updated_at": now}).Error; e != nil {
return e
}
}
return nil
})
}
// Sidecars serve by the traffic rows, so push them only after the rows flip;
// a push before it left a bulk-enabled client off until the reconcile job.
for i, ibRes := range enableResults {
if enablePanics[i] == nil && ibRes.sidecar != "" {
applyBulkSidecar(inboundSvc, enableIds[i], ibRes.sidecar)
}
}
if trafficErr != nil {
return result, needRestart, trafficErr
}
result.Changed = len(successEmails)
for email, reason := range skippedReasons {
result.Skipped = append(result.Skipped, BulkSetEnableReport{Email: email, Reason: reason})
}
return result, needRestart, nil
}
type bulkSetEnableInboundResult struct {
perEmailSkipped map[string]string
needRestart bool
sidecar model.Protocol // local sidecar inbound to push after the traffic rows
}
func applyBulkSidecar(inboundSvc *InboundService, inboundId int, protocol model.Protocol) {
defer lockInbound(inboundId).Unlock()
switch protocol {
case model.MTProto:
inboundSvc.applyLocalMtproto(inboundId)
case model.AmneziaWG:
inboundSvc.applyLocalAmneziaWG(inboundId)
case model.TUIC:
inboundSvc.applyLocalTuic(inboundId)
}
}
func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService, inboundId int, emails []string, scope *GroupBulkScope, enable bool) bulkSetEnableInboundResult {
res := bulkSetEnableInboundResult{perEmailSkipped: map[string]string{}}
mutation := beginInboundClientMutation(inboundId)
defer mutation.close()
oldInbound, err := inboundSvc.GetInbound(inboundId)
if err != nil {
for _, e := range emails {
res.perEmailSkipped[e] = err.Error()
}
return res
}
var settings map[string]any
if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
s.recordClientNodeFailure(oldInbound.NodeID, &err)
for _, e := range emails {
res.perEmailSkipped[e] = err.Error()
}
return res
}
wanted := make(map[string]struct{}, len(emails))
for _, email := range emails {
wanted[email] = struct{}{}
}
cipher := ""
if oldInbound.Protocol == model.Shadowsocks {
cipher, _ = settings["method"].(string)
}
type changedClient struct {
email string
wasEnable bool
client model.Client
}
var changed []changedClient
found := map[string]bool{}
nowMs := time.Now().UnixMilli()
interfaceClients, _ := settings["clients"].([]any)
for i, c := range interfaceClients {
entry, ok := c.(map[string]any)
if !ok {
continue
}
email, _ := entry["email"].(string)
if _, want := wanted[email]; !want || email == "" {
continue
}
found[email] = true
prev, _ := entry["enable"].(bool)
if prev == enable {
continue
}
entry["enable"] = enable
entry["updated_at"] = nowMs
interfaceClients[i] = entry
// Build the pushed client from the inbound JSON (the per-inbound source of
// truth), so a remote UpdateUser carries every field and never zeroes
// subId/totalGB/expiry from drifting ClientRecord columns (#4628/#4792).
var parsed model.Client
if b, mErr := json.Marshal(entry); mErr == nil {
_ = json.Unmarshal(b, &parsed)
}
parsed.Email = email
parsed.Enable = enable
changed = append(changed, changedClient{email: email, wasEnable: prev, client: parsed})
}
for email := range wanted {
if !found[email] {
res.perEmailSkipped[email] = "Client Not Found In Inbound"
}
}
if len(changed) == 0 {
return res
}
settings["clients"] = interfaceClients
newSettings, err := json.MarshalIndent(settings, "", " ")
if err != nil {
for _, ch := range changed {
res.perEmailSkipped[ch.email] = err.Error()
}
return res
}
prevSettings := oldInbound.Settings
oldInbound.Settings = string(newSettings)
rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound)
if perr != nil {
for _, ch := range changed {
res.perEmailSkipped[ch.email] = perr.Error()
}
return res
}
if oldInbound.NodeID != nil && push && len(changed) > nodeBulkPushThreshold {
push = false
}
txErr := mutation.commit(oldInbound, nodeClientDelta, func(tx *gorm.DB) error {
if _, err := scope.inboundRecords(tx, inboundId, emails); err != nil {
return err
}
if e := commitInboundClientSettings(tx, oldInbound, prevSettings); e != nil {
return e
}
finalClients, gcErr := inboundSvc.GetClients(oldInbound)
if gcErr != nil {
return gcErr
}
if err := s.SyncInbound(tx, inboundId, finalClients); err != nil {
return err
}
return nil
})
if txErr != nil {
if !errors.Is(txErr, errGroupSelectionStale) {
s.recordClientNodeFailure(oldInbound.NodeID, &txErr)
}
for _, ch := range changed {
res.perEmailSkipped[ch.email] = txErr.Error()
}
return res
}
if oldInbound.NodeID == nil {
if !push {
res.needRestart = true
} else if servedOutsideXray(oldInbound.Protocol) {
res.sidecar = oldInbound.Protocol
} else {
for _, ch := range changed {
if enable {
err1 := rt.AddUser(context.Background(), oldInbound, coreUserFromClient(&ch.client, cipher))
if err1 != nil {
logger.Debug("Error in adding client on", rt.Name(), ":", err1)
res.needRestart = true
}
} else if ch.wasEnable {
err1 := rt.RemoveUser(context.Background(), oldInbound, ch.email)
if err1 != nil && !strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", ch.email)) {
logger.Debug("Error in removing client on", rt.Name(), ":", err1)
res.needRestart = true
} else if err1 == nil && endDroppedClientSessions(oldInbound) {
// A removed credential does not end the session it was serving.
res.needRestart = true
}
}
}
}
} else if push {
mutation.push(s, rt, oldInbound, func(ctx context.Context, batch *nodeClientBatch) bool {
for _, ch := range changed {
updated := ch.client
updated.UpdatedAt = nowMs
if !batch.acknowledge(rt.UpdateUser(ctx, oldInbound, ch.email, updated)) {
return false
}
}
advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound)
return true
})
} else {
s.recordClientNodeDeferred(oldInbound.NodeID)
}
return res
}
func bulkAdjustDisabledDepleted(tx *gorm.DB, emails []string, cond string, condArgs []any) ([]string, error) {
var disabled []string
for _, batch := range chunkStrings(emails, sqlInChunk) {
var rows []string
if err := tx.Model(xray.ClientTraffic{}).
Where(cond+" AND enable = ? AND email IN ?", append(append([]any{}, condArgs...), false, batch)...).
Pluck("email", &rows).Error; err != nil {
return nil, err
}
disabled = append(disabled, rows...)
}
return disabled, nil
}
// Lock the relevant clients before calling this. The email uniquely identifies the traffic row.
func writeBulkAdjustTrafficLimits(tx *gorm.DB, emails []string, plan map[string]*bulkAdjustEntry) error {
for _, batch := range chunkStrings(emails, sqlInChunk/3) {
var expiryArgs, totalArgs []any
var expiryCases, totalCases strings.Builder
for _, email := range batch {
entry := plan[email]
if entry.applyExpiry {
expiryCases.WriteString(" WHEN ? THEN CAST(? AS BIGINT)")
expiryArgs = append(expiryArgs, email, entry.newExpiry)
}
if entry.applyTotal {
totalCases.WriteString(" WHEN ? THEN CAST(? AS BIGINT)")
totalArgs = append(totalArgs, email, entry.newTotal)
}
}
values := make(map[string]any, 2)
if len(expiryArgs) != 0 {
values["expiry_time"] = gorm.Expr("CASE email"+expiryCases.String()+" ELSE expiry_time END", expiryArgs...)
}
if len(totalArgs) != 0 {
values["total"] = gorm.Expr("CASE email"+totalCases.String()+" ELSE total END", totalArgs...)
}
if err := tx.Model(xray.ClientTraffic{}).Where("email IN ?", batch).UpdateColumns(values).Error; err != nil {
return err
}
}
return nil
}