1
0

client_bulk.go 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687
  1. package service
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "strings"
  7. "time"
  8. "github.com/google/uuid"
  9. "github.com/mhsanaei/3x-ui/v3/internal/database"
  10. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  11. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  12. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  13. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  14. "gorm.io/gorm"
  15. )
  16. // BulkAttachResult reports the outcome of a bulk attach across target inbounds.
  17. type BulkAttachResult struct {
  18. Attached []string `json:"attached"`
  19. Skipped []string `json:"skipped"`
  20. Errors []string `json:"errors"`
  21. }
  22. // BulkAttach attaches the given existing clients (by email) to each target inbound,
  23. // reusing their identity (email/UUID/password/subId) and a shared traffic row. It adds
  24. // all clients to a target in a single AddInboundClient call, and reports clients already
  25. // present on a target as skipped.
  26. func (s *ClientService) BulkAttach(inboundSvc *InboundService, emails []string, inboundIds []int) (*BulkAttachResult, bool, error) {
  27. result := &BulkAttachResult{}
  28. if len(emails) == 0 || len(inboundIds) == 0 {
  29. return result, false, nil
  30. }
  31. recordErr := func(format string, args ...any) {
  32. msg := fmt.Sprintf(format, args...)
  33. result.Errors = append(result.Errors, msg)
  34. logger.Warningf("[BulkAttach] %s", msg)
  35. }
  36. records := make([]*model.ClientRecord, 0, len(emails))
  37. seenEmail := make(map[string]struct{}, len(emails))
  38. for _, email := range emails {
  39. if email == "" {
  40. continue
  41. }
  42. key := strings.ToLower(email)
  43. if _, ok := seenEmail[key]; ok {
  44. continue
  45. }
  46. seenEmail[key] = struct{}{}
  47. rec, err := s.GetRecordByEmail(nil, email)
  48. if err != nil {
  49. recordErr("%s: %v", email, err)
  50. continue
  51. }
  52. records = append(records, rec)
  53. }
  54. emailSubIDs, sidErr := inboundSvc.getAllEmailSubIDs()
  55. if sidErr != nil {
  56. emailSubIDs = nil
  57. logger.Warningf("[BulkAttach] getAllEmailSubIDs: %v", sidErr)
  58. }
  59. needRestart := false
  60. for _, ibId := range inboundIds {
  61. inbound, err := inboundSvc.GetInbound(ibId)
  62. if err != nil {
  63. recordErr("inbound %d: %v", ibId, err)
  64. continue
  65. }
  66. existingClients, err := inboundSvc.GetClients(inbound)
  67. if err != nil {
  68. recordErr("inbound %d: %v", ibId, err)
  69. continue
  70. }
  71. have := make(map[string]struct{}, len(existingClients))
  72. for _, c := range existingClients {
  73. have[strings.ToLower(c.Email)] = struct{}{}
  74. }
  75. clientsToAdd := make([]model.Client, 0, len(records))
  76. for _, rec := range records {
  77. if _, attached := have[strings.ToLower(rec.Email)]; attached {
  78. result.Skipped = append(result.Skipped, rec.Email)
  79. continue
  80. }
  81. client := *rec.ToClient()
  82. client.UpdatedAt = time.Now().UnixMilli()
  83. if err := s.fillProtocolDefaults(&client, inbound); err != nil {
  84. recordErr("%s -> inbound %d: %v", rec.Email, ibId, err)
  85. continue
  86. }
  87. clientsToAdd = append(clientsToAdd, clientWithInboundFlow(client, inbound))
  88. }
  89. if len(clientsToAdd) == 0 {
  90. continue
  91. }
  92. payload, err := json.Marshal(map[string][]model.Client{"clients": clientsToAdd})
  93. if err != nil {
  94. recordErr("inbound %d: %v", ibId, err)
  95. continue
  96. }
  97. nr, err := s.addInboundClient(inboundSvc, &model.Inbound{Id: ibId, Settings: string(payload)}, emailSubIDs)
  98. if err != nil {
  99. recordErr("inbound %d: %v", ibId, err)
  100. continue
  101. }
  102. if nr {
  103. needRestart = true
  104. }
  105. for _, c := range clientsToAdd {
  106. result.Attached = append(result.Attached, c.Email)
  107. }
  108. }
  109. return result, needRestart, nil
  110. }
  111. // BulkDetachResult reports the outcome of a bulk detach across target inbounds.
  112. type BulkDetachResult struct {
  113. Detached []string `json:"detached"`
  114. Skipped []string `json:"skipped"`
  115. Errors []string `json:"errors"`
  116. }
  117. // BulkDetach detaches the given existing clients (by email) from each target inbound.
  118. // (email, inbound) pairs where the client is not currently attached are silently skipped
  119. // at the inbound level; emails that aren't attached to any of the requested inbounds
  120. // are reported under skipped. ClientRecord rows are kept even when they become orphaned
  121. // (matches single-client detach semantics); callers should use bulkDelete for full removal.
  122. func (s *ClientService) BulkDetach(inboundSvc *InboundService, emails []string, inboundIds []int) (*BulkDetachResult, bool, error) {
  123. result := &BulkDetachResult{}
  124. if len(emails) == 0 || len(inboundIds) == 0 {
  125. return result, false, nil
  126. }
  127. recordErr := func(format string, args ...any) {
  128. msg := fmt.Sprintf(format, args...)
  129. result.Errors = append(result.Errors, msg)
  130. logger.Warningf("[BulkDetach] %s", msg)
  131. }
  132. requested := make(map[int]struct{}, len(inboundIds))
  133. for _, id := range inboundIds {
  134. requested[id] = struct{}{}
  135. }
  136. recsByInbound := make(map[int][]*model.ClientRecord)
  137. emailOrder := make([]string, 0, len(emails))
  138. emailRepr := make(map[string]string, len(emails))
  139. emailFailed := make(map[string]bool, len(emails))
  140. seenEmail := make(map[string]struct{}, len(emails))
  141. for _, email := range emails {
  142. if email == "" {
  143. continue
  144. }
  145. key := strings.ToLower(email)
  146. if _, ok := seenEmail[key]; ok {
  147. continue
  148. }
  149. seenEmail[key] = struct{}{}
  150. rec, err := s.GetRecordByEmail(nil, email)
  151. if err != nil {
  152. recordErr("%s: %v", email, err)
  153. continue
  154. }
  155. currentIds, err := s.GetInboundIdsForRecord(rec.Id)
  156. if err != nil {
  157. recordErr("%s: %v", email, err)
  158. continue
  159. }
  160. matched := false
  161. for _, id := range currentIds {
  162. if _, ok := requested[id]; ok {
  163. recsByInbound[id] = append(recsByInbound[id], rec)
  164. matched = true
  165. }
  166. }
  167. if !matched {
  168. result.Skipped = append(result.Skipped, rec.Email)
  169. continue
  170. }
  171. emailOrder = append(emailOrder, key)
  172. emailRepr[key] = rec.Email
  173. }
  174. needRestart := false
  175. for _, ibId := range inboundIds {
  176. recs, ok := recsByInbound[ibId]
  177. if !ok {
  178. continue
  179. }
  180. delete(recsByInbound, ibId)
  181. nr, err := s.delInboundClients(inboundSvc, ibId, recs, true)
  182. if err != nil {
  183. recordErr("inbound %d: %v", ibId, err)
  184. for _, rec := range recs {
  185. emailFailed[strings.ToLower(rec.Email)] = true
  186. }
  187. continue
  188. }
  189. if nr {
  190. needRestart = true
  191. }
  192. }
  193. for _, key := range emailOrder {
  194. if emailFailed[key] {
  195. continue
  196. }
  197. result.Detached = append(result.Detached, emailRepr[key])
  198. }
  199. return result, needRestart, nil
  200. }
  201. // BulkAdjustResult is returned by BulkAdjust to report how many clients were
  202. // successfully updated and which were skipped (typically because the field
  203. // being adjusted was unlimited for that client) or failed.
  204. type BulkAdjustResult struct {
  205. Adjusted int `json:"adjusted"`
  206. Skipped []BulkAdjustReport `json:"skipped,omitempty"`
  207. }
  208. type BulkAdjustReport struct {
  209. Email string `json:"email"`
  210. Reason string `json:"reason"`
  211. }
  212. type bulkAdjustEntry struct {
  213. record *model.ClientRecord
  214. applyExpiry bool
  215. newExpiry int64
  216. applyTotal bool
  217. newTotal int64
  218. }
  219. // bulkFlowClear is the directive that strips the XTLS flow from every selected
  220. // client. The vision values are the only positive flows xray accepts.
  221. const bulkFlowClear = "none"
  222. // bulkFlowAllowed whitelists the flow directives BulkAdjust accepts. Anything
  223. // outside this set is treated as "" (leave flow untouched) so a malformed or
  224. // hostile value can never be injected into a client's settings. The dropdown in
  225. // ClientBulkAdjustModal.tsx offers the same set ("" / "none" / TLS_FLOW_CONTROL);
  226. // keep the two in sync.
  227. var bulkFlowAllowed = map[string]struct{}{
  228. "": {},
  229. bulkFlowClear: {},
  230. "xtls-rprx-vision": {},
  231. "xtls-rprx-vision-udp443": {},
  232. }
  233. // BulkAdjust shifts ExpiryTime by addDays (days) and TotalGB by addBytes
  234. // for every email in the list. Clients whose corresponding field is
  235. // unlimited (0) are skipped — bulk extend should not accidentally
  236. // limit an unlimited client. addDays and addBytes may be negative.
  237. //
  238. // Like BulkDelete, the work is grouped by inbound so each inbound's
  239. // settings JSON is parsed and written exactly once regardless of how
  240. // many target emails it contains.
  241. func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string, addDays int, addBytes int64, flow string) (BulkAdjustResult, bool, error) {
  242. result := BulkAdjustResult{}
  243. if len(emails) == 0 {
  244. return result, false, nil
  245. }
  246. flow = strings.TrimSpace(flow)
  247. if _, ok := bulkFlowAllowed[flow]; !ok {
  248. flow = "" // ignore unknown directives — "" means "leave flow untouched"
  249. }
  250. adjustFlow := flow != ""
  251. if addDays == 0 && addBytes == 0 && !adjustFlow {
  252. return result, false, common.NewError("no adjustment specified")
  253. }
  254. addExpiryMs := int64(addDays) * 24 * 60 * 60 * 1000
  255. seen := map[string]struct{}{}
  256. cleanEmails := make([]string, 0, len(emails))
  257. for _, e := range emails {
  258. e = strings.TrimSpace(e)
  259. if e == "" {
  260. continue
  261. }
  262. if _, ok := seen[e]; ok {
  263. continue
  264. }
  265. seen[e] = struct{}{}
  266. cleanEmails = append(cleanEmails, e)
  267. }
  268. if len(cleanEmails) == 0 {
  269. return result, false, nil
  270. }
  271. db := database.GetDB()
  272. var records []model.ClientRecord
  273. for _, batch := range chunkStrings(cleanEmails, sqlInChunk) {
  274. var rows []model.ClientRecord
  275. if err := db.Where("email IN ?", batch).Find(&rows).Error; err != nil {
  276. return result, false, err
  277. }
  278. records = append(records, rows...)
  279. }
  280. recordsByEmail := make(map[string]*model.ClientRecord, len(records))
  281. for i := range records {
  282. recordsByEmail[records[i].Email] = &records[i]
  283. }
  284. skippedReasons := map[string]string{}
  285. for _, email := range cleanEmails {
  286. if _, ok := recordsByEmail[email]; !ok {
  287. skippedReasons[email] = "client not found"
  288. }
  289. }
  290. plan := map[string]*bulkAdjustEntry{}
  291. for email, rec := range recordsByEmail {
  292. entry := &bulkAdjustEntry{record: rec}
  293. if addDays != 0 {
  294. switch {
  295. case rec.ExpiryTime == 0:
  296. if _, exists := skippedReasons[email]; !exists {
  297. skippedReasons[email] = "unlimited expiry"
  298. }
  299. case rec.ExpiryTime > 0:
  300. next := rec.ExpiryTime + addExpiryMs
  301. if next <= 0 {
  302. if _, exists := skippedReasons[email]; !exists {
  303. skippedReasons[email] = "reduction exceeds remaining time"
  304. }
  305. } else {
  306. entry.applyExpiry = true
  307. entry.newExpiry = next
  308. }
  309. default:
  310. next := rec.ExpiryTime - addExpiryMs
  311. if next >= 0 {
  312. if _, exists := skippedReasons[email]; !exists {
  313. skippedReasons[email] = "reduction exceeds delay window"
  314. }
  315. } else {
  316. entry.applyExpiry = true
  317. entry.newExpiry = next
  318. }
  319. }
  320. }
  321. if addBytes != 0 {
  322. if rec.TotalGB == 0 {
  323. if _, exists := skippedReasons[email]; !exists {
  324. skippedReasons[email] = "unlimited traffic"
  325. }
  326. } else {
  327. next := rec.TotalGB + addBytes
  328. if next <= 0 {
  329. if _, exists := skippedReasons[email]; !exists {
  330. skippedReasons[email] = "reduction exceeds remaining quota"
  331. }
  332. } else {
  333. entry.applyTotal = true
  334. entry.newTotal = next
  335. }
  336. }
  337. }
  338. if entry.applyExpiry || entry.applyTotal || adjustFlow {
  339. plan[email] = entry
  340. }
  341. }
  342. if len(plan) == 0 {
  343. for email, reason := range skippedReasons {
  344. result.Skipped = append(result.Skipped, BulkAdjustReport{Email: email, Reason: reason})
  345. }
  346. return result, false, nil
  347. }
  348. plannedIds := make([]int, 0, len(plan))
  349. recordIdToEmail := make(map[int]string, len(plan))
  350. for email, entry := range plan {
  351. plannedIds = append(plannedIds, entry.record.Id)
  352. recordIdToEmail[entry.record.Id] = email
  353. }
  354. var mappings []model.ClientInbound
  355. for _, batch := range chunkInts(plannedIds, sqlInChunk) {
  356. var rows []model.ClientInbound
  357. if err := db.Where("client_id IN ?", batch).Find(&rows).Error; err != nil {
  358. return result, false, err
  359. }
  360. mappings = append(mappings, rows...)
  361. }
  362. emailsByInbound := map[int][]string{}
  363. for _, m := range mappings {
  364. email, ok := recordIdToEmail[m.ClientId]
  365. if !ok {
  366. continue
  367. }
  368. emailsByInbound[m.InboundId] = append(emailsByInbound[m.InboundId], email)
  369. }
  370. needRestart := false
  371. flowHonored := map[string]bool{}
  372. flowIneligible := map[string]bool{}
  373. execFailed := map[string]bool{}
  374. for inboundId, ibEmails := range emailsByInbound {
  375. ibRes := s.bulkAdjustInboundClients(inboundSvc, inboundId, ibEmails, plan, flow)
  376. if ibRes.needRestart {
  377. needRestart = true
  378. }
  379. for email := range ibRes.flowHonored {
  380. flowHonored[email] = true
  381. }
  382. for email := range ibRes.flowIneligible {
  383. flowIneligible[email] = true
  384. }
  385. for email, reason := range ibRes.perEmailSkipped {
  386. execFailed[email] = true
  387. if _, already := skippedReasons[email]; !already {
  388. skippedReasons[email] = reason
  389. }
  390. }
  391. }
  392. cond, condArgs := depletedCond(db)
  393. candidateEmails := make([]string, 0, len(plan))
  394. for email, entry := range plan {
  395. if entry.applyExpiry || entry.applyTotal {
  396. candidateEmails = append(candidateEmails, email)
  397. }
  398. }
  399. wasDisabledDepleted := map[string]struct{}{}
  400. for _, batch := range chunkStrings(candidateEmails, sqlInChunk) {
  401. var rows []string
  402. if err := db.Model(xray.ClientTraffic{}).
  403. Where(cond+" AND enable = ? AND email IN ?", append(append([]any{}, condArgs...), false, batch)...).
  404. Pluck("email", &rows).Error; err != nil {
  405. return result, needRestart, err
  406. }
  407. for _, e := range rows {
  408. wasDisabledDepleted[e] = struct{}{}
  409. }
  410. }
  411. adjusted := map[string]struct{}{}
  412. for email, entry := range plan {
  413. if execFailed[email] {
  414. continue
  415. }
  416. updates := map[string]any{}
  417. if entry.applyExpiry {
  418. updates["expiry_time"] = entry.newExpiry
  419. }
  420. if entry.applyTotal {
  421. updates["total"] = entry.newTotal
  422. }
  423. if len(updates) > 0 {
  424. if err := db.Model(xray.ClientTraffic{}).Where("email = ?", email).Updates(updates).Error; err != nil {
  425. if _, already := skippedReasons[email]; !already {
  426. skippedReasons[email] = err.Error()
  427. }
  428. continue
  429. }
  430. }
  431. // Counted when expiry/total changed, or a flow directive was honored
  432. // for this client (flow lives in the inbound JSON, not ClientTraffic).
  433. if len(updates) > 0 || flowHonored[email] {
  434. adjusted[email] = struct{}{}
  435. }
  436. }
  437. result.Adjusted = len(adjusted)
  438. for email, reason := range skippedReasons {
  439. result.Skipped = append(result.Skipped, BulkAdjustReport{Email: email, Reason: reason})
  440. }
  441. // Report a flow directive that no inbound could carry — only when it was not
  442. // honored anywhere and the client has no other (expiry/total) skip reason.
  443. // The expiry/total part, if any, has already been applied and counted above.
  444. for email := range flowIneligible {
  445. if flowHonored[email] {
  446. continue
  447. }
  448. if _, already := skippedReasons[email]; already {
  449. continue
  450. }
  451. result.Skipped = append(result.Skipped, BulkAdjustReport{Email: email, Reason: "flow not supported on inbound"})
  452. }
  453. if len(wasDisabledDepleted) > 0 {
  454. stillDepleted := map[string]struct{}{}
  455. wasList := make([]string, 0, len(wasDisabledDepleted))
  456. for e := range wasDisabledDepleted {
  457. wasList = append(wasList, e)
  458. }
  459. for _, batch := range chunkStrings(wasList, sqlInChunk) {
  460. var rows []string
  461. if err := db.Model(xray.ClientTraffic{}).
  462. Where(cond+" AND email IN ?", append(append([]any{}, condArgs...), batch)...).
  463. Pluck("email", &rows).Error; err != nil {
  464. return result, needRestart, err
  465. }
  466. for _, e := range rows {
  467. stillDepleted[e] = struct{}{}
  468. }
  469. }
  470. reEnable := make([]string, 0, len(wasDisabledDepleted))
  471. for e := range wasDisabledDepleted {
  472. if _, still := stillDepleted[e]; !still {
  473. reEnable = append(reEnable, e)
  474. }
  475. }
  476. if len(reEnable) > 0 {
  477. _, nr, err := s.BulkSetEnable(inboundSvc, reEnable, true)
  478. if err != nil {
  479. return result, needRestart, err
  480. }
  481. if nr {
  482. needRestart = true
  483. }
  484. }
  485. }
  486. return result, needRestart, nil
  487. }
  488. type bulkInboundAdjustResult struct {
  489. perEmailSkipped map[string]string
  490. flowHonored map[string]bool
  491. // flowIneligible is tracked apart from perEmailSkipped: a flow directive
  492. // that an inbound cannot carry must not suppress the expiry/total write for
  493. // the same client (which would diverge the inbound JSON / ClientRecord from
  494. // ClientTraffic). It only feeds the final Skipped report.
  495. flowIneligible map[string]bool
  496. needRestart bool
  497. }
  498. // bulkAdjustInboundClients applies expiry/total deltas to multiple clients
  499. // inside a single inbound's settings JSON. The xray runtime is updated
  500. // only for remote-node inbounds; local nodes do not need a notification
  501. // because the AddUser payload does not include totalGB/expiryTime —
  502. // changing those fields is identity-preserving and the panel's traffic
  503. // enforcement loop picks up the new limits from ClientTraffic directly.
  504. func (s *ClientService) bulkAdjustInboundClients(
  505. inboundSvc *InboundService,
  506. inboundId int,
  507. emails []string,
  508. plan map[string]*bulkAdjustEntry,
  509. flow string,
  510. ) bulkInboundAdjustResult {
  511. res := bulkInboundAdjustResult{perEmailSkipped: map[string]string{}, flowHonored: map[string]bool{}, flowIneligible: map[string]bool{}}
  512. defer lockInbound(inboundId).Unlock()
  513. oldInbound, err := inboundSvc.GetInbound(inboundId)
  514. if err != nil {
  515. logger.Error("Load Old Data Error")
  516. for _, e := range emails {
  517. res.perEmailSkipped[e] = err.Error()
  518. }
  519. return res
  520. }
  521. var settings map[string]any
  522. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  523. for _, e := range emails {
  524. res.perEmailSkipped[e] = err.Error()
  525. }
  526. return res
  527. }
  528. // Match by email — the client's stable identity (see Delete). Credentials
  529. // can drift from the inbound JSON, so they are never used for matching.
  530. wantedEmails := make(map[string]struct{}, len(emails))
  531. for _, email := range emails {
  532. if plan[email] == nil {
  533. res.perEmailSkipped[email] = "client not found"
  534. continue
  535. }
  536. wantedEmails[email] = struct{}{}
  537. }
  538. // Flow eligibility is a property of the inbound (protocol + transport), so
  539. // resolve it once. Clearing flow is always allowed; setting a vision flow
  540. // is only honored on an inbound that can carry it.
  541. flowEligible := flow == bulkFlowClear ||
  542. inboundCanEnableTlsFlow(string(oldInbound.Protocol), oldInbound.StreamSettings, oldInbound.Settings)
  543. interfaceClients, _ := settings["clients"].([]any)
  544. foundEmails := map[string]bool{}
  545. flowChanged := false
  546. nowMs := time.Now().Unix() * 1000
  547. for i, client := range interfaceClients {
  548. c, ok := client.(map[string]any)
  549. if !ok {
  550. continue
  551. }
  552. targetEmail, _ := c["email"].(string)
  553. if _, want := wantedEmails[targetEmail]; !want || targetEmail == "" {
  554. continue
  555. }
  556. entry := plan[targetEmail]
  557. if entry.applyExpiry {
  558. c["expiryTime"] = entry.newExpiry
  559. }
  560. if entry.applyTotal {
  561. c["totalGB"] = entry.newTotal
  562. }
  563. if flow != "" {
  564. if flowEligible {
  565. want := ""
  566. if flow != bulkFlowClear {
  567. want = flow
  568. }
  569. if cur, _ := c["flow"].(string); cur != want {
  570. c["flow"] = want
  571. flowChanged = true
  572. }
  573. res.flowHonored[targetEmail] = true
  574. } else {
  575. // Record separately so this never suppresses the expiry/total
  576. // write for the same client (see flowIneligible doc).
  577. res.flowIneligible[targetEmail] = true
  578. }
  579. }
  580. c["updated_at"] = nowMs
  581. interfaceClients[i] = c
  582. foundEmails[targetEmail] = true
  583. }
  584. for email := range wantedEmails {
  585. if !foundEmails[email] {
  586. res.perEmailSkipped[email] = "Client Not Found In Inbound"
  587. }
  588. }
  589. if len(foundEmails) == 0 {
  590. return res
  591. }
  592. settings["clients"] = interfaceClients
  593. newSettings, err := json.MarshalIndent(settings, "", " ")
  594. if err != nil {
  595. for email := range foundEmails {
  596. res.perEmailSkipped[email] = err.Error()
  597. }
  598. return res
  599. }
  600. prevSettings := oldInbound.Settings
  601. oldInbound.Settings = string(newSettings)
  602. // A flow change rewrites the user's xray config, which the lightweight
  603. // UpdateUser push below does not carry. Local nodes reload via restart;
  604. // remote nodes get a full reconcile (MarkNodeDirty) instead of a per-user push.
  605. if flowChanged && oldInbound.NodeID == nil {
  606. res.needRestart = true
  607. }
  608. if oldInbound.NodeID != nil {
  609. rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound)
  610. if perr != nil {
  611. for email := range foundEmails {
  612. res.perEmailSkipped[email] = perr.Error()
  613. delete(foundEmails, email)
  614. }
  615. } else {
  616. if flowChanged {
  617. push = false
  618. }
  619. // Large batches collapse into one reconcile push rather than M updates.
  620. if push && len(foundEmails) > nodeBulkPushThreshold {
  621. push = false
  622. }
  623. if push {
  624. pushFailed := false
  625. for email := range foundEmails {
  626. entry := plan[email]
  627. updated := *entry.record.ToClient()
  628. if entry.applyExpiry {
  629. updated.ExpiryTime = entry.newExpiry
  630. }
  631. if entry.applyTotal {
  632. updated.TotalGB = entry.newTotal
  633. }
  634. updated.UpdatedAt = nowMs
  635. if err1 := rt.UpdateUser(context.Background(), oldInbound, email, updated); err1 != nil {
  636. logger.Warning("Error in updating client on", rt.Name(), ":", err1)
  637. pushFailed = true
  638. }
  639. }
  640. if !pushFailed {
  641. advancePushedInbound(rt, prevSettings, oldInbound)
  642. }
  643. }
  644. }
  645. }
  646. // Serialize against the traffic poll to avoid the cross-transaction
  647. // lock-order deadlock on inbounds/client_records (runSerializedTx).
  648. txErr := runSerializedTx(func(tx *gorm.DB) error {
  649. if err := tx.Save(oldInbound).Error; err != nil {
  650. return err
  651. }
  652. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  653. if gcErr != nil {
  654. return gcErr
  655. }
  656. if err := s.SyncInbound(tx, inboundId, finalClients); err != nil {
  657. return err
  658. }
  659. if oldInbound.NodeID != nil {
  660. return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID)
  661. }
  662. return nil
  663. })
  664. if txErr != nil {
  665. for email := range foundEmails {
  666. if _, skip := res.perEmailSkipped[email]; !skip {
  667. res.perEmailSkipped[email] = txErr.Error()
  668. }
  669. }
  670. }
  671. return res
  672. }
  673. // BulkDeleteResult mirrors BulkAdjustResult: total deleted plus per-email
  674. // skip reasons when an email could not be processed.
  675. type BulkDeleteResult struct {
  676. Deleted int `json:"deleted"`
  677. Skipped []BulkDeleteReport `json:"skipped,omitempty"`
  678. }
  679. type BulkDeleteReport struct {
  680. Email string `json:"email"`
  681. Reason string `json:"reason"`
  682. }
  683. // BulkDelete removes every client in the list in one optimized pass.
  684. // Instead of running the full single-delete pipeline N times (which would
  685. // re-read, re-parse, and re-write each inbound's settings JSON for every
  686. // email), it groups emails by inbound and performs a single
  687. // read-modify-write per inbound. Per-row DB cleanups are also batched with
  688. // IN-clause queries at the end. Errors on a particular email are recorded
  689. // in the Skipped list and processing continues for the rest.
  690. func (s *ClientService) BulkDelete(inboundSvc *InboundService, emails []string, keepTraffic bool) (BulkDeleteResult, bool, error) {
  691. result := BulkDeleteResult{}
  692. seen := map[string]struct{}{}
  693. cleanEmails := make([]string, 0, len(emails))
  694. for _, e := range emails {
  695. e = strings.TrimSpace(e)
  696. if e == "" {
  697. continue
  698. }
  699. if _, ok := seen[e]; ok {
  700. continue
  701. }
  702. seen[e] = struct{}{}
  703. cleanEmails = append(cleanEmails, e)
  704. }
  705. if len(cleanEmails) == 0 {
  706. return result, false, nil
  707. }
  708. db := database.GetDB()
  709. var records []model.ClientRecord
  710. for _, batch := range chunkStrings(cleanEmails, sqlInChunk) {
  711. var rows []model.ClientRecord
  712. if err := db.Where("email IN ?", batch).Find(&rows).Error; err != nil {
  713. return result, false, err
  714. }
  715. records = append(records, rows...)
  716. }
  717. recordsByEmail := make(map[string]*model.ClientRecord, len(records))
  718. tombstoneEmails := make([]string, 0, len(records))
  719. for i := range records {
  720. recordsByEmail[records[i].Email] = &records[i]
  721. tombstoneEmails = append(tombstoneEmails, records[i].Email)
  722. }
  723. tombstoneClientEmails(tombstoneEmails)
  724. skippedReasons := map[string]string{}
  725. for _, email := range cleanEmails {
  726. if _, ok := recordsByEmail[email]; !ok {
  727. skippedReasons[email] = "client not found"
  728. }
  729. }
  730. clientIds := make([]int, 0, len(recordsByEmail))
  731. recordIdToEmail := make(map[int]string, len(recordsByEmail))
  732. for _, r := range recordsByEmail {
  733. clientIds = append(clientIds, r.Id)
  734. recordIdToEmail[r.Id] = r.Email
  735. }
  736. emailsByInbound := map[int][]string{}
  737. if len(clientIds) > 0 {
  738. var mappings []model.ClientInbound
  739. for _, batch := range chunkInts(clientIds, sqlInChunk) {
  740. var rows []model.ClientInbound
  741. if err := db.Where("client_id IN ?", batch).Find(&rows).Error; err != nil {
  742. return result, false, err
  743. }
  744. mappings = append(mappings, rows...)
  745. }
  746. for _, m := range mappings {
  747. email, ok := recordIdToEmail[m.ClientId]
  748. if !ok {
  749. continue
  750. }
  751. emailsByInbound[m.InboundId] = append(emailsByInbound[m.InboundId], email)
  752. }
  753. }
  754. needRestart := false
  755. for inboundId, ibEmails := range emailsByInbound {
  756. ibResult := s.bulkDelInboundClients(inboundSvc, inboundId, ibEmails, recordsByEmail, keepTraffic)
  757. if ibResult.needRestart {
  758. needRestart = true
  759. }
  760. for email, reason := range ibResult.perEmailSkipped {
  761. if _, already := skippedReasons[email]; !already {
  762. skippedReasons[email] = reason
  763. }
  764. }
  765. }
  766. successEmails := make([]string, 0, len(recordsByEmail))
  767. successIds := make([]int, 0, len(recordsByEmail))
  768. failedEmails := make([]string, 0, len(recordsByEmail))
  769. for email, rec := range recordsByEmail {
  770. if _, skipped := skippedReasons[email]; skipped {
  771. failedEmails = append(failedEmails, email)
  772. continue
  773. }
  774. successEmails = append(successEmails, email)
  775. successIds = append(successIds, rec.Id)
  776. }
  777. withdrawClientTombstones(failedEmails...)
  778. if len(successIds) > 0 {
  779. // Serialize the row cleanup against the traffic poll to avoid the
  780. // cross-transaction lock-order deadlock on client_traffics/inbounds.
  781. if err := runSerializedTx(func(tx *gorm.DB) error {
  782. if e := adjustGroupBaselinesForRemovedTraffic(tx, successEmails); e != nil {
  783. return e
  784. }
  785. for _, batch := range chunkInts(successIds, sqlInChunk) {
  786. if e := tx.Where("client_id IN ?", batch).Delete(&model.ClientInbound{}).Error; e != nil {
  787. return e
  788. }
  789. if e := tx.Where("client_id IN ?", batch).Delete(&model.ClientExternalLink{}).Error; e != nil {
  790. return e
  791. }
  792. }
  793. if !keepTraffic && len(successEmails) > 0 {
  794. for _, batch := range chunkStrings(successEmails, sqlInChunk) {
  795. if e := tx.Where("email IN ?", batch).Delete(&xray.ClientTraffic{}).Error; e != nil {
  796. return e
  797. }
  798. if e := tx.Where("client_email IN ?", batch).Delete(&model.InboundClientIps{}).Error; e != nil {
  799. return e
  800. }
  801. }
  802. }
  803. for _, batch := range chunkInts(successIds, sqlInChunk) {
  804. if e := tx.Where("id IN ?", batch).Delete(&model.ClientRecord{}).Error; e != nil {
  805. return e
  806. }
  807. }
  808. return nil
  809. }); err != nil {
  810. withdrawClientTombstones(successEmails...)
  811. return result, needRestart, err
  812. }
  813. }
  814. result.Deleted = len(successEmails)
  815. for email, reason := range skippedReasons {
  816. result.Skipped = append(result.Skipped, BulkDeleteReport{Email: email, Reason: reason})
  817. }
  818. return result, needRestart, nil
  819. }
  820. type bulkInboundDeleteResult struct {
  821. perEmailSkipped map[string]string
  822. needRestart bool
  823. }
  824. // bulkDelInboundClients removes multiple clients from a single inbound's
  825. // settings JSON in one read-modify-write cycle, runs the xray runtime
  826. // RemoveUser/DeleteUser calls, and persists the inbound. The returned map
  827. // holds per-email failure reasons; emails not present in the map are
  828. // considered successful for this inbound.
  829. func (s *ClientService) bulkDelInboundClients(
  830. inboundSvc *InboundService,
  831. inboundId int,
  832. emails []string,
  833. records map[string]*model.ClientRecord,
  834. keepTraffic bool,
  835. ) bulkInboundDeleteResult {
  836. res := bulkInboundDeleteResult{perEmailSkipped: map[string]string{}}
  837. defer lockInbound(inboundId).Unlock()
  838. oldInbound, err := inboundSvc.GetInbound(inboundId)
  839. if err != nil {
  840. logger.Error("Load Old Data Error")
  841. for _, e := range emails {
  842. res.perEmailSkipped[e] = err.Error()
  843. }
  844. return res
  845. }
  846. var settings map[string]any
  847. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  848. for _, e := range emails {
  849. res.perEmailSkipped[e] = err.Error()
  850. }
  851. return res
  852. }
  853. // Match by email — the client's stable identity (see Delete). Removes every
  854. // entry carrying a wanted email, independent of credential drift.
  855. wantedEmails := make(map[string]struct{}, len(emails))
  856. for _, email := range emails {
  857. if records[email] == nil {
  858. res.perEmailSkipped[email] = "client not found"
  859. continue
  860. }
  861. wantedEmails[email] = struct{}{}
  862. }
  863. interfaceClients, _ := settings["clients"].([]any)
  864. newClients := make([]any, 0, len(interfaceClients))
  865. foundEmails := map[string]bool{}
  866. enableByEmail := map[string]bool{}
  867. for _, client := range interfaceClients {
  868. c, ok := client.(map[string]any)
  869. if !ok {
  870. newClients = append(newClients, client)
  871. continue
  872. }
  873. em, _ := c["email"].(string)
  874. if _, found := wantedEmails[em]; found && em != "" {
  875. foundEmails[em] = true
  876. en, _ := c["enable"].(bool)
  877. enableByEmail[em] = en
  878. continue
  879. }
  880. newClients = append(newClients, client)
  881. }
  882. for email := range wantedEmails {
  883. if !foundEmails[email] {
  884. res.perEmailSkipped[email] = "Client Not Found In Inbound"
  885. }
  886. }
  887. db := database.GetDB()
  888. newClients = compactOrphans(db, newClients)
  889. if newClients == nil {
  890. newClients = []any{}
  891. }
  892. settings["clients"] = newClients
  893. newSettings, err := json.MarshalIndent(settings, "", " ")
  894. if err != nil {
  895. for email := range foundEmails {
  896. if _, skip := res.perEmailSkipped[email]; !skip {
  897. res.perEmailSkipped[email] = err.Error()
  898. }
  899. }
  900. return res
  901. }
  902. prevSettings := oldInbound.Settings
  903. oldInbound.Settings = string(newSettings)
  904. foundList := make([]string, 0, len(foundEmails))
  905. for email := range foundEmails {
  906. foundList = append(foundList, email)
  907. }
  908. notDepletedByEmail := map[string]bool{}
  909. if len(foundList) > 0 {
  910. type trafficRow struct {
  911. Email string
  912. Enable bool
  913. }
  914. for _, batch := range chunkStrings(foundList, sqlInChunk) {
  915. var rows []trafficRow
  916. if err := db.Model(xray.ClientTraffic{}).
  917. Where("email IN ?", batch).
  918. Select("email, enable").
  919. Scan(&rows).Error; err == nil {
  920. for _, r := range rows {
  921. notDepletedByEmail[r.Email] = r.Enable
  922. }
  923. }
  924. }
  925. }
  926. var sharedSet map[string]bool
  927. if !keepTraffic {
  928. var sharedErr error
  929. sharedSet, sharedErr = inboundSvc.emailsUsedByOtherInbounds(foundList, inboundId)
  930. if sharedErr != nil {
  931. for email := range foundEmails {
  932. res.perEmailSkipped[email] = sharedErr.Error()
  933. delete(foundEmails, email)
  934. }
  935. return res
  936. }
  937. }
  938. if !keepTraffic {
  939. purge := make([]string, 0, len(foundEmails))
  940. for email := range foundEmails {
  941. if !sharedSet[strings.ToLower(strings.TrimSpace(email))] {
  942. purge = append(purge, email)
  943. }
  944. }
  945. if len(purge) > 0 {
  946. // Serialize the IP/stat purge against the traffic poll to avoid the
  947. // cross-transaction lock-order deadlock on client_traffics.
  948. if delErr := runSerializedTx(func(tx *gorm.DB) error {
  949. if e := inboundSvc.delClientIPsByEmails(tx, purge); e != nil {
  950. logger.Error("Error in delete client IPs")
  951. return e
  952. }
  953. if e := inboundSvc.delClientStatsByEmails(tx, purge); e != nil {
  954. logger.Error("Delete stats Data Error")
  955. return e
  956. }
  957. return nil
  958. }); delErr != nil {
  959. for _, email := range purge {
  960. res.perEmailSkipped[email] = delErr.Error()
  961. delete(foundEmails, email)
  962. }
  963. }
  964. }
  965. }
  966. if oldInbound.NodeID == nil {
  967. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  968. if rterr != nil {
  969. res.needRestart = true
  970. } else {
  971. for email := range foundEmails {
  972. if !enableByEmail[email] || !notDepletedByEmail[email] {
  973. continue
  974. }
  975. err1 := rt.RemoveUser(context.Background(), oldInbound, email)
  976. if err1 == nil {
  977. logger.Debug("Client deleted on", rt.Name(), ":", email)
  978. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  979. logger.Debug("User is already deleted. Nothing to do more...")
  980. } else {
  981. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  982. res.needRestart = true
  983. }
  984. }
  985. }
  986. } else {
  987. rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound)
  988. if perr != nil {
  989. for email := range foundEmails {
  990. res.perEmailSkipped[email] = perr.Error()
  991. delete(foundEmails, email)
  992. }
  993. } else {
  994. // Large batches collapse into one reconcile push rather than M deletes.
  995. if push && len(foundEmails) > nodeBulkPushThreshold {
  996. push = false
  997. }
  998. if push {
  999. // bulkDelInboundClients only runs for full client deletion
  1000. // (BulkDelete), so the node must drop its client record too,
  1001. // not just detach from this inbound (#5797).
  1002. pushFailed := false
  1003. for email := range foundEmails {
  1004. if err1 := rt.DeleteClient(context.Background(), email); err1 != nil {
  1005. logger.Warning("Error in deleting client on", rt.Name(), ":", err1)
  1006. pushFailed = true
  1007. }
  1008. }
  1009. if !pushFailed {
  1010. advancePushedInbound(rt, prevSettings, oldInbound)
  1011. }
  1012. }
  1013. }
  1014. }
  1015. // Serialize against the traffic poll to avoid the cross-transaction
  1016. // lock-order deadlock on inbounds/client_records (runSerializedTx).
  1017. txErr := runSerializedTx(func(tx *gorm.DB) error {
  1018. if err := tx.Save(oldInbound).Error; err != nil {
  1019. return err
  1020. }
  1021. finalClients, err := inboundSvc.GetClients(oldInbound)
  1022. if err != nil {
  1023. return err
  1024. }
  1025. if err := s.SyncInbound(tx, inboundId, finalClients); err != nil {
  1026. return err
  1027. }
  1028. if oldInbound.NodeID != nil {
  1029. return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID)
  1030. }
  1031. return nil
  1032. })
  1033. if txErr != nil {
  1034. for email := range foundEmails {
  1035. if _, skip := res.perEmailSkipped[email]; !skip {
  1036. res.perEmailSkipped[email] = txErr.Error()
  1037. }
  1038. }
  1039. }
  1040. return res
  1041. }
  1042. // BulkCreateResult mirrors BulkAdjustResult for the create flow.
  1043. type BulkCreateResult struct {
  1044. Created int `json:"created"`
  1045. Skipped []BulkCreateReport `json:"skipped,omitempty"`
  1046. }
  1047. type BulkCreateReport struct {
  1048. Email string `json:"email"`
  1049. Reason string `json:"reason"`
  1050. }
  1051. func (s *ClientService) BulkCreate(inboundSvc *InboundService, payloads []ClientCreatePayload) (BulkCreateResult, bool, error) {
  1052. result := BulkCreateResult{}
  1053. if len(payloads) == 0 {
  1054. return result, false, nil
  1055. }
  1056. skip := func(email, reason string) {
  1057. if strings.TrimSpace(email) == "" {
  1058. email = "(missing email)"
  1059. }
  1060. result.Skipped = append(result.Skipped, BulkCreateReport{Email: email, Reason: reason})
  1061. }
  1062. emailSubIDs, err := inboundSvc.getAllEmailSubIDs()
  1063. if err != nil {
  1064. emailSubIDs = nil
  1065. }
  1066. type prepared struct {
  1067. client model.Client
  1068. inboundIds []int
  1069. }
  1070. prep := make([]prepared, 0, len(payloads))
  1071. emails := make([]string, 0, len(payloads))
  1072. subIDs := make([]string, 0, len(payloads))
  1073. seenEmail := make(map[string]struct{}, len(payloads))
  1074. seenSubID := make(map[string]string, len(payloads))
  1075. for i := range payloads {
  1076. client := payloads[i].Client
  1077. email := strings.TrimSpace(client.Email)
  1078. if email == "" {
  1079. skip("", "client email is required")
  1080. continue
  1081. }
  1082. if verr := validateClientEmail(email); verr != nil {
  1083. skip(email, verr.Error())
  1084. continue
  1085. }
  1086. if verr := validateClientSubID(client.SubID); verr != nil {
  1087. skip(email, verr.Error())
  1088. continue
  1089. }
  1090. if len(payloads[i].InboundIds) == 0 {
  1091. skip(email, "at least one inbound is required")
  1092. continue
  1093. }
  1094. client.Email = email
  1095. if client.SubID == "" {
  1096. client.SubID = uuid.NewString()
  1097. }
  1098. if !client.Enable {
  1099. client.Enable = true
  1100. }
  1101. now := time.Now().UnixMilli()
  1102. if client.CreatedAt == 0 {
  1103. client.CreatedAt = now
  1104. }
  1105. client.UpdatedAt = now
  1106. le := strings.ToLower(email)
  1107. if _, dup := seenEmail[le]; dup {
  1108. skip(email, "email already in use: "+email)
  1109. continue
  1110. }
  1111. if owner, ok := seenSubID[client.SubID]; ok && owner != le {
  1112. skip(email, "subId already in use: "+client.SubID)
  1113. continue
  1114. }
  1115. seenEmail[le] = struct{}{}
  1116. seenSubID[client.SubID] = le
  1117. prep = append(prep, prepared{client: client, inboundIds: payloads[i].InboundIds})
  1118. emails = append(emails, email)
  1119. subIDs = append(subIDs, client.SubID)
  1120. }
  1121. if len(prep) == 0 {
  1122. return result, false, nil
  1123. }
  1124. db := database.GetDB()
  1125. const lookupChunk = 400
  1126. existingByEmail := make(map[string]model.ClientRecord, len(emails))
  1127. for start := 0; start < len(emails); start += lookupChunk {
  1128. end := min(start+lookupChunk, len(emails))
  1129. var rows []model.ClientRecord
  1130. if e := db.Where("email IN ?", emails[start:end]).Find(&rows).Error; e != nil {
  1131. return result, false, e
  1132. }
  1133. for i := range rows {
  1134. existingByEmail[strings.ToLower(rows[i].Email)] = rows[i]
  1135. }
  1136. }
  1137. existingSubOwner := make(map[string]string, len(subIDs))
  1138. for start := 0; start < len(subIDs); start += lookupChunk {
  1139. end := min(start+lookupChunk, len(subIDs))
  1140. var rows []model.ClientRecord
  1141. if e := db.Where("sub_id IN ?", subIDs[start:end]).Find(&rows).Error; e != nil {
  1142. return result, false, e
  1143. }
  1144. for i := range rows {
  1145. existingSubOwner[rows[i].SubID] = strings.ToLower(rows[i].Email)
  1146. }
  1147. }
  1148. inboundCache := make(map[int]*model.Inbound)
  1149. getIb := func(id int) (*model.Inbound, error) {
  1150. if ib, ok := inboundCache[id]; ok {
  1151. return ib, nil
  1152. }
  1153. ib, e := inboundSvc.GetInbound(id)
  1154. if e != nil {
  1155. return nil, e
  1156. }
  1157. inboundCache[id] = ib
  1158. return ib, nil
  1159. }
  1160. byInbound := make(map[int][]model.Client)
  1161. idxByInbound := make(map[int][]int)
  1162. inboundOrder := make([]int, 0)
  1163. failed := make([]bool, len(prep))
  1164. reason := make([]string, len(prep))
  1165. for idx := range prep {
  1166. le := strings.ToLower(prep[idx].client.Email)
  1167. if rec, ok := existingByEmail[le]; ok {
  1168. if rec.SubID != prep[idx].client.SubID {
  1169. failed[idx] = true
  1170. reason[idx] = "email already in use: " + prep[idx].client.Email
  1171. continue
  1172. }
  1173. if prep[idx].client.ID == "" {
  1174. prep[idx].client.ID = rec.UUID
  1175. }
  1176. if prep[idx].client.Password == "" {
  1177. prep[idx].client.Password = rec.Password
  1178. }
  1179. if prep[idx].client.Auth == "" {
  1180. prep[idx].client.Auth = rec.Auth
  1181. }
  1182. if prep[idx].client.Secret == "" {
  1183. prep[idx].client.Secret = rec.Secret
  1184. }
  1185. }
  1186. if owner, ok := existingSubOwner[prep[idx].client.SubID]; ok && owner != le {
  1187. failed[idx] = true
  1188. reason[idx] = "subId already in use: " + prep[idx].client.SubID
  1189. continue
  1190. }
  1191. ok := true
  1192. for _, ibId := range prep[idx].inboundIds {
  1193. ib, e := getIb(ibId)
  1194. if e != nil {
  1195. failed[idx] = true
  1196. reason[idx] = e.Error()
  1197. ok = false
  1198. break
  1199. }
  1200. if e := s.fillProtocolDefaults(&prep[idx].client, ib); e != nil {
  1201. failed[idx] = true
  1202. reason[idx] = e.Error()
  1203. ok = false
  1204. break
  1205. }
  1206. }
  1207. if !ok {
  1208. continue
  1209. }
  1210. for _, ibId := range prep[idx].inboundIds {
  1211. ib, _ := getIb(ibId)
  1212. if _, seen := byInbound[ibId]; !seen {
  1213. inboundOrder = append(inboundOrder, ibId)
  1214. }
  1215. byInbound[ibId] = append(byInbound[ibId], clientWithInboundFlow(prep[idx].client, ib))
  1216. idxByInbound[ibId] = append(idxByInbound[ibId], idx)
  1217. }
  1218. }
  1219. needRestart := false
  1220. for _, ibId := range inboundOrder {
  1221. payload, e := json.Marshal(map[string][]model.Client{"clients": byInbound[ibId]})
  1222. if e == nil {
  1223. var nr bool
  1224. nr, e = s.addInboundClient(inboundSvc, &model.Inbound{Id: ibId, Settings: string(payload)}, emailSubIDs)
  1225. if e == nil && nr {
  1226. needRestart = true
  1227. }
  1228. }
  1229. if e != nil {
  1230. for _, idx := range idxByInbound[ibId] {
  1231. failed[idx] = true
  1232. if reason[idx] == "" {
  1233. reason[idx] = e.Error()
  1234. }
  1235. }
  1236. }
  1237. }
  1238. for idx := range prep {
  1239. if failed[idx] {
  1240. skip(prep[idx].client.Email, reason[idx])
  1241. } else {
  1242. result.Created++
  1243. }
  1244. }
  1245. return result, needRestart, nil
  1246. }
  1247. func (s *ClientService) DelDepleted(inboundSvc *InboundService) (int, bool, error) {
  1248. db := database.GetDB()
  1249. now := time.Now().UnixMilli()
  1250. depletedClause := "reset = 0 and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))"
  1251. var rows []xray.ClientTraffic
  1252. if err := db.Where(depletedClause, now).Find(&rows).Error; err != nil {
  1253. return 0, false, err
  1254. }
  1255. if len(rows) == 0 {
  1256. return 0, false, nil
  1257. }
  1258. seen := make(map[string]struct{}, len(rows))
  1259. emails := make([]string, 0, len(rows))
  1260. for _, r := range rows {
  1261. if r.Email == "" {
  1262. continue
  1263. }
  1264. if _, ok := seen[r.Email]; ok {
  1265. continue
  1266. }
  1267. seen[r.Email] = struct{}{}
  1268. emails = append(emails, r.Email)
  1269. }
  1270. if len(emails) == 0 {
  1271. return 0, false, nil
  1272. }
  1273. res, needRestart, err := s.BulkDelete(inboundSvc, emails, false)
  1274. if err != nil {
  1275. return res.Deleted, needRestart, err
  1276. }
  1277. return res.Deleted, needRestart, nil
  1278. }
  1279. type BulkSetEnableResult struct {
  1280. Changed int `json:"changed"`
  1281. Skipped []BulkSetEnableReport `json:"skipped,omitempty"`
  1282. }
  1283. type BulkSetEnableReport struct {
  1284. Email string `json:"email"`
  1285. Reason string `json:"reason"`
  1286. }
  1287. func (s *ClientService) BulkSetEnable(inboundSvc *InboundService, emails []string, enable bool) (BulkSetEnableResult, bool, error) {
  1288. result := BulkSetEnableResult{}
  1289. seen := map[string]struct{}{}
  1290. cleanEmails := make([]string, 0, len(emails))
  1291. for _, e := range emails {
  1292. e = strings.TrimSpace(e)
  1293. if e == "" {
  1294. continue
  1295. }
  1296. if _, ok := seen[e]; ok {
  1297. continue
  1298. }
  1299. seen[e] = struct{}{}
  1300. cleanEmails = append(cleanEmails, e)
  1301. }
  1302. if len(cleanEmails) == 0 {
  1303. return result, false, nil
  1304. }
  1305. db := database.GetDB()
  1306. var records []model.ClientRecord
  1307. for _, batch := range chunkStrings(cleanEmails, sqlInChunk) {
  1308. var rows []model.ClientRecord
  1309. if err := db.Where("email IN ?", batch).Find(&rows).Error; err != nil {
  1310. return result, false, err
  1311. }
  1312. records = append(records, rows...)
  1313. }
  1314. recordsByEmail := make(map[string]*model.ClientRecord, len(records))
  1315. for i := range records {
  1316. recordsByEmail[records[i].Email] = &records[i]
  1317. }
  1318. skippedReasons := map[string]string{}
  1319. for _, email := range cleanEmails {
  1320. if _, ok := recordsByEmail[email]; !ok {
  1321. skippedReasons[email] = "client not found"
  1322. }
  1323. }
  1324. clientIds := make([]int, 0, len(recordsByEmail))
  1325. recordIdToEmail := make(map[int]string, len(recordsByEmail))
  1326. for _, r := range recordsByEmail {
  1327. clientIds = append(clientIds, r.Id)
  1328. recordIdToEmail[r.Id] = r.Email
  1329. }
  1330. emailsByInbound := map[int][]string{}
  1331. if len(clientIds) > 0 {
  1332. var mappings []model.ClientInbound
  1333. for _, batch := range chunkInts(clientIds, sqlInChunk) {
  1334. var rows []model.ClientInbound
  1335. if err := db.Where("client_id IN ?", batch).Find(&rows).Error; err != nil {
  1336. return result, false, err
  1337. }
  1338. mappings = append(mappings, rows...)
  1339. }
  1340. for _, m := range mappings {
  1341. email, ok := recordIdToEmail[m.ClientId]
  1342. if !ok {
  1343. continue
  1344. }
  1345. emailsByInbound[m.InboundId] = append(emailsByInbound[m.InboundId], email)
  1346. }
  1347. }
  1348. needRestart := false
  1349. for inboundId, ibEmails := range emailsByInbound {
  1350. ibRes := s.bulkSetEnableInboundClients(inboundSvc, inboundId, ibEmails, enable)
  1351. if ibRes.needRestart {
  1352. needRestart = true
  1353. }
  1354. for email, reason := range ibRes.perEmailSkipped {
  1355. if _, already := skippedReasons[email]; !already {
  1356. skippedReasons[email] = reason
  1357. }
  1358. }
  1359. }
  1360. successEmails := make([]string, 0, len(recordsByEmail))
  1361. for email := range recordsByEmail {
  1362. if _, skipped := skippedReasons[email]; skipped {
  1363. continue
  1364. }
  1365. successEmails = append(successEmails, email)
  1366. }
  1367. if len(successEmails) > 0 {
  1368. now := time.Now().UnixMilli()
  1369. if err := runSerializedTx(func(tx *gorm.DB) error {
  1370. for _, batch := range chunkStrings(successEmails, sqlInChunk) {
  1371. if e := tx.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Update("enable", enable).Error; e != nil {
  1372. return e
  1373. }
  1374. if e := tx.Model(&model.ClientRecord{}).Where("email IN ?", batch).
  1375. Updates(map[string]any{"enable": enable, "updated_at": now}).Error; e != nil {
  1376. return e
  1377. }
  1378. }
  1379. return nil
  1380. }); err != nil {
  1381. return result, needRestart, err
  1382. }
  1383. }
  1384. result.Changed = len(successEmails)
  1385. for email, reason := range skippedReasons {
  1386. result.Skipped = append(result.Skipped, BulkSetEnableReport{Email: email, Reason: reason})
  1387. }
  1388. return result, needRestart, nil
  1389. }
  1390. type bulkSetEnableInboundResult struct {
  1391. perEmailSkipped map[string]string
  1392. needRestart bool
  1393. }
  1394. func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService, inboundId int, emails []string, enable bool) bulkSetEnableInboundResult {
  1395. res := bulkSetEnableInboundResult{perEmailSkipped: map[string]string{}}
  1396. defer lockInbound(inboundId).Unlock()
  1397. oldInbound, err := inboundSvc.GetInbound(inboundId)
  1398. if err != nil {
  1399. for _, e := range emails {
  1400. res.perEmailSkipped[e] = err.Error()
  1401. }
  1402. return res
  1403. }
  1404. var settings map[string]any
  1405. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  1406. for _, e := range emails {
  1407. res.perEmailSkipped[e] = err.Error()
  1408. }
  1409. return res
  1410. }
  1411. wanted := make(map[string]struct{}, len(emails))
  1412. for _, email := range emails {
  1413. wanted[email] = struct{}{}
  1414. }
  1415. cipher := ""
  1416. if oldInbound.Protocol == model.Shadowsocks {
  1417. cipher, _ = settings["method"].(string)
  1418. }
  1419. type changedClient struct {
  1420. email string
  1421. wasEnable bool
  1422. client model.Client
  1423. }
  1424. var changed []changedClient
  1425. found := map[string]bool{}
  1426. nowMs := time.Now().UnixMilli()
  1427. interfaceClients, _ := settings["clients"].([]any)
  1428. for i, c := range interfaceClients {
  1429. entry, ok := c.(map[string]any)
  1430. if !ok {
  1431. continue
  1432. }
  1433. email, _ := entry["email"].(string)
  1434. if _, want := wanted[email]; !want || email == "" {
  1435. continue
  1436. }
  1437. found[email] = true
  1438. prev, _ := entry["enable"].(bool)
  1439. if prev == enable {
  1440. continue
  1441. }
  1442. entry["enable"] = enable
  1443. entry["updated_at"] = nowMs
  1444. interfaceClients[i] = entry
  1445. // Build the pushed client from the inbound JSON (the per-inbound source of
  1446. // truth), so a remote UpdateUser carries every field and never zeroes
  1447. // subId/totalGB/expiry from drifting ClientRecord columns (#4628/#4792).
  1448. var parsed model.Client
  1449. if b, mErr := json.Marshal(entry); mErr == nil {
  1450. _ = json.Unmarshal(b, &parsed)
  1451. }
  1452. parsed.Email = email
  1453. parsed.Enable = enable
  1454. changed = append(changed, changedClient{email: email, wasEnable: prev, client: parsed})
  1455. }
  1456. for email := range wanted {
  1457. if !found[email] {
  1458. res.perEmailSkipped[email] = "Client Not Found In Inbound"
  1459. }
  1460. }
  1461. if len(changed) == 0 {
  1462. return res
  1463. }
  1464. settings["clients"] = interfaceClients
  1465. newSettings, err := json.MarshalIndent(settings, "", " ")
  1466. if err != nil {
  1467. for _, ch := range changed {
  1468. res.perEmailSkipped[ch.email] = err.Error()
  1469. }
  1470. return res
  1471. }
  1472. prevSettings := oldInbound.Settings
  1473. oldInbound.Settings = string(newSettings)
  1474. rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound)
  1475. if perr != nil {
  1476. for _, ch := range changed {
  1477. res.perEmailSkipped[ch.email] = perr.Error()
  1478. }
  1479. return res
  1480. }
  1481. if oldInbound.NodeID != nil && push && len(changed) > nodeBulkPushThreshold {
  1482. push = false
  1483. }
  1484. txErr := runSerializedTx(func(tx *gorm.DB) error {
  1485. if e := tx.Save(oldInbound).Error; e != nil {
  1486. return e
  1487. }
  1488. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  1489. if gcErr != nil {
  1490. return gcErr
  1491. }
  1492. if err := s.SyncInbound(tx, inboundId, finalClients); err != nil {
  1493. return err
  1494. }
  1495. if oldInbound.NodeID != nil {
  1496. return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID)
  1497. }
  1498. return nil
  1499. })
  1500. if txErr != nil {
  1501. for _, ch := range changed {
  1502. res.perEmailSkipped[ch.email] = txErr.Error()
  1503. }
  1504. return res
  1505. }
  1506. if oldInbound.NodeID == nil {
  1507. if !push {
  1508. res.needRestart = true
  1509. } else {
  1510. for _, ch := range changed {
  1511. if enable {
  1512. err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
  1513. "email": ch.client.Email,
  1514. "id": ch.client.ID,
  1515. "security": ch.client.Security,
  1516. "flow": ch.client.Flow,
  1517. "auth": ch.client.Auth,
  1518. "password": ch.client.Password,
  1519. "cipher": cipher,
  1520. })
  1521. if err1 != nil {
  1522. logger.Debug("Error in adding client on", rt.Name(), ":", err1)
  1523. res.needRestart = true
  1524. }
  1525. } else if ch.wasEnable {
  1526. err1 := rt.RemoveUser(context.Background(), oldInbound, ch.email)
  1527. if err1 != nil && !strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", ch.email)) {
  1528. logger.Debug("Error in removing client on", rt.Name(), ":", err1)
  1529. res.needRestart = true
  1530. }
  1531. }
  1532. }
  1533. }
  1534. } else if push {
  1535. pushFailed := false
  1536. for _, ch := range changed {
  1537. updated := ch.client
  1538. updated.UpdatedAt = nowMs
  1539. if err1 := rt.UpdateUser(context.Background(), oldInbound, ch.email, updated); err1 != nil {
  1540. logger.Warning("Error in updating client on", rt.Name(), ":", err1)
  1541. pushFailed = true
  1542. }
  1543. }
  1544. if !pushFailed {
  1545. advancePushedInbound(rt, prevSettings, oldInbound)
  1546. }
  1547. }
  1548. return res
  1549. }