client_bulk.go 47 KB

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