client_bulk.go 51 KB

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