1
0

client_bulk.go 47 KB

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