client_bulk.go 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673
  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 := max(rec.TotalGB+addBytes, 0)
  328. entry.applyTotal = true
  329. entry.newTotal = next
  330. }
  331. }
  332. if entry.applyExpiry || entry.applyTotal || adjustFlow {
  333. plan[email] = entry
  334. }
  335. }
  336. if len(plan) == 0 {
  337. for email, reason := range skippedReasons {
  338. result.Skipped = append(result.Skipped, BulkAdjustReport{Email: email, Reason: reason})
  339. }
  340. return result, false, nil
  341. }
  342. plannedIds := make([]int, 0, len(plan))
  343. recordIdToEmail := make(map[int]string, len(plan))
  344. for email, entry := range plan {
  345. plannedIds = append(plannedIds, entry.record.Id)
  346. recordIdToEmail[entry.record.Id] = email
  347. }
  348. var mappings []model.ClientInbound
  349. for _, batch := range chunkInts(plannedIds, sqlInChunk) {
  350. var rows []model.ClientInbound
  351. if err := db.Where("client_id IN ?", batch).Find(&rows).Error; err != nil {
  352. return result, false, err
  353. }
  354. mappings = append(mappings, rows...)
  355. }
  356. emailsByInbound := map[int][]string{}
  357. for _, m := range mappings {
  358. email, ok := recordIdToEmail[m.ClientId]
  359. if !ok {
  360. continue
  361. }
  362. emailsByInbound[m.InboundId] = append(emailsByInbound[m.InboundId], email)
  363. }
  364. needRestart := false
  365. flowHonored := map[string]bool{}
  366. flowIneligible := map[string]bool{}
  367. for inboundId, ibEmails := range emailsByInbound {
  368. ibRes := s.bulkAdjustInboundClients(inboundSvc, inboundId, ibEmails, plan, flow)
  369. if ibRes.needRestart {
  370. needRestart = true
  371. }
  372. for email := range ibRes.flowHonored {
  373. flowHonored[email] = true
  374. }
  375. for email := range ibRes.flowIneligible {
  376. flowIneligible[email] = true
  377. }
  378. for email, reason := range ibRes.perEmailSkipped {
  379. if _, already := skippedReasons[email]; !already {
  380. skippedReasons[email] = reason
  381. }
  382. }
  383. }
  384. now := time.Now().Unix() * 1000
  385. cond := depletedCond(db)
  386. candidateEmails := make([]string, 0, len(plan))
  387. for email, entry := range plan {
  388. if entry.applyExpiry || entry.applyTotal {
  389. candidateEmails = append(candidateEmails, email)
  390. }
  391. }
  392. wasDisabledDepleted := map[string]struct{}{}
  393. for _, batch := range chunkStrings(candidateEmails, sqlInChunk) {
  394. var rows []string
  395. if err := db.Model(xray.ClientTraffic{}).
  396. Where(cond+" AND enable = ? AND email IN ?", now, false, batch).
  397. Pluck("email", &rows).Error; err != nil {
  398. return result, needRestart, err
  399. }
  400. for _, e := range rows {
  401. wasDisabledDepleted[e] = struct{}{}
  402. }
  403. }
  404. adjusted := map[string]struct{}{}
  405. for email, entry := range plan {
  406. if _, skipped := skippedReasons[email]; skipped {
  407. continue
  408. }
  409. updates := map[string]any{}
  410. if entry.applyExpiry {
  411. updates["expiry_time"] = entry.newExpiry
  412. }
  413. if entry.applyTotal {
  414. updates["total"] = entry.newTotal
  415. }
  416. if len(updates) > 0 {
  417. if err := db.Model(xray.ClientTraffic{}).Where("email = ?", email).Updates(updates).Error; err != nil {
  418. if _, already := skippedReasons[email]; !already {
  419. skippedReasons[email] = err.Error()
  420. }
  421. continue
  422. }
  423. }
  424. // Counted when expiry/total changed, or a flow directive was honored
  425. // for this client (flow lives in the inbound JSON, not ClientTraffic).
  426. if len(updates) > 0 || flowHonored[email] {
  427. adjusted[email] = struct{}{}
  428. }
  429. }
  430. result.Adjusted = len(adjusted)
  431. for email, reason := range skippedReasons {
  432. result.Skipped = append(result.Skipped, BulkAdjustReport{Email: email, Reason: reason})
  433. }
  434. // Report a flow directive that no inbound could carry — only when it was not
  435. // honored anywhere and the client has no other (expiry/total) skip reason.
  436. // The expiry/total part, if any, has already been applied and counted above.
  437. for email := range flowIneligible {
  438. if flowHonored[email] {
  439. continue
  440. }
  441. if _, already := skippedReasons[email]; already {
  442. continue
  443. }
  444. result.Skipped = append(result.Skipped, BulkAdjustReport{Email: email, Reason: "flow not supported on inbound"})
  445. }
  446. if len(wasDisabledDepleted) > 0 {
  447. stillDepleted := map[string]struct{}{}
  448. wasList := make([]string, 0, len(wasDisabledDepleted))
  449. for e := range wasDisabledDepleted {
  450. wasList = append(wasList, e)
  451. }
  452. for _, batch := range chunkStrings(wasList, sqlInChunk) {
  453. var rows []string
  454. if err := db.Model(xray.ClientTraffic{}).
  455. Where(cond+" AND email IN ?", now, batch).
  456. Pluck("email", &rows).Error; err != nil {
  457. return result, needRestart, err
  458. }
  459. for _, e := range rows {
  460. stillDepleted[e] = struct{}{}
  461. }
  462. }
  463. reEnable := make([]string, 0, len(wasDisabledDepleted))
  464. for e := range wasDisabledDepleted {
  465. if _, still := stillDepleted[e]; !still {
  466. reEnable = append(reEnable, e)
  467. }
  468. }
  469. if len(reEnable) > 0 {
  470. _, nr, err := s.BulkSetEnable(inboundSvc, reEnable, true)
  471. if err != nil {
  472. return result, needRestart, err
  473. }
  474. if nr {
  475. needRestart = true
  476. }
  477. }
  478. }
  479. return result, needRestart, nil
  480. }
  481. type bulkInboundAdjustResult struct {
  482. perEmailSkipped map[string]string
  483. flowHonored map[string]bool
  484. // flowIneligible is tracked apart from perEmailSkipped: a flow directive
  485. // that an inbound cannot carry must not suppress the expiry/total write for
  486. // the same client (which would diverge the inbound JSON / ClientRecord from
  487. // ClientTraffic). It only feeds the final Skipped report.
  488. flowIneligible map[string]bool
  489. needRestart bool
  490. }
  491. // bulkAdjustInboundClients applies expiry/total deltas to multiple clients
  492. // inside a single inbound's settings JSON. The xray runtime is updated
  493. // only for remote-node inbounds; local nodes do not need a notification
  494. // because the AddUser payload does not include totalGB/expiryTime —
  495. // changing those fields is identity-preserving and the panel's traffic
  496. // enforcement loop picks up the new limits from ClientTraffic directly.
  497. func (s *ClientService) bulkAdjustInboundClients(
  498. inboundSvc *InboundService,
  499. inboundId int,
  500. emails []string,
  501. plan map[string]*bulkAdjustEntry,
  502. flow string,
  503. ) bulkInboundAdjustResult {
  504. res := bulkInboundAdjustResult{perEmailSkipped: map[string]string{}, flowHonored: map[string]bool{}, flowIneligible: map[string]bool{}}
  505. defer lockInbound(inboundId).Unlock()
  506. oldInbound, err := inboundSvc.GetInbound(inboundId)
  507. if err != nil {
  508. logger.Error("Load Old Data Error")
  509. for _, e := range emails {
  510. res.perEmailSkipped[e] = err.Error()
  511. }
  512. return res
  513. }
  514. var settings map[string]any
  515. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  516. for _, e := range emails {
  517. res.perEmailSkipped[e] = err.Error()
  518. }
  519. return res
  520. }
  521. // Match by email — the client's stable identity (see Delete). Credentials
  522. // can drift from the inbound JSON, so they are never used for matching.
  523. wantedEmails := make(map[string]struct{}, len(emails))
  524. for _, email := range emails {
  525. if plan[email] == nil {
  526. res.perEmailSkipped[email] = "client not found"
  527. continue
  528. }
  529. wantedEmails[email] = struct{}{}
  530. }
  531. // Flow eligibility is a property of the inbound (protocol + transport), so
  532. // resolve it once. Clearing flow is always allowed; setting a vision flow
  533. // is only honored on an inbound that can carry it.
  534. flowEligible := flow == bulkFlowClear ||
  535. inboundCanEnableTlsFlow(string(oldInbound.Protocol), oldInbound.StreamSettings, oldInbound.Settings)
  536. interfaceClients, _ := settings["clients"].([]any)
  537. foundEmails := map[string]bool{}
  538. flowChanged := false
  539. nowMs := time.Now().Unix() * 1000
  540. for i, client := range interfaceClients {
  541. c, ok := client.(map[string]any)
  542. if !ok {
  543. continue
  544. }
  545. targetEmail, _ := c["email"].(string)
  546. if _, want := wantedEmails[targetEmail]; !want || targetEmail == "" {
  547. continue
  548. }
  549. entry := plan[targetEmail]
  550. if entry.applyExpiry {
  551. c["expiryTime"] = entry.newExpiry
  552. }
  553. if entry.applyTotal {
  554. c["totalGB"] = entry.newTotal
  555. }
  556. if flow != "" {
  557. if flowEligible {
  558. want := ""
  559. if flow != bulkFlowClear {
  560. want = flow
  561. }
  562. if cur, _ := c["flow"].(string); cur != want {
  563. c["flow"] = want
  564. flowChanged = true
  565. }
  566. res.flowHonored[targetEmail] = true
  567. } else {
  568. // Record separately so this never suppresses the expiry/total
  569. // write for the same client (see flowIneligible doc).
  570. res.flowIneligible[targetEmail] = true
  571. }
  572. }
  573. c["updated_at"] = nowMs
  574. interfaceClients[i] = c
  575. foundEmails[targetEmail] = true
  576. }
  577. for email := range wantedEmails {
  578. if !foundEmails[email] {
  579. res.perEmailSkipped[email] = "Client Not Found In Inbound"
  580. }
  581. }
  582. if len(foundEmails) == 0 {
  583. return res
  584. }
  585. settings["clients"] = interfaceClients
  586. newSettings, err := json.MarshalIndent(settings, "", " ")
  587. if err != nil {
  588. for email := range foundEmails {
  589. res.perEmailSkipped[email] = err.Error()
  590. }
  591. return res
  592. }
  593. prevSettings := oldInbound.Settings
  594. oldInbound.Settings = string(newSettings)
  595. // A flow change rewrites the user's xray config, which the lightweight
  596. // UpdateUser push below does not carry. Local nodes reload via restart;
  597. // remote nodes get a full reconcile (MarkNodeDirty) instead of a per-user push.
  598. if flowChanged && oldInbound.NodeID == nil {
  599. res.needRestart = true
  600. }
  601. if oldInbound.NodeID != nil {
  602. rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound)
  603. if perr != nil {
  604. for email := range foundEmails {
  605. res.perEmailSkipped[email] = perr.Error()
  606. delete(foundEmails, email)
  607. }
  608. } else {
  609. if flowChanged {
  610. push = false
  611. }
  612. // Large batches collapse into one reconcile push rather than M updates.
  613. if push && len(foundEmails) > nodeBulkPushThreshold {
  614. push = false
  615. }
  616. if push {
  617. pushFailed := false
  618. for email := range foundEmails {
  619. entry := plan[email]
  620. updated := *entry.record.ToClient()
  621. if entry.applyExpiry {
  622. updated.ExpiryTime = entry.newExpiry
  623. }
  624. if entry.applyTotal {
  625. updated.TotalGB = entry.newTotal
  626. }
  627. updated.UpdatedAt = nowMs
  628. if err1 := rt.UpdateUser(context.Background(), oldInbound, email, updated); err1 != nil {
  629. logger.Warning("Error in updating client on", rt.Name(), ":", err1)
  630. pushFailed = true
  631. }
  632. }
  633. if !pushFailed {
  634. advancePushedInbound(rt, prevSettings, oldInbound)
  635. }
  636. }
  637. }
  638. }
  639. // Serialize against the traffic poll to avoid the cross-transaction
  640. // lock-order deadlock on inbounds/client_records (runSerializedTx).
  641. txErr := runSerializedTx(func(tx *gorm.DB) error {
  642. if err := tx.Save(oldInbound).Error; err != nil {
  643. return err
  644. }
  645. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  646. if gcErr != nil {
  647. return gcErr
  648. }
  649. if err := s.SyncInbound(tx, inboundId, finalClients); err != nil {
  650. return err
  651. }
  652. if oldInbound.NodeID != nil {
  653. return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID)
  654. }
  655. return nil
  656. })
  657. if txErr != nil {
  658. for email := range foundEmails {
  659. if _, skip := res.perEmailSkipped[email]; !skip {
  660. res.perEmailSkipped[email] = txErr.Error()
  661. }
  662. }
  663. }
  664. return res
  665. }
  666. // BulkDeleteResult mirrors BulkAdjustResult: total deleted plus per-email
  667. // skip reasons when an email could not be processed.
  668. type BulkDeleteResult struct {
  669. Deleted int `json:"deleted"`
  670. Skipped []BulkDeleteReport `json:"skipped,omitempty"`
  671. }
  672. type BulkDeleteReport struct {
  673. Email string `json:"email"`
  674. Reason string `json:"reason"`
  675. }
  676. // BulkDelete removes every client in the list in one optimized pass.
  677. // Instead of running the full single-delete pipeline N times (which would
  678. // re-read, re-parse, and re-write each inbound's settings JSON for every
  679. // email), it groups emails by inbound and performs a single
  680. // read-modify-write per inbound. Per-row DB cleanups are also batched with
  681. // IN-clause queries at the end. Errors on a particular email are recorded
  682. // in the Skipped list and processing continues for the rest.
  683. func (s *ClientService) BulkDelete(inboundSvc *InboundService, emails []string, keepTraffic bool) (BulkDeleteResult, bool, error) {
  684. result := BulkDeleteResult{}
  685. seen := map[string]struct{}{}
  686. cleanEmails := make([]string, 0, len(emails))
  687. for _, e := range emails {
  688. e = strings.TrimSpace(e)
  689. if e == "" {
  690. continue
  691. }
  692. if _, ok := seen[e]; ok {
  693. continue
  694. }
  695. seen[e] = struct{}{}
  696. cleanEmails = append(cleanEmails, e)
  697. }
  698. if len(cleanEmails) == 0 {
  699. return result, false, nil
  700. }
  701. db := database.GetDB()
  702. var records []model.ClientRecord
  703. for _, batch := range chunkStrings(cleanEmails, sqlInChunk) {
  704. var rows []model.ClientRecord
  705. if err := db.Where("email IN ?", batch).Find(&rows).Error; err != nil {
  706. return result, false, err
  707. }
  708. records = append(records, rows...)
  709. }
  710. recordsByEmail := make(map[string]*model.ClientRecord, len(records))
  711. tombstoneEmails := make([]string, 0, len(records))
  712. for i := range records {
  713. recordsByEmail[records[i].Email] = &records[i]
  714. tombstoneEmails = append(tombstoneEmails, records[i].Email)
  715. }
  716. tombstoneClientEmails(tombstoneEmails)
  717. skippedReasons := map[string]string{}
  718. for _, email := range cleanEmails {
  719. if _, ok := recordsByEmail[email]; !ok {
  720. skippedReasons[email] = "client not found"
  721. }
  722. }
  723. clientIds := make([]int, 0, len(recordsByEmail))
  724. recordIdToEmail := make(map[int]string, len(recordsByEmail))
  725. for _, r := range recordsByEmail {
  726. clientIds = append(clientIds, r.Id)
  727. recordIdToEmail[r.Id] = r.Email
  728. }
  729. emailsByInbound := map[int][]string{}
  730. if len(clientIds) > 0 {
  731. var mappings []model.ClientInbound
  732. for _, batch := range chunkInts(clientIds, sqlInChunk) {
  733. var rows []model.ClientInbound
  734. if err := db.Where("client_id IN ?", batch).Find(&rows).Error; err != nil {
  735. return result, false, err
  736. }
  737. mappings = append(mappings, rows...)
  738. }
  739. for _, m := range mappings {
  740. email, ok := recordIdToEmail[m.ClientId]
  741. if !ok {
  742. continue
  743. }
  744. emailsByInbound[m.InboundId] = append(emailsByInbound[m.InboundId], email)
  745. }
  746. }
  747. needRestart := false
  748. for inboundId, ibEmails := range emailsByInbound {
  749. ibResult := s.bulkDelInboundClients(inboundSvc, inboundId, ibEmails, recordsByEmail, false)
  750. if ibResult.needRestart {
  751. needRestart = true
  752. }
  753. for email, reason := range ibResult.perEmailSkipped {
  754. if _, already := skippedReasons[email]; !already {
  755. skippedReasons[email] = reason
  756. }
  757. }
  758. }
  759. successEmails := make([]string, 0, len(recordsByEmail))
  760. successIds := make([]int, 0, len(recordsByEmail))
  761. for email, rec := range recordsByEmail {
  762. if _, skipped := skippedReasons[email]; skipped {
  763. continue
  764. }
  765. successEmails = append(successEmails, email)
  766. successIds = append(successIds, rec.Id)
  767. }
  768. if len(successIds) > 0 {
  769. // Serialize the row cleanup against the traffic poll to avoid the
  770. // cross-transaction lock-order deadlock on client_traffics/inbounds.
  771. if err := runSerializedTx(func(tx *gorm.DB) error {
  772. if e := adjustGroupBaselinesForRemovedTraffic(tx, successEmails); e != nil {
  773. return e
  774. }
  775. for _, batch := range chunkInts(successIds, sqlInChunk) {
  776. if e := tx.Where("client_id IN ?", batch).Delete(&model.ClientInbound{}).Error; e != nil {
  777. return e
  778. }
  779. }
  780. if !keepTraffic && len(successEmails) > 0 {
  781. for _, batch := range chunkStrings(successEmails, sqlInChunk) {
  782. if e := tx.Where("email IN ?", batch).Delete(&xray.ClientTraffic{}).Error; e != nil {
  783. return e
  784. }
  785. if e := tx.Where("client_email IN ?", batch).Delete(&model.InboundClientIps{}).Error; e != nil {
  786. return e
  787. }
  788. }
  789. }
  790. for _, batch := range chunkInts(successIds, sqlInChunk) {
  791. if e := tx.Where("id IN ?", batch).Delete(&model.ClientRecord{}).Error; e != nil {
  792. return e
  793. }
  794. }
  795. return nil
  796. }); err != nil {
  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. prevSettings := oldInbound.Settings
  889. oldInbound.Settings = string(newSettings)
  890. foundList := make([]string, 0, len(foundEmails))
  891. for email := range foundEmails {
  892. foundList = append(foundList, email)
  893. }
  894. notDepletedByEmail := map[string]bool{}
  895. if len(foundList) > 0 {
  896. type trafficRow struct {
  897. Email string
  898. Enable bool
  899. }
  900. for _, batch := range chunkStrings(foundList, sqlInChunk) {
  901. var rows []trafficRow
  902. if err := db.Model(xray.ClientTraffic{}).
  903. Where("email IN ?", batch).
  904. Select("email, enable").
  905. Scan(&rows).Error; err == nil {
  906. for _, r := range rows {
  907. notDepletedByEmail[r.Email] = r.Enable
  908. }
  909. }
  910. }
  911. }
  912. var sharedSet map[string]bool
  913. if !keepTraffic {
  914. var sharedErr error
  915. sharedSet, sharedErr = inboundSvc.emailsUsedByOtherInbounds(foundList, inboundId)
  916. if sharedErr != nil {
  917. for email := range foundEmails {
  918. res.perEmailSkipped[email] = sharedErr.Error()
  919. delete(foundEmails, email)
  920. }
  921. return res
  922. }
  923. }
  924. if !keepTraffic {
  925. purge := make([]string, 0, len(foundEmails))
  926. for email := range foundEmails {
  927. if !sharedSet[strings.ToLower(strings.TrimSpace(email))] {
  928. purge = append(purge, email)
  929. }
  930. }
  931. if len(purge) > 0 {
  932. // Serialize the IP/stat purge against the traffic poll to avoid the
  933. // cross-transaction lock-order deadlock on client_traffics.
  934. if delErr := runSerializedTx(func(tx *gorm.DB) error {
  935. if e := inboundSvc.delClientIPsByEmails(tx, purge); e != nil {
  936. logger.Error("Error in delete client IPs")
  937. return e
  938. }
  939. if e := inboundSvc.delClientStatsByEmails(tx, purge); e != nil {
  940. logger.Error("Delete stats Data Error")
  941. return e
  942. }
  943. return nil
  944. }); delErr != nil {
  945. for _, email := range purge {
  946. res.perEmailSkipped[email] = delErr.Error()
  947. delete(foundEmails, email)
  948. }
  949. }
  950. }
  951. }
  952. if oldInbound.NodeID == nil {
  953. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  954. if rterr != nil {
  955. res.needRestart = true
  956. } else {
  957. for email := range foundEmails {
  958. if !enableByEmail[email] || !notDepletedByEmail[email] {
  959. continue
  960. }
  961. err1 := rt.RemoveUser(context.Background(), oldInbound, email)
  962. if err1 == nil {
  963. logger.Debug("Client deleted on", rt.Name(), ":", email)
  964. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  965. logger.Debug("User is already deleted. Nothing to do more...")
  966. } else {
  967. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  968. res.needRestart = true
  969. }
  970. }
  971. }
  972. } else {
  973. rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound)
  974. if perr != nil {
  975. for email := range foundEmails {
  976. res.perEmailSkipped[email] = perr.Error()
  977. delete(foundEmails, email)
  978. }
  979. } else {
  980. // Large batches collapse into one reconcile push rather than M deletes.
  981. if push && len(foundEmails) > nodeBulkPushThreshold {
  982. push = false
  983. }
  984. if push {
  985. // bulkDelInboundClients only runs for full client deletion
  986. // (BulkDelete), so the node must drop its client record too,
  987. // not just detach from this inbound (#5797).
  988. pushFailed := false
  989. for email := range foundEmails {
  990. if err1 := rt.DeleteClient(context.Background(), email); err1 != nil {
  991. logger.Warning("Error in deleting client on", rt.Name(), ":", err1)
  992. pushFailed = true
  993. }
  994. }
  995. if !pushFailed {
  996. advancePushedInbound(rt, prevSettings, oldInbound)
  997. }
  998. }
  999. }
  1000. }
  1001. // Serialize against the traffic poll to avoid the cross-transaction
  1002. // lock-order deadlock on inbounds/client_records (runSerializedTx).
  1003. txErr := runSerializedTx(func(tx *gorm.DB) error {
  1004. if err := tx.Save(oldInbound).Error; err != nil {
  1005. return err
  1006. }
  1007. finalClients, err := inboundSvc.GetClients(oldInbound)
  1008. if err != nil {
  1009. return err
  1010. }
  1011. if err := s.SyncInbound(tx, inboundId, finalClients); err != nil {
  1012. return err
  1013. }
  1014. if oldInbound.NodeID != nil {
  1015. return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID)
  1016. }
  1017. return nil
  1018. })
  1019. if txErr != nil {
  1020. for email := range foundEmails {
  1021. if _, skip := res.perEmailSkipped[email]; !skip {
  1022. res.perEmailSkipped[email] = txErr.Error()
  1023. }
  1024. }
  1025. }
  1026. return res
  1027. }
  1028. // BulkCreateResult mirrors BulkAdjustResult for the create flow.
  1029. type BulkCreateResult struct {
  1030. Created int `json:"created"`
  1031. Skipped []BulkCreateReport `json:"skipped,omitempty"`
  1032. }
  1033. type BulkCreateReport struct {
  1034. Email string `json:"email"`
  1035. Reason string `json:"reason"`
  1036. }
  1037. func (s *ClientService) BulkCreate(inboundSvc *InboundService, payloads []ClientCreatePayload) (BulkCreateResult, bool, error) {
  1038. result := BulkCreateResult{}
  1039. if len(payloads) == 0 {
  1040. return result, false, nil
  1041. }
  1042. skip := func(email, reason string) {
  1043. if strings.TrimSpace(email) == "" {
  1044. email = "(missing email)"
  1045. }
  1046. result.Skipped = append(result.Skipped, BulkCreateReport{Email: email, Reason: reason})
  1047. }
  1048. emailSubIDs, err := inboundSvc.getAllEmailSubIDs()
  1049. if err != nil {
  1050. emailSubIDs = nil
  1051. }
  1052. type prepared struct {
  1053. client model.Client
  1054. inboundIds []int
  1055. }
  1056. prep := make([]prepared, 0, len(payloads))
  1057. emails := make([]string, 0, len(payloads))
  1058. subIDs := make([]string, 0, len(payloads))
  1059. seenEmail := make(map[string]struct{}, len(payloads))
  1060. seenSubID := make(map[string]string, len(payloads))
  1061. for i := range payloads {
  1062. client := payloads[i].Client
  1063. email := strings.TrimSpace(client.Email)
  1064. if email == "" {
  1065. skip("", "client email is required")
  1066. continue
  1067. }
  1068. if verr := validateClientEmail(email); verr != nil {
  1069. skip(email, verr.Error())
  1070. continue
  1071. }
  1072. if verr := validateClientSubID(client.SubID); verr != nil {
  1073. skip(email, verr.Error())
  1074. continue
  1075. }
  1076. if len(payloads[i].InboundIds) == 0 {
  1077. skip(email, "at least one inbound is required")
  1078. continue
  1079. }
  1080. client.Email = email
  1081. if client.SubID == "" {
  1082. client.SubID = uuid.NewString()
  1083. }
  1084. if !client.Enable {
  1085. client.Enable = true
  1086. }
  1087. now := time.Now().UnixMilli()
  1088. if client.CreatedAt == 0 {
  1089. client.CreatedAt = now
  1090. }
  1091. client.UpdatedAt = now
  1092. le := strings.ToLower(email)
  1093. if _, dup := seenEmail[le]; dup {
  1094. skip(email, "email already in use: "+email)
  1095. continue
  1096. }
  1097. if owner, ok := seenSubID[client.SubID]; ok && owner != le {
  1098. skip(email, "subId already in use: "+client.SubID)
  1099. continue
  1100. }
  1101. seenEmail[le] = struct{}{}
  1102. seenSubID[client.SubID] = le
  1103. prep = append(prep, prepared{client: client, inboundIds: payloads[i].InboundIds})
  1104. emails = append(emails, email)
  1105. subIDs = append(subIDs, client.SubID)
  1106. }
  1107. if len(prep) == 0 {
  1108. return result, false, nil
  1109. }
  1110. db := database.GetDB()
  1111. const lookupChunk = 400
  1112. existingByEmail := make(map[string]model.ClientRecord, len(emails))
  1113. for start := 0; start < len(emails); start += lookupChunk {
  1114. end := min(start+lookupChunk, len(emails))
  1115. var rows []model.ClientRecord
  1116. if e := db.Where("email IN ?", emails[start:end]).Find(&rows).Error; e != nil {
  1117. return result, false, e
  1118. }
  1119. for i := range rows {
  1120. existingByEmail[strings.ToLower(rows[i].Email)] = rows[i]
  1121. }
  1122. }
  1123. existingSubOwner := make(map[string]string, len(subIDs))
  1124. for start := 0; start < len(subIDs); start += lookupChunk {
  1125. end := min(start+lookupChunk, len(subIDs))
  1126. var rows []model.ClientRecord
  1127. if e := db.Where("sub_id IN ?", subIDs[start:end]).Find(&rows).Error; e != nil {
  1128. return result, false, e
  1129. }
  1130. for i := range rows {
  1131. existingSubOwner[rows[i].SubID] = strings.ToLower(rows[i].Email)
  1132. }
  1133. }
  1134. inboundCache := make(map[int]*model.Inbound)
  1135. getIb := func(id int) (*model.Inbound, error) {
  1136. if ib, ok := inboundCache[id]; ok {
  1137. return ib, nil
  1138. }
  1139. ib, e := inboundSvc.GetInbound(id)
  1140. if e != nil {
  1141. return nil, e
  1142. }
  1143. inboundCache[id] = ib
  1144. return ib, nil
  1145. }
  1146. byInbound := make(map[int][]model.Client)
  1147. idxByInbound := make(map[int][]int)
  1148. inboundOrder := make([]int, 0)
  1149. failed := make([]bool, len(prep))
  1150. reason := make([]string, len(prep))
  1151. for idx := range prep {
  1152. le := strings.ToLower(prep[idx].client.Email)
  1153. if rec, ok := existingByEmail[le]; ok {
  1154. if rec.SubID != prep[idx].client.SubID {
  1155. failed[idx] = true
  1156. reason[idx] = "email already in use: " + prep[idx].client.Email
  1157. continue
  1158. }
  1159. if prep[idx].client.ID == "" {
  1160. prep[idx].client.ID = rec.UUID
  1161. }
  1162. if prep[idx].client.Password == "" {
  1163. prep[idx].client.Password = rec.Password
  1164. }
  1165. if prep[idx].client.Auth == "" {
  1166. prep[idx].client.Auth = rec.Auth
  1167. }
  1168. if prep[idx].client.Secret == "" {
  1169. prep[idx].client.Secret = rec.Secret
  1170. }
  1171. }
  1172. if owner, ok := existingSubOwner[prep[idx].client.SubID]; ok && owner != le {
  1173. failed[idx] = true
  1174. reason[idx] = "subId already in use: " + prep[idx].client.SubID
  1175. continue
  1176. }
  1177. ok := true
  1178. for _, ibId := range prep[idx].inboundIds {
  1179. ib, e := getIb(ibId)
  1180. if e != nil {
  1181. failed[idx] = true
  1182. reason[idx] = e.Error()
  1183. ok = false
  1184. break
  1185. }
  1186. if e := s.fillProtocolDefaults(&prep[idx].client, ib); e != nil {
  1187. failed[idx] = true
  1188. reason[idx] = e.Error()
  1189. ok = false
  1190. break
  1191. }
  1192. }
  1193. if !ok {
  1194. continue
  1195. }
  1196. for _, ibId := range prep[idx].inboundIds {
  1197. ib, _ := getIb(ibId)
  1198. if _, seen := byInbound[ibId]; !seen {
  1199. inboundOrder = append(inboundOrder, ibId)
  1200. }
  1201. byInbound[ibId] = append(byInbound[ibId], clientWithInboundFlow(prep[idx].client, ib))
  1202. idxByInbound[ibId] = append(idxByInbound[ibId], idx)
  1203. }
  1204. }
  1205. needRestart := false
  1206. for _, ibId := range inboundOrder {
  1207. payload, e := json.Marshal(map[string][]model.Client{"clients": byInbound[ibId]})
  1208. if e == nil {
  1209. var nr bool
  1210. nr, e = s.addInboundClient(inboundSvc, &model.Inbound{Id: ibId, Settings: string(payload)}, emailSubIDs)
  1211. if e == nil && nr {
  1212. needRestart = true
  1213. }
  1214. }
  1215. if e != nil {
  1216. for _, idx := range idxByInbound[ibId] {
  1217. failed[idx] = true
  1218. if reason[idx] == "" {
  1219. reason[idx] = e.Error()
  1220. }
  1221. }
  1222. }
  1223. }
  1224. for idx := range prep {
  1225. if failed[idx] {
  1226. skip(prep[idx].client.Email, reason[idx])
  1227. } else {
  1228. result.Created++
  1229. }
  1230. }
  1231. return result, needRestart, nil
  1232. }
  1233. func (s *ClientService) DelDepleted(inboundSvc *InboundService) (int, bool, error) {
  1234. db := database.GetDB()
  1235. now := time.Now().UnixMilli()
  1236. depletedClause := "reset = 0 and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))"
  1237. var rows []xray.ClientTraffic
  1238. if err := db.Where(depletedClause, now).Find(&rows).Error; err != nil {
  1239. return 0, false, err
  1240. }
  1241. if len(rows) == 0 {
  1242. return 0, false, nil
  1243. }
  1244. seen := make(map[string]struct{}, len(rows))
  1245. emails := make([]string, 0, len(rows))
  1246. for _, r := range rows {
  1247. if r.Email == "" {
  1248. continue
  1249. }
  1250. if _, ok := seen[r.Email]; ok {
  1251. continue
  1252. }
  1253. seen[r.Email] = struct{}{}
  1254. emails = append(emails, r.Email)
  1255. }
  1256. if len(emails) == 0 {
  1257. return 0, false, nil
  1258. }
  1259. res, needRestart, err := s.BulkDelete(inboundSvc, emails, false)
  1260. if err != nil {
  1261. return res.Deleted, needRestart, err
  1262. }
  1263. return res.Deleted, needRestart, nil
  1264. }
  1265. type BulkSetEnableResult struct {
  1266. Changed int `json:"changed"`
  1267. Skipped []BulkSetEnableReport `json:"skipped,omitempty"`
  1268. }
  1269. type BulkSetEnableReport struct {
  1270. Email string `json:"email"`
  1271. Reason string `json:"reason"`
  1272. }
  1273. func (s *ClientService) BulkSetEnable(inboundSvc *InboundService, emails []string, enable bool) (BulkSetEnableResult, bool, error) {
  1274. result := BulkSetEnableResult{}
  1275. seen := map[string]struct{}{}
  1276. cleanEmails := make([]string, 0, len(emails))
  1277. for _, e := range emails {
  1278. e = strings.TrimSpace(e)
  1279. if e == "" {
  1280. continue
  1281. }
  1282. if _, ok := seen[e]; ok {
  1283. continue
  1284. }
  1285. seen[e] = struct{}{}
  1286. cleanEmails = append(cleanEmails, e)
  1287. }
  1288. if len(cleanEmails) == 0 {
  1289. return result, false, nil
  1290. }
  1291. db := database.GetDB()
  1292. var records []model.ClientRecord
  1293. for _, batch := range chunkStrings(cleanEmails, sqlInChunk) {
  1294. var rows []model.ClientRecord
  1295. if err := db.Where("email IN ?", batch).Find(&rows).Error; err != nil {
  1296. return result, false, err
  1297. }
  1298. records = append(records, rows...)
  1299. }
  1300. recordsByEmail := make(map[string]*model.ClientRecord, len(records))
  1301. for i := range records {
  1302. recordsByEmail[records[i].Email] = &records[i]
  1303. }
  1304. skippedReasons := map[string]string{}
  1305. for _, email := range cleanEmails {
  1306. if _, ok := recordsByEmail[email]; !ok {
  1307. skippedReasons[email] = "client not found"
  1308. }
  1309. }
  1310. clientIds := make([]int, 0, len(recordsByEmail))
  1311. recordIdToEmail := make(map[int]string, len(recordsByEmail))
  1312. for _, r := range recordsByEmail {
  1313. clientIds = append(clientIds, r.Id)
  1314. recordIdToEmail[r.Id] = r.Email
  1315. }
  1316. emailsByInbound := map[int][]string{}
  1317. if len(clientIds) > 0 {
  1318. var mappings []model.ClientInbound
  1319. for _, batch := range chunkInts(clientIds, sqlInChunk) {
  1320. var rows []model.ClientInbound
  1321. if err := db.Where("client_id IN ?", batch).Find(&rows).Error; err != nil {
  1322. return result, false, err
  1323. }
  1324. mappings = append(mappings, rows...)
  1325. }
  1326. for _, m := range mappings {
  1327. email, ok := recordIdToEmail[m.ClientId]
  1328. if !ok {
  1329. continue
  1330. }
  1331. emailsByInbound[m.InboundId] = append(emailsByInbound[m.InboundId], email)
  1332. }
  1333. }
  1334. needRestart := false
  1335. for inboundId, ibEmails := range emailsByInbound {
  1336. ibRes := s.bulkSetEnableInboundClients(inboundSvc, inboundId, ibEmails, enable)
  1337. if ibRes.needRestart {
  1338. needRestart = true
  1339. }
  1340. for email, reason := range ibRes.perEmailSkipped {
  1341. if _, already := skippedReasons[email]; !already {
  1342. skippedReasons[email] = reason
  1343. }
  1344. }
  1345. }
  1346. successEmails := make([]string, 0, len(recordsByEmail))
  1347. for email := range recordsByEmail {
  1348. if _, skipped := skippedReasons[email]; skipped {
  1349. continue
  1350. }
  1351. successEmails = append(successEmails, email)
  1352. }
  1353. if len(successEmails) > 0 {
  1354. now := time.Now().UnixMilli()
  1355. if err := runSerializedTx(func(tx *gorm.DB) error {
  1356. for _, batch := range chunkStrings(successEmails, sqlInChunk) {
  1357. if e := tx.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Update("enable", enable).Error; e != nil {
  1358. return e
  1359. }
  1360. if e := tx.Model(&model.ClientRecord{}).Where("email IN ?", batch).
  1361. Updates(map[string]any{"enable": enable, "updated_at": now}).Error; e != nil {
  1362. return e
  1363. }
  1364. }
  1365. return nil
  1366. }); err != nil {
  1367. return result, needRestart, err
  1368. }
  1369. }
  1370. result.Changed = len(successEmails)
  1371. for email, reason := range skippedReasons {
  1372. result.Skipped = append(result.Skipped, BulkSetEnableReport{Email: email, Reason: reason})
  1373. }
  1374. return result, needRestart, nil
  1375. }
  1376. type bulkSetEnableInboundResult struct {
  1377. perEmailSkipped map[string]string
  1378. needRestart bool
  1379. }
  1380. func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService, inboundId int, emails []string, enable bool) bulkSetEnableInboundResult {
  1381. res := bulkSetEnableInboundResult{perEmailSkipped: map[string]string{}}
  1382. defer lockInbound(inboundId).Unlock()
  1383. oldInbound, err := inboundSvc.GetInbound(inboundId)
  1384. if err != nil {
  1385. for _, e := range emails {
  1386. res.perEmailSkipped[e] = err.Error()
  1387. }
  1388. return res
  1389. }
  1390. var settings map[string]any
  1391. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  1392. for _, e := range emails {
  1393. res.perEmailSkipped[e] = err.Error()
  1394. }
  1395. return res
  1396. }
  1397. wanted := make(map[string]struct{}, len(emails))
  1398. for _, email := range emails {
  1399. wanted[email] = struct{}{}
  1400. }
  1401. cipher := ""
  1402. if oldInbound.Protocol == model.Shadowsocks {
  1403. cipher, _ = settings["method"].(string)
  1404. }
  1405. type changedClient struct {
  1406. email string
  1407. wasEnable bool
  1408. client model.Client
  1409. }
  1410. var changed []changedClient
  1411. found := map[string]bool{}
  1412. nowMs := time.Now().UnixMilli()
  1413. interfaceClients, _ := settings["clients"].([]any)
  1414. for i, c := range interfaceClients {
  1415. entry, ok := c.(map[string]any)
  1416. if !ok {
  1417. continue
  1418. }
  1419. email, _ := entry["email"].(string)
  1420. if _, want := wanted[email]; !want || email == "" {
  1421. continue
  1422. }
  1423. found[email] = true
  1424. prev, _ := entry["enable"].(bool)
  1425. if prev == enable {
  1426. continue
  1427. }
  1428. entry["enable"] = enable
  1429. entry["updated_at"] = nowMs
  1430. interfaceClients[i] = entry
  1431. // Build the pushed client from the inbound JSON (the per-inbound source of
  1432. // truth), so a remote UpdateUser carries every field and never zeroes
  1433. // subId/totalGB/expiry from drifting ClientRecord columns (#4628/#4792).
  1434. var parsed model.Client
  1435. if b, mErr := json.Marshal(entry); mErr == nil {
  1436. _ = json.Unmarshal(b, &parsed)
  1437. }
  1438. parsed.Email = email
  1439. parsed.Enable = enable
  1440. changed = append(changed, changedClient{email: email, wasEnable: prev, client: parsed})
  1441. }
  1442. for email := range wanted {
  1443. if !found[email] {
  1444. res.perEmailSkipped[email] = "Client Not Found In Inbound"
  1445. }
  1446. }
  1447. if len(changed) == 0 {
  1448. return res
  1449. }
  1450. settings["clients"] = interfaceClients
  1451. newSettings, err := json.MarshalIndent(settings, "", " ")
  1452. if err != nil {
  1453. for _, ch := range changed {
  1454. res.perEmailSkipped[ch.email] = err.Error()
  1455. }
  1456. return res
  1457. }
  1458. prevSettings := oldInbound.Settings
  1459. oldInbound.Settings = string(newSettings)
  1460. rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound)
  1461. if perr != nil {
  1462. for _, ch := range changed {
  1463. res.perEmailSkipped[ch.email] = perr.Error()
  1464. }
  1465. return res
  1466. }
  1467. if oldInbound.NodeID != nil && push && len(changed) > nodeBulkPushThreshold {
  1468. push = false
  1469. }
  1470. txErr := runSerializedTx(func(tx *gorm.DB) error {
  1471. if e := tx.Save(oldInbound).Error; e != nil {
  1472. return e
  1473. }
  1474. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  1475. if gcErr != nil {
  1476. return gcErr
  1477. }
  1478. if err := s.SyncInbound(tx, inboundId, finalClients); err != nil {
  1479. return err
  1480. }
  1481. if oldInbound.NodeID != nil {
  1482. return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID)
  1483. }
  1484. return nil
  1485. })
  1486. if txErr != nil {
  1487. for _, ch := range changed {
  1488. res.perEmailSkipped[ch.email] = txErr.Error()
  1489. }
  1490. return res
  1491. }
  1492. if oldInbound.NodeID == nil {
  1493. if !push {
  1494. res.needRestart = true
  1495. } else {
  1496. for _, ch := range changed {
  1497. if enable {
  1498. err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
  1499. "email": ch.client.Email,
  1500. "id": ch.client.ID,
  1501. "security": ch.client.Security,
  1502. "flow": ch.client.Flow,
  1503. "auth": ch.client.Auth,
  1504. "password": ch.client.Password,
  1505. "cipher": cipher,
  1506. })
  1507. if err1 != nil {
  1508. logger.Debug("Error in adding client on", rt.Name(), ":", err1)
  1509. res.needRestart = true
  1510. }
  1511. } else if ch.wasEnable {
  1512. err1 := rt.RemoveUser(context.Background(), oldInbound, ch.email)
  1513. if err1 != nil && !strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", ch.email)) {
  1514. logger.Debug("Error in removing client on", rt.Name(), ":", err1)
  1515. res.needRestart = true
  1516. }
  1517. }
  1518. }
  1519. }
  1520. } else if push {
  1521. pushFailed := false
  1522. for _, ch := range changed {
  1523. updated := ch.client
  1524. updated.UpdatedAt = nowMs
  1525. if err1 := rt.UpdateUser(context.Background(), oldInbound, ch.email, updated); err1 != nil {
  1526. logger.Warning("Error in updating client on", rt.Name(), ":", err1)
  1527. pushFailed = true
  1528. }
  1529. }
  1530. if !pushFailed {
  1531. advancePushedInbound(rt, prevSettings, oldInbound)
  1532. }
  1533. }
  1534. return res
  1535. }