1
0

client_bulk.go 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657
  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. oldInbound.Settings = string(newSettings)
  601. // A flow change rewrites the user's xray config, which the lightweight
  602. // UpdateUser push below does not carry. Local nodes reload via restart;
  603. // remote nodes get a full reconcile (MarkNodeDirty) instead of a per-user push.
  604. if flowChanged && oldInbound.NodeID == nil {
  605. res.needRestart = true
  606. }
  607. // Serialize against the traffic poll to avoid the cross-transaction
  608. // lock-order deadlock on inbounds/client_records (runSerializedTx).
  609. txErr := runSerializedTx(func(tx *gorm.DB) error {
  610. if err := tx.Save(oldInbound).Error; err != nil {
  611. return err
  612. }
  613. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  614. if gcErr != nil {
  615. return gcErr
  616. }
  617. if err := s.SyncInbound(tx, inboundId, finalClients); err != nil {
  618. return err
  619. }
  620. if oldInbound.NodeID != nil {
  621. return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID)
  622. }
  623. return nil
  624. })
  625. if txErr != nil {
  626. for email := range foundEmails {
  627. if _, skip := res.perEmailSkipped[email]; !skip {
  628. res.perEmailSkipped[email] = txErr.Error()
  629. }
  630. }
  631. } else if oldInbound.NodeID != nil && !flowChanged && len(foundEmails) <= nodeBulkPushThreshold {
  632. rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound)
  633. if perr != nil {
  634. logger.Warning("BulkAdjust: node runtime lookup after commit failed:", perr)
  635. } else if push {
  636. for email := range foundEmails {
  637. entry := plan[email]
  638. updated := *entry.record.ToClient()
  639. if entry.applyExpiry {
  640. updated.ExpiryTime = entry.newExpiry
  641. }
  642. if entry.applyTotal {
  643. updated.TotalGB = entry.newTotal
  644. }
  645. updated.UpdatedAt = nowMs
  646. if err1 := rt.UpdateUser(context.Background(), oldInbound, email, updated); err1 != nil {
  647. logger.Warning("Error in updating client on", rt.Name(), ":", err1)
  648. }
  649. }
  650. }
  651. }
  652. return res
  653. }
  654. // BulkDeleteResult mirrors BulkAdjustResult: total deleted plus per-email
  655. // skip reasons when an email could not be processed.
  656. type BulkDeleteResult struct {
  657. Deleted int `json:"deleted"`
  658. Skipped []BulkDeleteReport `json:"skipped,omitempty"`
  659. }
  660. type BulkDeleteReport struct {
  661. Email string `json:"email"`
  662. Reason string `json:"reason"`
  663. }
  664. // BulkDelete removes every client in the list in one optimized pass.
  665. // Instead of running the full single-delete pipeline N times (which would
  666. // re-read, re-parse, and re-write each inbound's settings JSON for every
  667. // email), it groups emails by inbound and performs a single
  668. // read-modify-write per inbound. Per-row DB cleanups are also batched with
  669. // IN-clause queries at the end. Errors on a particular email are recorded
  670. // in the Skipped list and processing continues for the rest.
  671. func (s *ClientService) BulkDelete(inboundSvc *InboundService, emails []string, keepTraffic bool) (BulkDeleteResult, bool, error) {
  672. result := BulkDeleteResult{}
  673. seen := map[string]struct{}{}
  674. cleanEmails := make([]string, 0, len(emails))
  675. for _, e := range emails {
  676. e = strings.TrimSpace(e)
  677. if e == "" {
  678. continue
  679. }
  680. if _, ok := seen[e]; ok {
  681. continue
  682. }
  683. seen[e] = struct{}{}
  684. cleanEmails = append(cleanEmails, e)
  685. }
  686. if len(cleanEmails) == 0 {
  687. return result, false, nil
  688. }
  689. db := database.GetDB()
  690. var records []model.ClientRecord
  691. for _, batch := range chunkStrings(cleanEmails, sqlInChunk) {
  692. var rows []model.ClientRecord
  693. if err := db.Where("email IN ?", batch).Find(&rows).Error; err != nil {
  694. return result, false, err
  695. }
  696. records = append(records, rows...)
  697. }
  698. recordsByEmail := make(map[string]*model.ClientRecord, len(records))
  699. tombstoneEmails := make([]string, 0, len(records))
  700. for i := range records {
  701. recordsByEmail[records[i].Email] = &records[i]
  702. tombstoneEmails = append(tombstoneEmails, records[i].Email)
  703. }
  704. tombstoneClientEmails(tombstoneEmails)
  705. skippedReasons := map[string]string{}
  706. for _, email := range cleanEmails {
  707. if _, ok := recordsByEmail[email]; !ok {
  708. skippedReasons[email] = "client not found"
  709. }
  710. }
  711. clientIds := make([]int, 0, len(recordsByEmail))
  712. recordIdToEmail := make(map[int]string, len(recordsByEmail))
  713. for _, r := range recordsByEmail {
  714. clientIds = append(clientIds, r.Id)
  715. recordIdToEmail[r.Id] = r.Email
  716. }
  717. emailsByInbound := map[int][]string{}
  718. if len(clientIds) > 0 {
  719. var mappings []model.ClientInbound
  720. for _, batch := range chunkInts(clientIds, sqlInChunk) {
  721. var rows []model.ClientInbound
  722. if err := db.Where("client_id IN ?", batch).Find(&rows).Error; err != nil {
  723. return result, false, err
  724. }
  725. mappings = append(mappings, rows...)
  726. }
  727. for _, m := range mappings {
  728. email, ok := recordIdToEmail[m.ClientId]
  729. if !ok {
  730. continue
  731. }
  732. emailsByInbound[m.InboundId] = append(emailsByInbound[m.InboundId], email)
  733. }
  734. }
  735. needRestart := false
  736. for inboundId, ibEmails := range emailsByInbound {
  737. ibResult := s.bulkDelInboundClients(inboundSvc, inboundId, ibEmails, recordsByEmail, keepTraffic)
  738. if ibResult.needRestart {
  739. needRestart = true
  740. }
  741. for email, reason := range ibResult.perEmailSkipped {
  742. if _, already := skippedReasons[email]; !already {
  743. skippedReasons[email] = reason
  744. }
  745. }
  746. }
  747. successEmails := make([]string, 0, len(recordsByEmail))
  748. successIds := make([]int, 0, len(recordsByEmail))
  749. failedEmails := make([]string, 0, len(recordsByEmail))
  750. successSubIDs := make([]string, 0, len(recordsByEmail))
  751. for email, rec := range recordsByEmail {
  752. if _, skipped := skippedReasons[email]; skipped {
  753. failedEmails = append(failedEmails, email)
  754. continue
  755. }
  756. successEmails = append(successEmails, email)
  757. successIds = append(successIds, rec.Id)
  758. successSubIDs = append(successSubIDs, rec.SubID)
  759. }
  760. withdrawClientTombstones(failedEmails...)
  761. if len(successIds) > 0 {
  762. // Serialize the row cleanup against the traffic poll to avoid the
  763. // cross-transaction lock-order deadlock on client_traffics/inbounds.
  764. if err := runSerializedTx(func(tx *gorm.DB) error {
  765. if e := adjustGroupBaselinesForRemovedTraffic(tx, successEmails); e != nil {
  766. return e
  767. }
  768. if e := clearClientHwidsBySubIDTx(tx, successSubIDs...); e != nil {
  769. return e
  770. }
  771. for _, batch := range chunkInts(successIds, sqlInChunk) {
  772. if e := tx.Where("client_id IN ?", batch).Delete(&model.ClientInbound{}).Error; e != nil {
  773. return e
  774. }
  775. if e := tx.Where("client_id IN ?", batch).Delete(&model.ClientExternalLink{}).Error; e != nil {
  776. return e
  777. }
  778. }
  779. if !keepTraffic && len(successEmails) > 0 {
  780. for _, batch := range chunkStrings(successEmails, sqlInChunk) {
  781. if e := tx.Where("email IN ?", batch).Delete(&xray.ClientTraffic{}).Error; e != nil {
  782. return e
  783. }
  784. if e := tx.Where("client_email IN ?", batch).Delete(&model.InboundClientIps{}).Error; e != nil {
  785. return e
  786. }
  787. }
  788. }
  789. for _, batch := range chunkInts(successIds, sqlInChunk) {
  790. if e := tx.Where("id IN ?", batch).Delete(&model.ClientRecord{}).Error; e != nil {
  791. return e
  792. }
  793. }
  794. return nil
  795. }); err != nil {
  796. withdrawClientTombstones(successEmails...)
  797. return result, needRestart, err
  798. }
  799. }
  800. result.Deleted = len(successEmails)
  801. for email, reason := range skippedReasons {
  802. result.Skipped = append(result.Skipped, BulkDeleteReport{Email: email, Reason: reason})
  803. }
  804. return result, needRestart, nil
  805. }
  806. type bulkInboundDeleteResult struct {
  807. perEmailSkipped map[string]string
  808. needRestart bool
  809. }
  810. // bulkDelInboundClients removes multiple clients from a single inbound's
  811. // settings JSON in one read-modify-write cycle, runs the xray runtime
  812. // RemoveUser/DeleteUser calls, and persists the inbound. The returned map
  813. // holds per-email failure reasons; emails not present in the map are
  814. // considered successful for this inbound.
  815. func (s *ClientService) bulkDelInboundClients(
  816. inboundSvc *InboundService,
  817. inboundId int,
  818. emails []string,
  819. records map[string]*model.ClientRecord,
  820. keepTraffic bool,
  821. ) bulkInboundDeleteResult {
  822. res := bulkInboundDeleteResult{perEmailSkipped: map[string]string{}}
  823. defer lockInbound(inboundId).Unlock()
  824. oldInbound, err := inboundSvc.GetInbound(inboundId)
  825. if err != nil {
  826. logger.Error("Load Old Data Error")
  827. for _, e := range emails {
  828. res.perEmailSkipped[e] = err.Error()
  829. }
  830. return res
  831. }
  832. var settings map[string]any
  833. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  834. for _, e := range emails {
  835. res.perEmailSkipped[e] = err.Error()
  836. }
  837. return res
  838. }
  839. // Match by email — the client's stable identity (see Delete). Removes every
  840. // entry carrying a wanted email, independent of credential drift.
  841. wantedEmails := make(map[string]struct{}, len(emails))
  842. for _, email := range emails {
  843. if records[email] == nil {
  844. res.perEmailSkipped[email] = "client not found"
  845. continue
  846. }
  847. wantedEmails[email] = struct{}{}
  848. }
  849. interfaceClients, _ := settings["clients"].([]any)
  850. newClients := make([]any, 0, len(interfaceClients))
  851. foundEmails := map[string]bool{}
  852. enableByEmail := map[string]bool{}
  853. for _, client := range interfaceClients {
  854. c, ok := client.(map[string]any)
  855. if !ok {
  856. newClients = append(newClients, client)
  857. continue
  858. }
  859. em, _ := c["email"].(string)
  860. if _, found := wantedEmails[em]; found && em != "" {
  861. foundEmails[em] = true
  862. en, _ := c["enable"].(bool)
  863. enableByEmail[em] = en
  864. continue
  865. }
  866. newClients = append(newClients, client)
  867. }
  868. for email := range wantedEmails {
  869. if !foundEmails[email] {
  870. res.perEmailSkipped[email] = "Client Not Found In Inbound"
  871. }
  872. }
  873. db := database.GetDB()
  874. newClients = compactOrphans(db, newClients)
  875. if newClients == nil {
  876. newClients = []any{}
  877. }
  878. settings["clients"] = newClients
  879. newSettings, err := json.MarshalIndent(settings, "", " ")
  880. if err != nil {
  881. for email := range foundEmails {
  882. if _, skip := res.perEmailSkipped[email]; !skip {
  883. res.perEmailSkipped[email] = err.Error()
  884. }
  885. }
  886. return res
  887. }
  888. oldInbound.Settings = string(newSettings)
  889. foundList := make([]string, 0, len(foundEmails))
  890. for email := range foundEmails {
  891. foundList = append(foundList, email)
  892. }
  893. notDepletedByEmail := map[string]bool{}
  894. if len(foundList) > 0 {
  895. type trafficRow struct {
  896. Email string
  897. Enable bool
  898. }
  899. for _, batch := range chunkStrings(foundList, sqlInChunk) {
  900. var rows []trafficRow
  901. if err := db.Model(xray.ClientTraffic{}).
  902. Where("email IN ?", batch).
  903. Select("email, enable").
  904. Scan(&rows).Error; err == nil {
  905. for _, r := range rows {
  906. notDepletedByEmail[r.Email] = r.Enable
  907. }
  908. }
  909. }
  910. }
  911. var sharedSet map[string]bool
  912. if !keepTraffic {
  913. var sharedErr error
  914. sharedSet, sharedErr = inboundSvc.emailsUsedByOtherInbounds(foundList, inboundId)
  915. if sharedErr != nil {
  916. for email := range foundEmails {
  917. res.perEmailSkipped[email] = sharedErr.Error()
  918. delete(foundEmails, email)
  919. }
  920. return res
  921. }
  922. }
  923. if !keepTraffic {
  924. purge := make([]string, 0, len(foundEmails))
  925. for email := range foundEmails {
  926. if !sharedSet[strings.ToLower(strings.TrimSpace(email))] {
  927. purge = append(purge, email)
  928. }
  929. }
  930. if len(purge) > 0 {
  931. // Serialize the IP/stat purge against the traffic poll to avoid the
  932. // cross-transaction lock-order deadlock on client_traffics.
  933. if delErr := runSerializedTx(func(tx *gorm.DB) error {
  934. if e := inboundSvc.delClientIPsByEmails(tx, purge); e != nil {
  935. logger.Error("Error in delete client IPs")
  936. return e
  937. }
  938. if e := inboundSvc.delClientStatsByEmails(tx, purge); e != nil {
  939. logger.Error("Delete stats Data Error")
  940. return e
  941. }
  942. return nil
  943. }); delErr != nil {
  944. for _, email := range purge {
  945. res.perEmailSkipped[email] = delErr.Error()
  946. delete(foundEmails, email)
  947. }
  948. }
  949. }
  950. }
  951. // Serialize against the traffic poll to avoid the cross-transaction
  952. // lock-order deadlock on inbounds/client_records (runSerializedTx).
  953. txErr := runSerializedTx(func(tx *gorm.DB) error {
  954. if err := tx.Save(oldInbound).Error; err != nil {
  955. return err
  956. }
  957. finalClients, err := inboundSvc.GetClients(oldInbound)
  958. if err != nil {
  959. return err
  960. }
  961. if err := s.SyncInbound(tx, inboundId, finalClients); err != nil {
  962. return err
  963. }
  964. if oldInbound.NodeID != nil {
  965. return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID)
  966. }
  967. return nil
  968. })
  969. if txErr != nil {
  970. for email := range foundEmails {
  971. if _, skip := res.perEmailSkipped[email]; !skip {
  972. res.perEmailSkipped[email] = txErr.Error()
  973. }
  974. }
  975. } else if oldInbound.NodeID == nil {
  976. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  977. if rterr != nil {
  978. res.needRestart = true
  979. } else {
  980. for email := range foundEmails {
  981. if !enableByEmail[email] || !notDepletedByEmail[email] {
  982. continue
  983. }
  984. err1 := rt.RemoveUser(context.Background(), oldInbound, email)
  985. if err1 == nil {
  986. logger.Debug("Client deleted on", rt.Name(), ":", email)
  987. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  988. logger.Debug("User is already deleted. Nothing to do more...")
  989. } else {
  990. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  991. res.needRestart = true
  992. }
  993. }
  994. }
  995. } else if len(foundEmails) <= nodeBulkPushThreshold {
  996. rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound)
  997. if perr != nil {
  998. logger.Warning("BulkDelete: node runtime lookup after commit failed:", perr)
  999. } else if push {
  1000. for email := range foundEmails {
  1001. if err1 := rt.DeleteClient(context.Background(), email); err1 != nil {
  1002. logger.Warning("Error in deleting client on", rt.Name(), ":", err1)
  1003. }
  1004. }
  1005. }
  1006. }
  1007. return res
  1008. }
  1009. // BulkCreateResult mirrors BulkAdjustResult for the create flow.
  1010. type BulkCreateResult struct {
  1011. Created int `json:"created"`
  1012. Skipped []BulkCreateReport `json:"skipped,omitempty"`
  1013. }
  1014. type BulkCreateReport struct {
  1015. Email string `json:"email"`
  1016. Reason string `json:"reason"`
  1017. }
  1018. func (s *ClientService) BulkCreate(inboundSvc *InboundService, payloads []ClientCreatePayload) (BulkCreateResult, bool, error) {
  1019. result := BulkCreateResult{}
  1020. if len(payloads) == 0 {
  1021. return result, false, nil
  1022. }
  1023. skip := func(email, reason string) {
  1024. if strings.TrimSpace(email) == "" {
  1025. email = "(missing email)"
  1026. }
  1027. result.Skipped = append(result.Skipped, BulkCreateReport{Email: email, Reason: reason})
  1028. }
  1029. emailSubIDs, err := inboundSvc.getAllEmailSubIDs()
  1030. if err != nil {
  1031. emailSubIDs = nil
  1032. }
  1033. type prepared struct {
  1034. client model.Client
  1035. inboundIds []int
  1036. limitHwid int
  1037. }
  1038. prep := make([]prepared, 0, len(payloads))
  1039. emails := make([]string, 0, len(payloads))
  1040. subIDs := make([]string, 0, len(payloads))
  1041. seenEmail := make(map[string]struct{}, len(payloads))
  1042. seenSubID := make(map[string]string, len(payloads))
  1043. for i := range payloads {
  1044. client := payloads[i].Client
  1045. email := strings.TrimSpace(client.Email)
  1046. if email == "" {
  1047. skip("", "client email is required")
  1048. continue
  1049. }
  1050. if verr := validateClientEmail(email); verr != nil {
  1051. skip(email, verr.Error())
  1052. continue
  1053. }
  1054. if verr := validateClientSubID(client.SubID); verr != nil {
  1055. skip(email, verr.Error())
  1056. continue
  1057. }
  1058. if len(payloads[i].InboundIds) == 0 {
  1059. skip(email, "at least one inbound is required")
  1060. continue
  1061. }
  1062. client.Email = email
  1063. if client.SubID == "" {
  1064. client.SubID = uuid.NewString()
  1065. }
  1066. if !client.Enable {
  1067. client.Enable = true
  1068. }
  1069. now := time.Now().UnixMilli()
  1070. if client.CreatedAt == 0 {
  1071. client.CreatedAt = now
  1072. }
  1073. client.UpdatedAt = now
  1074. le := strings.ToLower(email)
  1075. if _, dup := seenEmail[le]; dup {
  1076. skip(email, "email already in use: "+email)
  1077. continue
  1078. }
  1079. if owner, ok := seenSubID[client.SubID]; ok && owner != le {
  1080. skip(email, "subId already in use: "+client.SubID)
  1081. continue
  1082. }
  1083. seenEmail[le] = struct{}{}
  1084. seenSubID[client.SubID] = le
  1085. prep = append(prep, prepared{client: client, inboundIds: payloads[i].InboundIds, limitHwid: payloads[i].LimitHwid})
  1086. emails = append(emails, email)
  1087. subIDs = append(subIDs, client.SubID)
  1088. }
  1089. if len(prep) == 0 {
  1090. return result, false, nil
  1091. }
  1092. db := database.GetDB()
  1093. const lookupChunk = 400
  1094. existingByEmail := make(map[string]model.ClientRecord, len(emails))
  1095. for start := 0; start < len(emails); start += lookupChunk {
  1096. end := min(start+lookupChunk, len(emails))
  1097. var rows []model.ClientRecord
  1098. if e := db.Where("email IN ?", emails[start:end]).Find(&rows).Error; e != nil {
  1099. return result, false, e
  1100. }
  1101. for i := range rows {
  1102. existingByEmail[strings.ToLower(rows[i].Email)] = rows[i]
  1103. }
  1104. }
  1105. existingSubOwner := make(map[string]string, len(subIDs))
  1106. for start := 0; start < len(subIDs); start += lookupChunk {
  1107. end := min(start+lookupChunk, len(subIDs))
  1108. var rows []model.ClientRecord
  1109. if e := db.Where("sub_id IN ?", subIDs[start:end]).Find(&rows).Error; e != nil {
  1110. return result, false, e
  1111. }
  1112. for i := range rows {
  1113. existingSubOwner[rows[i].SubID] = strings.ToLower(rows[i].Email)
  1114. }
  1115. }
  1116. inboundCache := make(map[int]*model.Inbound)
  1117. getIb := func(id int) (*model.Inbound, error) {
  1118. if ib, ok := inboundCache[id]; ok {
  1119. return ib, nil
  1120. }
  1121. ib, e := inboundSvc.GetInbound(id)
  1122. if e != nil {
  1123. return nil, e
  1124. }
  1125. inboundCache[id] = ib
  1126. return ib, nil
  1127. }
  1128. byInbound := make(map[int][]model.Client)
  1129. idxByInbound := make(map[int][]int)
  1130. inboundOrder := make([]int, 0)
  1131. failed := make([]bool, len(prep))
  1132. reason := make([]string, len(prep))
  1133. for idx := range prep {
  1134. le := strings.ToLower(prep[idx].client.Email)
  1135. if rec, ok := existingByEmail[le]; ok {
  1136. if rec.SubID != prep[idx].client.SubID {
  1137. failed[idx] = true
  1138. reason[idx] = "email already in use: " + prep[idx].client.Email
  1139. continue
  1140. }
  1141. if prep[idx].client.ID == "" {
  1142. prep[idx].client.ID = rec.UUID
  1143. }
  1144. if prep[idx].client.Password == "" {
  1145. prep[idx].client.Password = rec.Password
  1146. }
  1147. if prep[idx].client.Auth == "" {
  1148. prep[idx].client.Auth = rec.Auth
  1149. }
  1150. if prep[idx].client.Secret == "" {
  1151. prep[idx].client.Secret = rec.Secret
  1152. }
  1153. }
  1154. if owner, ok := existingSubOwner[prep[idx].client.SubID]; ok && owner != le {
  1155. failed[idx] = true
  1156. reason[idx] = "subId already in use: " + prep[idx].client.SubID
  1157. continue
  1158. }
  1159. ok := true
  1160. for _, ibId := range prep[idx].inboundIds {
  1161. ib, e := getIb(ibId)
  1162. if e != nil {
  1163. failed[idx] = true
  1164. reason[idx] = e.Error()
  1165. ok = false
  1166. break
  1167. }
  1168. if e := s.fillProtocolDefaults(&prep[idx].client, ib); e != nil {
  1169. failed[idx] = true
  1170. reason[idx] = e.Error()
  1171. ok = false
  1172. break
  1173. }
  1174. }
  1175. if !ok {
  1176. continue
  1177. }
  1178. for _, ibId := range prep[idx].inboundIds {
  1179. ib, _ := getIb(ibId)
  1180. if _, seen := byInbound[ibId]; !seen {
  1181. inboundOrder = append(inboundOrder, ibId)
  1182. }
  1183. byInbound[ibId] = append(byInbound[ibId], clientWithInboundFlow(prep[idx].client, ib))
  1184. idxByInbound[ibId] = append(idxByInbound[ibId], idx)
  1185. }
  1186. }
  1187. needRestart := false
  1188. for _, ibId := range inboundOrder {
  1189. payload, e := json.Marshal(map[string][]model.Client{"clients": byInbound[ibId]})
  1190. if e == nil {
  1191. var nr bool
  1192. nr, e = s.addInboundClient(inboundSvc, &model.Inbound{Id: ibId, Settings: string(payload)}, emailSubIDs)
  1193. if e == nil && nr {
  1194. needRestart = true
  1195. }
  1196. }
  1197. if e != nil {
  1198. for _, idx := range idxByInbound[ibId] {
  1199. failed[idx] = true
  1200. if reason[idx] == "" {
  1201. reason[idx] = e.Error()
  1202. }
  1203. }
  1204. }
  1205. }
  1206. for idx := range prep {
  1207. if failed[idx] {
  1208. skip(prep[idx].client.Email, reason[idx])
  1209. continue
  1210. }
  1211. if err := s.setClientLimitHwidByEmail(nil, prep[idx].client.Email, prep[idx].limitHwid); err != nil {
  1212. skip(prep[idx].client.Email, err.Error())
  1213. continue
  1214. }
  1215. result.Created++
  1216. }
  1217. return result, needRestart, nil
  1218. }
  1219. func (s *ClientService) DelDepleted(inboundSvc *InboundService) (int, bool, error) {
  1220. db := database.GetDB()
  1221. now := time.Now().UnixMilli()
  1222. depletedClause := "reset = 0 and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))"
  1223. var rows []xray.ClientTraffic
  1224. if err := db.Where(depletedClause, now).Find(&rows).Error; err != nil {
  1225. return 0, false, err
  1226. }
  1227. if len(rows) == 0 {
  1228. return 0, false, nil
  1229. }
  1230. seen := make(map[string]struct{}, len(rows))
  1231. emails := make([]string, 0, len(rows))
  1232. for _, r := range rows {
  1233. if r.Email == "" {
  1234. continue
  1235. }
  1236. if _, ok := seen[r.Email]; ok {
  1237. continue
  1238. }
  1239. seen[r.Email] = struct{}{}
  1240. emails = append(emails, r.Email)
  1241. }
  1242. if len(emails) == 0 {
  1243. return 0, false, nil
  1244. }
  1245. res, needRestart, err := s.BulkDelete(inboundSvc, emails, false)
  1246. if err != nil {
  1247. return res.Deleted, needRestart, err
  1248. }
  1249. return res.Deleted, needRestart, nil
  1250. }
  1251. type BulkSetEnableResult struct {
  1252. Changed int `json:"changed"`
  1253. Skipped []BulkSetEnableReport `json:"skipped,omitempty"`
  1254. }
  1255. type BulkSetEnableReport struct {
  1256. Email string `json:"email"`
  1257. Reason string `json:"reason"`
  1258. }
  1259. func (s *ClientService) BulkSetEnable(inboundSvc *InboundService, emails []string, enable bool) (BulkSetEnableResult, bool, error) {
  1260. result := BulkSetEnableResult{}
  1261. seen := map[string]struct{}{}
  1262. cleanEmails := make([]string, 0, len(emails))
  1263. for _, e := range emails {
  1264. e = strings.TrimSpace(e)
  1265. if e == "" {
  1266. continue
  1267. }
  1268. if _, ok := seen[e]; ok {
  1269. continue
  1270. }
  1271. seen[e] = struct{}{}
  1272. cleanEmails = append(cleanEmails, e)
  1273. }
  1274. if len(cleanEmails) == 0 {
  1275. return result, false, nil
  1276. }
  1277. db := database.GetDB()
  1278. var records []model.ClientRecord
  1279. for _, batch := range chunkStrings(cleanEmails, sqlInChunk) {
  1280. var rows []model.ClientRecord
  1281. if err := db.Where("email IN ?", batch).Find(&rows).Error; err != nil {
  1282. return result, false, err
  1283. }
  1284. records = append(records, rows...)
  1285. }
  1286. recordsByEmail := make(map[string]*model.ClientRecord, len(records))
  1287. for i := range records {
  1288. recordsByEmail[records[i].Email] = &records[i]
  1289. }
  1290. skippedReasons := map[string]string{}
  1291. for _, email := range cleanEmails {
  1292. if _, ok := recordsByEmail[email]; !ok {
  1293. skippedReasons[email] = "client not found"
  1294. }
  1295. }
  1296. clientIds := make([]int, 0, len(recordsByEmail))
  1297. recordIdToEmail := make(map[int]string, len(recordsByEmail))
  1298. for _, r := range recordsByEmail {
  1299. clientIds = append(clientIds, r.Id)
  1300. recordIdToEmail[r.Id] = r.Email
  1301. }
  1302. emailsByInbound := map[int][]string{}
  1303. if len(clientIds) > 0 {
  1304. var mappings []model.ClientInbound
  1305. for _, batch := range chunkInts(clientIds, sqlInChunk) {
  1306. var rows []model.ClientInbound
  1307. if err := db.Where("client_id IN ?", batch).Find(&rows).Error; err != nil {
  1308. return result, false, err
  1309. }
  1310. mappings = append(mappings, rows...)
  1311. }
  1312. for _, m := range mappings {
  1313. email, ok := recordIdToEmail[m.ClientId]
  1314. if !ok {
  1315. continue
  1316. }
  1317. emailsByInbound[m.InboundId] = append(emailsByInbound[m.InboundId], email)
  1318. }
  1319. }
  1320. needRestart := false
  1321. for inboundId, ibEmails := range emailsByInbound {
  1322. ibRes := s.bulkSetEnableInboundClients(inboundSvc, inboundId, ibEmails, enable)
  1323. if ibRes.needRestart {
  1324. needRestart = true
  1325. }
  1326. for email, reason := range ibRes.perEmailSkipped {
  1327. if _, already := skippedReasons[email]; !already {
  1328. skippedReasons[email] = reason
  1329. }
  1330. }
  1331. }
  1332. successEmails := make([]string, 0, len(recordsByEmail))
  1333. for email := range recordsByEmail {
  1334. if _, skipped := skippedReasons[email]; skipped {
  1335. continue
  1336. }
  1337. successEmails = append(successEmails, email)
  1338. }
  1339. if len(successEmails) > 0 {
  1340. now := time.Now().UnixMilli()
  1341. if err := runSerializedTx(func(tx *gorm.DB) error {
  1342. for _, batch := range chunkStrings(successEmails, sqlInChunk) {
  1343. if e := tx.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Update("enable", enable).Error; e != nil {
  1344. return e
  1345. }
  1346. if e := tx.Model(&model.ClientRecord{}).Where("email IN ?", batch).
  1347. Updates(map[string]any{"enable": enable, "updated_at": now}).Error; e != nil {
  1348. return e
  1349. }
  1350. }
  1351. return nil
  1352. }); err != nil {
  1353. return result, needRestart, err
  1354. }
  1355. }
  1356. result.Changed = len(successEmails)
  1357. for email, reason := range skippedReasons {
  1358. result.Skipped = append(result.Skipped, BulkSetEnableReport{Email: email, Reason: reason})
  1359. }
  1360. return result, needRestart, nil
  1361. }
  1362. type bulkSetEnableInboundResult struct {
  1363. perEmailSkipped map[string]string
  1364. needRestart bool
  1365. }
  1366. func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService, inboundId int, emails []string, enable bool) bulkSetEnableInboundResult {
  1367. res := bulkSetEnableInboundResult{perEmailSkipped: map[string]string{}}
  1368. defer lockInbound(inboundId).Unlock()
  1369. oldInbound, err := inboundSvc.GetInbound(inboundId)
  1370. if err != nil {
  1371. for _, e := range emails {
  1372. res.perEmailSkipped[e] = err.Error()
  1373. }
  1374. return res
  1375. }
  1376. var settings map[string]any
  1377. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  1378. for _, e := range emails {
  1379. res.perEmailSkipped[e] = err.Error()
  1380. }
  1381. return res
  1382. }
  1383. wanted := make(map[string]struct{}, len(emails))
  1384. for _, email := range emails {
  1385. wanted[email] = struct{}{}
  1386. }
  1387. cipher := ""
  1388. if oldInbound.Protocol == model.Shadowsocks {
  1389. cipher, _ = settings["method"].(string)
  1390. }
  1391. type changedClient struct {
  1392. email string
  1393. wasEnable bool
  1394. client model.Client
  1395. }
  1396. var changed []changedClient
  1397. found := map[string]bool{}
  1398. nowMs := time.Now().UnixMilli()
  1399. interfaceClients, _ := settings["clients"].([]any)
  1400. for i, c := range interfaceClients {
  1401. entry, ok := c.(map[string]any)
  1402. if !ok {
  1403. continue
  1404. }
  1405. email, _ := entry["email"].(string)
  1406. if _, want := wanted[email]; !want || email == "" {
  1407. continue
  1408. }
  1409. found[email] = true
  1410. prev, _ := entry["enable"].(bool)
  1411. if prev == enable {
  1412. continue
  1413. }
  1414. entry["enable"] = enable
  1415. entry["updated_at"] = nowMs
  1416. interfaceClients[i] = entry
  1417. // Build the pushed client from the inbound JSON (the per-inbound source of
  1418. // truth), so a remote UpdateUser carries every field and never zeroes
  1419. // subId/totalGB/expiry from drifting ClientRecord columns (#4628/#4792).
  1420. var parsed model.Client
  1421. if b, mErr := json.Marshal(entry); mErr == nil {
  1422. _ = json.Unmarshal(b, &parsed)
  1423. }
  1424. parsed.Email = email
  1425. parsed.Enable = enable
  1426. changed = append(changed, changedClient{email: email, wasEnable: prev, client: parsed})
  1427. }
  1428. for email := range wanted {
  1429. if !found[email] {
  1430. res.perEmailSkipped[email] = "Client Not Found In Inbound"
  1431. }
  1432. }
  1433. if len(changed) == 0 {
  1434. return res
  1435. }
  1436. settings["clients"] = interfaceClients
  1437. newSettings, err := json.MarshalIndent(settings, "", " ")
  1438. if err != nil {
  1439. for _, ch := range changed {
  1440. res.perEmailSkipped[ch.email] = err.Error()
  1441. }
  1442. return res
  1443. }
  1444. prevSettings := oldInbound.Settings
  1445. oldInbound.Settings = string(newSettings)
  1446. rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound)
  1447. if perr != nil {
  1448. for _, ch := range changed {
  1449. res.perEmailSkipped[ch.email] = perr.Error()
  1450. }
  1451. return res
  1452. }
  1453. if oldInbound.NodeID != nil && push && len(changed) > nodeBulkPushThreshold {
  1454. push = false
  1455. }
  1456. txErr := runSerializedTx(func(tx *gorm.DB) error {
  1457. if e := tx.Save(oldInbound).Error; e != nil {
  1458. return e
  1459. }
  1460. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  1461. if gcErr != nil {
  1462. return gcErr
  1463. }
  1464. if err := s.SyncInbound(tx, inboundId, finalClients); err != nil {
  1465. return err
  1466. }
  1467. if oldInbound.NodeID != nil {
  1468. return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID)
  1469. }
  1470. return nil
  1471. })
  1472. if txErr != nil {
  1473. for _, ch := range changed {
  1474. res.perEmailSkipped[ch.email] = txErr.Error()
  1475. }
  1476. return res
  1477. }
  1478. if oldInbound.NodeID == nil {
  1479. if !push {
  1480. res.needRestart = true
  1481. } else {
  1482. for _, ch := range changed {
  1483. if enable {
  1484. err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
  1485. "email": ch.client.Email,
  1486. "id": ch.client.ID,
  1487. "security": ch.client.Security,
  1488. "flow": ch.client.Flow,
  1489. "auth": ch.client.Auth,
  1490. "password": ch.client.Password,
  1491. "cipher": cipher,
  1492. })
  1493. if err1 != nil {
  1494. logger.Debug("Error in adding client on", rt.Name(), ":", err1)
  1495. res.needRestart = true
  1496. }
  1497. } else if ch.wasEnable {
  1498. err1 := rt.RemoveUser(context.Background(), oldInbound, ch.email)
  1499. if err1 != nil && !strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", ch.email)) {
  1500. logger.Debug("Error in removing client on", rt.Name(), ":", err1)
  1501. res.needRestart = true
  1502. }
  1503. }
  1504. }
  1505. }
  1506. } else if push {
  1507. pushFailed := false
  1508. for _, ch := range changed {
  1509. updated := ch.client
  1510. updated.UpdatedAt = nowMs
  1511. if err1 := rt.UpdateUser(context.Background(), oldInbound, ch.email, updated); err1 != nil {
  1512. logger.Warning("Error in updating client on", rt.Name(), ":", err1)
  1513. pushFailed = true
  1514. }
  1515. }
  1516. if !pushFailed {
  1517. advancePushedInbound(rt, prevSettings, oldInbound)
  1518. }
  1519. }
  1520. return res
  1521. }