client_inbound_apply.go 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318
  1. package service
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "maps"
  7. "strings"
  8. "time"
  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/util/random"
  14. "github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
  15. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  16. "gorm.io/gorm"
  17. )
  18. func sameClientConfigExceptUpdatedAt(a, b map[string]any) bool {
  19. aa := maps.Clone(a)
  20. bb := maps.Clone(b)
  21. delete(aa, "updated_at")
  22. delete(bb, "updated_at")
  23. an, aerr := json.Marshal(aa)
  24. bn, berr := json.Marshal(bb)
  25. return aerr == nil && berr == nil && string(an) == string(bn)
  26. }
  27. // advancePushedInbound advances the node's reconcile-skip fingerprint from the
  28. // pre-edit settings to the saved ones after every per-client push succeeded.
  29. func advancePushedInbound(rt runtime.Runtime, prevSettings string, ib *model.Inbound) {
  30. rem, ok := rt.(*runtime.Remote)
  31. if !ok {
  32. return
  33. }
  34. prev := *ib
  35. prev.Settings = prevSettings
  36. rem.AdvancePushedInbound(&prev, ib)
  37. }
  38. // delInboundClients removes several clients from a single inbound in one pass:
  39. // one settings rewrite, one runtime sweep, one Save and one SyncInbound for the
  40. // whole batch, instead of repeating the full per-client cycle. It mirrors the
  41. // semantics of DelInboundClientByEmail for each removed client. needRestart is
  42. // the OR across all removals.
  43. func (s *ClientService) delInboundClients(inboundSvc *InboundService, inboundId int, recs []*model.ClientRecord, keepTraffic bool) (bool, error) {
  44. if len(recs) == 0 {
  45. return false, nil
  46. }
  47. defer lockInbound(inboundId).Unlock()
  48. oldInbound, err := inboundSvc.GetInbound(inboundId)
  49. if err != nil {
  50. logger.Error("Load Old Data Error")
  51. return false, err
  52. }
  53. var settings map[string]any
  54. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  55. return false, err
  56. }
  57. // Match by email — the client's stable identity (see Delete). Removes every
  58. // entry carrying a wanted email, independent of credential drift.
  59. wanted := make(map[string]struct{}, len(recs))
  60. for _, rec := range recs {
  61. if rec.Email != "" {
  62. wanted[rec.Email] = struct{}{}
  63. }
  64. }
  65. interfaceClients, ok := settings["clients"].([]any)
  66. if !ok {
  67. return false, common.NewError("invalid clients format in inbound settings")
  68. }
  69. type removedClient struct {
  70. email string
  71. needApiDel bool
  72. }
  73. removed := make([]removedClient, 0, len(wanted))
  74. newClients := make([]any, 0, len(interfaceClients))
  75. for _, client := range interfaceClients {
  76. c, ok := client.(map[string]any)
  77. if !ok {
  78. newClients = append(newClients, client)
  79. continue
  80. }
  81. email, _ := c["email"].(string)
  82. if _, hit := wanted[email]; hit && email != "" {
  83. enable, _ := c["enable"].(bool)
  84. removed = append(removed, removedClient{email: email, needApiDel: enable})
  85. continue
  86. }
  87. newClients = append(newClients, client)
  88. }
  89. if len(removed) == 0 {
  90. return false, nil
  91. }
  92. db := database.GetDB()
  93. newClients = compactOrphans(db, newClients)
  94. if newClients == nil {
  95. newClients = []any{}
  96. }
  97. settings["clients"] = newClients
  98. newSettings, err := json.MarshalIndent(settings, "", " ")
  99. if err != nil {
  100. return false, err
  101. }
  102. prevSettings := oldInbound.Settings
  103. oldInbound.Settings = string(newSettings)
  104. var sharedSet map[string]bool
  105. if !keepTraffic {
  106. removedEmails := make([]string, 0, len(removed))
  107. for _, r := range removed {
  108. if r.email != "" {
  109. removedEmails = append(removedEmails, r.email)
  110. }
  111. }
  112. var sharedErr error
  113. sharedSet, sharedErr = inboundSvc.emailsUsedByOtherInbounds(removedEmails, inboundId)
  114. if sharedErr != nil {
  115. return false, sharedErr
  116. }
  117. }
  118. needRestart := false
  119. // Read each client's live state before the DB write (DelClientStat would
  120. // erase the enable flag we need to decide on a runtime removal).
  121. type delTarget struct {
  122. email string
  123. emailShared bool
  124. notDepleted bool
  125. needApiDel bool
  126. }
  127. targets := make([]delTarget, 0, len(removed))
  128. for _, r := range removed {
  129. email := r.email
  130. emailShared := sharedSet[strings.ToLower(strings.TrimSpace(email))]
  131. notDepleted := false
  132. if len(email) > 0 {
  133. var enables []bool
  134. if err := db.Model(xray.ClientTraffic{}).Where("email = ?", email).Limit(1).Pluck("enable", &enables).Error; err != nil {
  135. logger.Error("Get stats error")
  136. return needRestart, err
  137. }
  138. notDepleted = len(enables) > 0 && enables[0]
  139. }
  140. targets = append(targets, delTarget{email: email, emailShared: emailShared, notDepleted: notDepleted, needApiDel: r.needApiDel})
  141. }
  142. // Persist the batch deletion atomically, serialized against the traffic poll
  143. // to avoid the cross-transaction lock-order deadlock (runSerializedTx).
  144. if txErr := runSerializedTx(func(tx *gorm.DB) error {
  145. for _, t := range targets {
  146. if t.emailShared || keepTraffic {
  147. continue
  148. }
  149. if e := inboundSvc.DelClientIPs(tx, t.email); e != nil {
  150. logger.Error("Error in delete client IPs")
  151. return e
  152. }
  153. if len(t.email) > 0 {
  154. if e := inboundSvc.DelClientStat(tx, t.email); e != nil {
  155. logger.Error("Delete stats Data Error")
  156. return e
  157. }
  158. }
  159. }
  160. if e := tx.Save(oldInbound).Error; e != nil {
  161. return e
  162. }
  163. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  164. if gcErr != nil {
  165. return gcErr
  166. }
  167. if err := s.SyncInbound(tx, inboundId, finalClients); err != nil {
  168. return err
  169. }
  170. if oldInbound.NodeID != nil {
  171. return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID)
  172. }
  173. return nil
  174. }); txErr != nil {
  175. return needRestart, txErr
  176. }
  177. // Resolve the node push plan once for the whole batch instead of per email.
  178. var nodeRt runtime.Runtime
  179. nodePush := false
  180. if oldInbound.NodeID != nil {
  181. rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound)
  182. if perr != nil {
  183. return needRestart, perr
  184. }
  185. nodeRt, nodePush = rt, push
  186. // Large batches collapse into one reconcile push rather than M deletes.
  187. if nodePush && len(targets) > nodeBulkPushThreshold {
  188. nodePush = false
  189. }
  190. }
  191. // Apply runtime deletes after commit — outside the serialized writer so a
  192. // slow node call can't stall traffic accounting.
  193. nodePushFailed := false
  194. for _, t := range targets {
  195. if len(t.email) == 0 {
  196. continue
  197. }
  198. if oldInbound.NodeID == nil {
  199. if t.needApiDel && t.notDepleted {
  200. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  201. if rterr != nil {
  202. needRestart = true
  203. } else if err1 := rt.RemoveUser(context.Background(), oldInbound, t.email); err1 != nil {
  204. if !strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", t.email)) {
  205. needRestart = true
  206. }
  207. }
  208. }
  209. } else if nodePush {
  210. if err1 := nodeRt.DeleteUser(context.Background(), oldInbound, t.email); err1 != nil {
  211. logger.Warning("Error in deleting client on", nodeRt.Name(), ":", err1)
  212. nodePushFailed = true
  213. }
  214. }
  215. }
  216. if nodePush && !nodePushFailed {
  217. advancePushedInbound(nodeRt, prevSettings, oldInbound)
  218. }
  219. return needRestart, nil
  220. }
  221. func (s *ClientService) checkEmailsExistForClients(inboundSvc *InboundService, clients []model.Client, emailSubIDs map[string]string) (string, error) {
  222. if emailSubIDs == nil {
  223. var err error
  224. emailSubIDs, err = inboundSvc.getAllEmailSubIDs()
  225. if err != nil {
  226. return "", err
  227. }
  228. }
  229. seen := make(map[string]string, len(clients))
  230. for _, client := range clients {
  231. if client.Email == "" {
  232. continue
  233. }
  234. key := strings.ToLower(client.Email)
  235. if prev, ok := seen[key]; ok {
  236. if prev != client.SubID || client.SubID == "" {
  237. return client.Email, nil
  238. }
  239. continue
  240. }
  241. seen[key] = client.SubID
  242. if existingSub, ok := emailSubIDs[key]; ok {
  243. if client.SubID == "" || existingSub == "" || existingSub != client.SubID {
  244. return client.Email, nil
  245. }
  246. }
  247. }
  248. return "", nil
  249. }
  250. func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model.Inbound) (bool, error) {
  251. return s.addInboundClient(inboundSvc, data, nil)
  252. }
  253. // addInboundClient is AddInboundClient with an optional precomputed email→subId
  254. // map. Bulk callers pass a single snapshot so the global getAllEmailSubIDs scan
  255. // runs once for the whole batch instead of once per target inbound; a nil map
  256. // makes it compute its own (the single-add path).
  257. func (s *ClientService) addInboundClient(inboundSvc *InboundService, data *model.Inbound, emailSubIDs map[string]string) (bool, error) {
  258. defer lockInbound(data.Id).Unlock()
  259. clients, err := inboundSvc.GetClients(data)
  260. if err != nil {
  261. return false, err
  262. }
  263. var settings map[string]any
  264. err = json.Unmarshal([]byte(data.Settings), &settings)
  265. if err != nil {
  266. return false, err
  267. }
  268. interfaceClients := settings["clients"].([]any)
  269. nowTs := time.Now().Unix() * 1000
  270. for i := range interfaceClients {
  271. if cm, ok := interfaceClients[i].(map[string]any); ok {
  272. if _, ok2 := cm["created_at"]; !ok2 {
  273. cm["created_at"] = nowTs
  274. }
  275. cm["updated_at"] = nowTs
  276. existingSub, _ := cm["subId"].(string)
  277. if strings.TrimSpace(existingSub) == "" {
  278. cm["subId"] = random.NumLower(16)
  279. }
  280. interfaceClients[i] = cm
  281. }
  282. }
  283. existEmail, err := s.checkEmailsExistForClients(inboundSvc, clients, emailSubIDs)
  284. if err != nil {
  285. return false, err
  286. }
  287. if existEmail != "" {
  288. return false, common.NewError("Duplicate email:", existEmail)
  289. }
  290. oldInbound, err := inboundSvc.GetInbound(data.Id)
  291. if err != nil {
  292. return false, err
  293. }
  294. existingClients, err := inboundSvc.GetClients(oldInbound)
  295. if err != nil {
  296. return false, err
  297. }
  298. // A client already on this inbound is skipped instead of appended again:
  299. // checkEmailsExistForClients exempts a matching subId so one identity can
  300. // live on several inbounds, which let retried or raced adds duplicate the
  301. // same email inside a single settings array (#5770). clients and
  302. // interfaceClients are parsed from the same data.Settings array, so they
  303. // stay index-aligned while filtering.
  304. if len(existingClients) > 0 && len(clients) > 0 {
  305. existingEmails := make(map[string]struct{}, len(existingClients))
  306. for _, c := range existingClients {
  307. if c.Email != "" {
  308. existingEmails[strings.ToLower(c.Email)] = struct{}{}
  309. }
  310. }
  311. keptClients := make([]model.Client, 0, len(clients))
  312. keptWire := make([]any, 0, len(interfaceClients))
  313. for i, c := range clients {
  314. if c.Email != "" {
  315. if _, dup := existingEmails[strings.ToLower(c.Email)]; dup {
  316. continue
  317. }
  318. }
  319. keptClients = append(keptClients, c)
  320. if i < len(interfaceClients) {
  321. keptWire = append(keptWire, interfaceClients[i])
  322. }
  323. }
  324. if len(keptClients) == 0 {
  325. return false, nil
  326. }
  327. clients = keptClients
  328. interfaceClients = keptWire
  329. }
  330. if oldInbound.Protocol == model.WireGuard {
  331. if dErr := defaultWireguardClients(existingClients, clients, interfaceClients); dErr != nil {
  332. return false, dErr
  333. }
  334. }
  335. for _, client := range clients {
  336. if strings.TrimSpace(client.Email) == "" {
  337. return false, common.NewError("client email is required")
  338. }
  339. switch oldInbound.Protocol {
  340. case "trojan":
  341. if client.Password == "" {
  342. return false, common.NewError("empty client ID")
  343. }
  344. case "shadowsocks":
  345. if client.Email == "" {
  346. return false, common.NewError("empty client ID")
  347. }
  348. case "hysteria":
  349. if client.Auth == "" {
  350. return false, common.NewError("empty client ID")
  351. }
  352. case "wireguard":
  353. if client.PublicKey == "" {
  354. return false, common.NewError("wireguard client requires a key")
  355. }
  356. case "mtproto":
  357. if client.Secret == "" {
  358. return false, common.NewError("mtproto client requires a secret")
  359. }
  360. if client.AdTag != "" && !model.ValidMtprotoAdTag(client.AdTag) {
  361. return false, common.NewError("mtproto client ad tag must be 32 hex characters")
  362. }
  363. default:
  364. if client.ID == "" {
  365. return false, common.NewError("empty client ID")
  366. }
  367. }
  368. }
  369. var oldSettings map[string]any
  370. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  371. if err != nil {
  372. return false, err
  373. }
  374. if oldInbound.Protocol == model.Shadowsocks {
  375. applyShadowsocksClientMethod(interfaceClients, oldSettings)
  376. }
  377. oldClients, _ := oldSettings["clients"].([]any)
  378. oldClients = compactOrphans(database.GetDB(), oldClients)
  379. oldClients = append(oldClients, interfaceClients...)
  380. oldSettings["clients"] = oldClients
  381. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  382. if err != nil {
  383. return false, err
  384. }
  385. prevSettings := oldInbound.Settings
  386. oldInbound.Settings = string(newSettings)
  387. needRestart := false
  388. rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound)
  389. if perr != nil {
  390. return false, perr
  391. }
  392. // Persist client stats + inbound atomically, serialized against the traffic
  393. // poll to avoid the cross-transaction lock-order deadlock (runSerializedTx).
  394. if txErr := runSerializedTx(func(tx *gorm.DB) error {
  395. for i := range clients {
  396. if len(clients[i].Email) == 0 {
  397. continue
  398. }
  399. if e := inboundSvc.AddClientStat(tx, data.Id, &clients[i]); e != nil {
  400. return e
  401. }
  402. }
  403. if e := tx.Save(oldInbound).Error; e != nil {
  404. return e
  405. }
  406. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  407. if gcErr != nil {
  408. return gcErr
  409. }
  410. if err := s.SyncInbound(tx, oldInbound.Id, finalClients); err != nil {
  411. return err
  412. }
  413. if oldInbound.NodeID != nil {
  414. return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID)
  415. }
  416. return nil
  417. }); txErr != nil {
  418. return false, txErr
  419. }
  420. // Apply to the running runtime after commit — outside the serialized writer
  421. // so a slow node call can't stall traffic accounting.
  422. if oldInbound.NodeID == nil {
  423. if !push {
  424. needRestart = true
  425. } else if oldInbound.Protocol == model.MTProto {
  426. inboundSvc.applyLocalMtproto(oldInbound.Id)
  427. } else {
  428. for _, client := range clients {
  429. if len(client.Email) == 0 {
  430. needRestart = true
  431. continue
  432. }
  433. if !client.Enable {
  434. continue
  435. }
  436. cipher := ""
  437. if oldInbound.Protocol == "shadowsocks" {
  438. cipher = oldSettings["method"].(string)
  439. }
  440. err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
  441. "email": client.Email,
  442. "id": client.ID,
  443. "auth": client.Auth,
  444. "security": client.Security,
  445. "flow": client.Flow,
  446. "password": client.Password,
  447. "cipher": cipher,
  448. "publicKey": client.PublicKey,
  449. "allowedIPs": client.AllowedIPs,
  450. "preSharedKey": client.PreSharedKey,
  451. "keepAlive": keepAliveStr(client.KeepAlive),
  452. })
  453. if err1 == nil {
  454. logger.Debug("Client added on", rt.Name(), ":", client.Email)
  455. } else {
  456. logger.Debug("Error in adding client on", rt.Name(), ":", err1)
  457. needRestart = true
  458. }
  459. }
  460. }
  461. } else {
  462. // Large batches would be M sequential per-client RPCs; the inbound's saved
  463. // settings already hold the final set, so mark dirty and let one reconcile
  464. // push converge the node instead.
  465. if push && len(clients) > nodeBulkPushThreshold {
  466. push = false
  467. }
  468. for _, client := range clients {
  469. if push {
  470. if err1 := rt.AddClient(context.Background(), oldInbound, client); err1 != nil {
  471. logger.Warning("Error in adding client on", rt.Name(), ":", err1)
  472. push = false
  473. }
  474. }
  475. }
  476. if push {
  477. advancePushedInbound(rt, prevSettings, oldInbound)
  478. }
  479. }
  480. return needRestart, nil
  481. }
  482. func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *model.Inbound, oldEmail string) (bool, error) {
  483. defer lockInbound(data.Id).Unlock()
  484. clients, err := inboundSvc.GetClients(data)
  485. if err != nil {
  486. return false, err
  487. }
  488. var settings map[string]any
  489. err = json.Unmarshal([]byte(data.Settings), &settings)
  490. if err != nil {
  491. return false, err
  492. }
  493. interfaceClients := settings["clients"].([]any)
  494. oldInbound, err := inboundSvc.GetInbound(data.Id)
  495. if err != nil {
  496. return false, err
  497. }
  498. oldClients, err := inboundSvc.GetClients(oldInbound)
  499. if err != nil {
  500. return false, err
  501. }
  502. newClientId := ""
  503. switch oldInbound.Protocol {
  504. case "trojan":
  505. newClientId = clients[0].Password
  506. case "shadowsocks":
  507. newClientId = clients[0].Email
  508. case "hysteria":
  509. newClientId = clients[0].Auth
  510. case "wireguard":
  511. newClientId = clients[0].Email
  512. case "mtproto":
  513. newClientId = clients[0].Email
  514. default:
  515. newClientId = clients[0].ID
  516. }
  517. // Locate the client to replace by email — the client's stable identity.
  518. // Credentials (uuid/password/auth) can drift from the inbound JSON, so they
  519. // are never used for matching.
  520. clientIndex := -1
  521. for index, oldClient := range oldClients {
  522. if strings.EqualFold(oldClient.Email, oldEmail) {
  523. oldEmail = oldClient.Email
  524. clientIndex = index
  525. break
  526. }
  527. }
  528. if newClientId == "" || clientIndex == -1 {
  529. return false, common.NewError("empty client ID")
  530. }
  531. if strings.TrimSpace(clients[0].Email) == "" {
  532. return false, common.NewError("client email is required")
  533. }
  534. if oldInbound.Protocol == model.MTProto && clients[0].AdTag != "" && !model.ValidMtprotoAdTag(clients[0].AdTag) {
  535. return false, common.NewError("mtproto client ad tag must be 32 hex characters")
  536. }
  537. if clients[0].Email != oldEmail {
  538. existEmail, err := s.checkEmailsExistForClients(inboundSvc, clients, nil)
  539. if err != nil {
  540. return false, err
  541. }
  542. if existEmail != "" {
  543. return false, common.NewError("Duplicate email:", existEmail)
  544. }
  545. }
  546. // WireGuard keys are never rotated by an edit: when the incoming payload omits
  547. // them (a metadata-only change), carry the stored credentials forward so the
  548. // settings JSON and the running peer keep the client's identity.
  549. if oldInbound.Protocol == model.WireGuard && clientIndex >= 0 && clientIndex < len(oldClients) {
  550. old := oldClients[clientIndex]
  551. if clients[0].PrivateKey == "" {
  552. clients[0].PrivateKey = old.PrivateKey
  553. }
  554. if clients[0].PublicKey == "" {
  555. clients[0].PublicKey = old.PublicKey
  556. }
  557. if len(clients[0].AllowedIPs) == 0 {
  558. clients[0].AllowedIPs = old.AllowedIPs
  559. } else {
  560. normalized, nErr := normalizeWireguardAllowedIPs(clients[0].AllowedIPs)
  561. if nErr != nil {
  562. return false, nErr
  563. }
  564. if len(normalized) == 0 {
  565. clients[0].AllowedIPs = old.AllowedIPs
  566. } else {
  567. peers := make([]string, 0, len(oldClients))
  568. for i := range oldClients {
  569. if i == clientIndex {
  570. continue
  571. }
  572. peers = append(peers, oldClients[i].AllowedIPs...)
  573. }
  574. if hit := wireguardAllowedIPsCollision(normalized, peers); hit != "" {
  575. return false, common.NewError("wireguard: allowedIPs entry already used by another client:", hit)
  576. }
  577. clients[0].AllowedIPs = normalized
  578. }
  579. }
  580. if clients[0].PreSharedKey == "" {
  581. clients[0].PreSharedKey = old.PreSharedKey
  582. }
  583. if clients[0].KeepAlive == 0 {
  584. clients[0].KeepAlive = old.KeepAlive
  585. }
  586. }
  587. var oldSettings map[string]any
  588. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  589. if err != nil {
  590. return false, err
  591. }
  592. settingsClients, _ := oldSettings["clients"].([]any)
  593. var preservedCreated any
  594. var preservedSubID string
  595. var oldClientMap map[string]any
  596. if clientIndex >= 0 && clientIndex < len(settingsClients) {
  597. if oldMap, ok := settingsClients[clientIndex].(map[string]any); ok {
  598. oldClientMap = oldMap
  599. if v, ok2 := oldMap["created_at"]; ok2 {
  600. preservedCreated = v
  601. }
  602. preservedSubID, _ = oldMap["subId"].(string)
  603. }
  604. }
  605. if oldInbound.Protocol == model.Shadowsocks {
  606. applyShadowsocksClientMethod(interfaceClients, oldSettings)
  607. }
  608. if len(interfaceClients) > 0 {
  609. if newMap, ok := interfaceClients[0].(map[string]any); ok {
  610. if preservedCreated == nil {
  611. preservedCreated = time.Now().Unix() * 1000
  612. }
  613. newMap["created_at"] = preservedCreated
  614. newSub, _ := newMap["subId"].(string)
  615. if strings.TrimSpace(newSub) == "" {
  616. if strings.TrimSpace(preservedSubID) != "" {
  617. newMap["subId"] = preservedSubID
  618. } else {
  619. newMap["subId"] = random.NumLower(16)
  620. }
  621. }
  622. if v, ok2 := newMap["subId"].(string); ok2 {
  623. clients[0].SubID = v
  624. }
  625. if oldInbound.Protocol == model.WireGuard {
  626. newMap["privateKey"] = clients[0].PrivateKey
  627. newMap["publicKey"] = clients[0].PublicKey
  628. newMap["allowedIPs"] = clients[0].AllowedIPs
  629. if clients[0].PreSharedKey != "" {
  630. newMap["preSharedKey"] = clients[0].PreSharedKey
  631. }
  632. if clients[0].KeepAlive > 0 {
  633. newMap["keepAlive"] = clients[0].KeepAlive
  634. }
  635. }
  636. if oldClientMap != nil && sameClientConfigExceptUpdatedAt(oldClientMap, newMap) {
  637. if v, ok2 := oldClientMap["updated_at"]; ok2 {
  638. newMap["updated_at"] = v
  639. } else {
  640. delete(newMap, "updated_at")
  641. }
  642. } else {
  643. newMap["updated_at"] = time.Now().Unix() * 1000
  644. }
  645. interfaceClients[0] = newMap
  646. }
  647. }
  648. settingsClients[clientIndex] = interfaceClients[0]
  649. oldSettings["clients"] = settingsClients
  650. if oldInbound.Protocol == model.VLESS {
  651. hasVisionFlow := false
  652. for _, c := range settingsClients {
  653. cm, ok := c.(map[string]any)
  654. if !ok {
  655. continue
  656. }
  657. if flow, _ := cm["flow"].(string); flow == "xtls-rprx-vision" {
  658. hasVisionFlow = true
  659. break
  660. }
  661. }
  662. if !hasVisionFlow {
  663. delete(oldSettings, "testseed")
  664. }
  665. }
  666. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  667. if err != nil {
  668. return false, err
  669. }
  670. if string(newSettings) == oldInbound.Settings {
  671. return false, nil
  672. }
  673. prevSettings := oldInbound.Settings
  674. oldInbound.Settings = string(newSettings)
  675. needRestart := false
  676. // Resolve the push plan before the DB write so a node-state lookup failure
  677. // still aborts the whole update without committing anything (it used to roll
  678. // the transaction back). nodePushPlan only reads, so order doesn't matter.
  679. var rt runtime.Runtime
  680. var push bool
  681. if len(oldEmail) > 0 {
  682. var perr error
  683. rt, push, _, perr = inboundSvc.nodePushPlan(oldInbound)
  684. if perr != nil {
  685. return false, perr
  686. }
  687. }
  688. // Persist client stats + inbound atomically, serialized against the traffic
  689. // poll to avoid the cross-transaction lock-order deadlock (runSerializedTx).
  690. if txErr := runSerializedTx(func(tx *gorm.DB) error {
  691. if len(clients[0].Email) > 0 {
  692. if len(oldEmail) > 0 {
  693. emailUnchanged := strings.EqualFold(oldEmail, clients[0].Email)
  694. targetExists := int64(0)
  695. if !emailUnchanged {
  696. if e := tx.Model(xray.ClientTraffic{}).Where("email = ?", clients[0].Email).Count(&targetExists).Error; e != nil {
  697. return e
  698. }
  699. }
  700. if emailUnchanged || targetExists == 0 {
  701. if e := inboundSvc.UpdateClientStat(tx, oldEmail, &clients[0]); e != nil {
  702. return e
  703. }
  704. if e := inboundSvc.UpdateClientIPs(tx, oldEmail, clients[0].Email); e != nil {
  705. return e
  706. }
  707. } else {
  708. stillUsed, sErr := inboundSvc.emailUsedByOtherInbounds(oldEmail, data.Id)
  709. if sErr != nil {
  710. return sErr
  711. }
  712. if !stillUsed {
  713. if e := inboundSvc.DelClientStat(tx, oldEmail); e != nil {
  714. return e
  715. }
  716. if e := inboundSvc.DelClientIPs(tx, oldEmail); e != nil {
  717. return e
  718. }
  719. }
  720. if e := inboundSvc.UpdateClientStat(tx, clients[0].Email, &clients[0]); e != nil {
  721. return e
  722. }
  723. }
  724. } else {
  725. if e := inboundSvc.AddClientStat(tx, data.Id, &clients[0]); e != nil {
  726. return e
  727. }
  728. }
  729. } else {
  730. stillUsed, sErr := inboundSvc.emailUsedByOtherInbounds(oldEmail, data.Id)
  731. if sErr != nil {
  732. return sErr
  733. }
  734. if !stillUsed {
  735. if e := inboundSvc.DelClientStat(tx, oldEmail); e != nil {
  736. return e
  737. }
  738. if e := inboundSvc.DelClientIPs(tx, oldEmail); e != nil {
  739. return e
  740. }
  741. }
  742. }
  743. if e := tx.Save(oldInbound).Error; e != nil {
  744. return e
  745. }
  746. // Rename the client record in the same transaction as the settings JSON
  747. // so no concurrent SyncInbound can see one renamed without the other.
  748. if len(oldEmail) > 0 && !strings.EqualFold(oldEmail, clients[0].Email) {
  749. var renameTaken int64
  750. if e := tx.Model(&model.ClientRecord{}).Where("email = ?", clients[0].Email).Count(&renameTaken).Error; e != nil {
  751. return e
  752. }
  753. if renameTaken == 0 {
  754. if e := tx.Model(&model.ClientRecord{}).Where("email = ?", oldEmail).Update("email", clients[0].Email).Error; e != nil {
  755. return e
  756. }
  757. }
  758. }
  759. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  760. if gcErr != nil {
  761. return gcErr
  762. }
  763. if err := s.SyncInbound(tx, oldInbound.Id, finalClients); err != nil {
  764. return err
  765. }
  766. if oldInbound.NodeID != nil {
  767. return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID)
  768. }
  769. return nil
  770. }); txErr != nil {
  771. return false, txErr
  772. }
  773. // Apply to the running runtime after the DB is committed — outside the
  774. // serialized writer so a slow node call can't stall traffic accounting.
  775. if len(oldEmail) > 0 {
  776. if oldInbound.NodeID == nil {
  777. if !push {
  778. needRestart = true
  779. } else if oldInbound.Protocol == model.MTProto {
  780. inboundSvc.applyLocalMtproto(oldInbound.Id)
  781. } else {
  782. if oldClients[clientIndex].Enable {
  783. err1 := rt.RemoveUser(context.Background(), oldInbound, oldEmail)
  784. if err1 == nil {
  785. logger.Debug("Old client deleted on", rt.Name(), ":", oldEmail)
  786. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", oldEmail)) {
  787. logger.Debug("User is already deleted. Nothing to do more...")
  788. } else {
  789. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  790. needRestart = true
  791. }
  792. }
  793. if clients[0].Enable {
  794. cipher := ""
  795. if oldInbound.Protocol == "shadowsocks" {
  796. cipher = oldSettings["method"].(string)
  797. }
  798. err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
  799. "email": clients[0].Email,
  800. "id": clients[0].ID,
  801. "security": clients[0].Security,
  802. "flow": clients[0].Flow,
  803. "auth": clients[0].Auth,
  804. "password": clients[0].Password,
  805. "cipher": cipher,
  806. "publicKey": clients[0].PublicKey,
  807. "allowedIPs": clients[0].AllowedIPs,
  808. "preSharedKey": clients[0].PreSharedKey,
  809. "keepAlive": keepAliveStr(clients[0].KeepAlive),
  810. })
  811. if err1 == nil {
  812. logger.Debug("Client edited on", rt.Name(), ":", clients[0].Email)
  813. } else {
  814. logger.Debug("Error in adding client on", rt.Name(), ":", err1)
  815. needRestart = true
  816. }
  817. }
  818. }
  819. } else if push {
  820. if err1 := rt.UpdateUser(context.Background(), oldInbound, oldEmail, clients[0]); err1 != nil {
  821. logger.Warning("Error in updating client on", rt.Name(), ":", err1)
  822. } else {
  823. advancePushedInbound(rt, prevSettings, oldInbound)
  824. }
  825. }
  826. } else {
  827. logger.Debug("Client old email not found")
  828. needRestart = true
  829. }
  830. return needRestart, nil
  831. }
  832. func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inboundId int, email string, keepTraffic bool, fullDelete bool) (bool, error) {
  833. defer lockInbound(inboundId).Unlock()
  834. oldInbound, err := inboundSvc.GetInbound(inboundId)
  835. if err != nil {
  836. logger.Error("Load Old Data Error")
  837. return false, err
  838. }
  839. var settings map[string]any
  840. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  841. return false, err
  842. }
  843. interfaceClients, ok := settings["clients"].([]any)
  844. if !ok {
  845. return false, common.NewError("invalid clients format in inbound settings")
  846. }
  847. var newClients []any
  848. needApiDel := false
  849. found := false
  850. for _, client := range interfaceClients {
  851. c, ok := client.(map[string]any)
  852. if !ok {
  853. continue
  854. }
  855. if cEmail, ok := c["email"].(string); ok && cEmail == email {
  856. found = true
  857. needApiDel, _ = c["enable"].(bool)
  858. } else {
  859. newClients = append(newClients, client)
  860. }
  861. }
  862. if !found {
  863. return false, fmt.Errorf("%w for email: %s", ErrClientNotInInbound, email)
  864. }
  865. db := database.GetDB()
  866. newClients = compactOrphans(db, newClients)
  867. if newClients == nil {
  868. newClients = []any{}
  869. }
  870. settings["clients"] = newClients
  871. newSettings, err := json.MarshalIndent(settings, "", " ")
  872. if err != nil {
  873. return false, err
  874. }
  875. prevSettings := oldInbound.Settings
  876. oldInbound.Settings = string(newSettings)
  877. emailShared, err := inboundSvc.emailUsedByOtherInbounds(email, inboundId)
  878. if err != nil {
  879. return false, err
  880. }
  881. needRestart := false
  882. // Decide what to delete and the push plan before the serialized DB write —
  883. // these are reads, and nodePushPlan failing should abort before committing.
  884. delStat := false
  885. if len(email) > 0 && !emailShared && !keepTraffic {
  886. traffic, tErr := inboundSvc.GetClientTrafficByEmail(email)
  887. if tErr != nil {
  888. return false, tErr
  889. }
  890. delStat = traffic != nil
  891. }
  892. // The runtime user is scoped to this inbound's tag + email, so the push plan
  893. // is resolved independently of emailShared — a sibling inbound still carrying
  894. // the email must not suppress removing the user from this inbound's Xray.
  895. var rt runtime.Runtime
  896. var push bool
  897. if len(email) > 0 && (oldInbound.NodeID != nil || needApiDel) {
  898. r, p, _, perr := inboundSvc.nodePushPlan(oldInbound)
  899. if perr != nil {
  900. return false, perr
  901. }
  902. rt, push = r, p
  903. }
  904. // Persist the deletion atomically, serialized against the traffic poll to
  905. // avoid the cross-transaction lock-order deadlock (runSerializedTx).
  906. if txErr := runSerializedTx(func(tx *gorm.DB) error {
  907. if !emailShared && !keepTraffic {
  908. if e := inboundSvc.DelClientIPs(tx, email); e != nil {
  909. logger.Error("Error in delete client IPs")
  910. return e
  911. }
  912. }
  913. if delStat {
  914. if e := inboundSvc.DelClientStat(tx, email); e != nil {
  915. logger.Error("Delete stats Data Error")
  916. return e
  917. }
  918. }
  919. if e := tx.Save(oldInbound).Error; e != nil {
  920. return e
  921. }
  922. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  923. if gcErr != nil {
  924. return gcErr
  925. }
  926. if err := s.SyncInbound(tx, inboundId, finalClients); err != nil {
  927. return err
  928. }
  929. if oldInbound.NodeID != nil {
  930. return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID)
  931. }
  932. return nil
  933. }); txErr != nil {
  934. return false, txErr
  935. }
  936. // Apply the runtime delete after commit — outside the serialized writer so a
  937. // slow node call can't stall traffic accounting. Independent of emailShared:
  938. // Xray users are keyed by inbound tag, so the user must be removed from this
  939. // inbound's runtime even when the same email survives in another inbound.
  940. if len(email) > 0 {
  941. if oldInbound.NodeID == nil {
  942. if oldInbound.Protocol == model.MTProto {
  943. // mtg serves the full secret set, so any client delete re-applies
  944. // it (removing the last client stops the sidecar) regardless of the
  945. // client's enable state.
  946. inboundSvc.applyLocalMtproto(oldInbound.Id)
  947. } else if needApiDel {
  948. // Local inbound: a disabled client isn't in the running Xray, so only
  949. // a live one (needApiDel) needs an API removal.
  950. if !push {
  951. needRestart = true
  952. } else if err1 := rt.RemoveUser(context.Background(), oldInbound, email); err1 == nil {
  953. logger.Debug("Client deleted on", rt.Name(), ":", email)
  954. needRestart = false
  955. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  956. logger.Debug("User is already deleted. Nothing to do more...")
  957. } else {
  958. logger.Debug("Error in deleting client on", rt.Name(), ":", email)
  959. needRestart = true
  960. }
  961. }
  962. } else {
  963. // Node inbound: propagate the delete regardless of the enable flag —
  964. // the node's own DB still carries a disabled client and would
  965. // resurrect it on the next snapshot otherwise. A full client delete
  966. // must remove the node's client record too, not just detach it from
  967. // this inbound (#5797).
  968. if push {
  969. var err1 error
  970. if fullDelete {
  971. err1 = rt.DeleteClient(context.Background(), email)
  972. } else {
  973. err1 = rt.DeleteUser(context.Background(), oldInbound, email)
  974. }
  975. if err1 != nil {
  976. logger.Warning("Error in deleting client on", rt.Name(), ":", err1)
  977. } else {
  978. advancePushedInbound(rt, prevSettings, oldInbound)
  979. }
  980. }
  981. }
  982. }
  983. return needRestart, nil
  984. }
  985. func (s *ClientService) SetClientTelegramUserID(inboundSvc *InboundService, trafficId int, tgId int64) (bool, error) {
  986. traffic, inbound, err := inboundSvc.GetClientInboundByTrafficID(trafficId)
  987. if err != nil {
  988. return false, err
  989. }
  990. if inbound == nil {
  991. return false, common.NewError("Inbound Not Found For Traffic ID:", trafficId)
  992. }
  993. clientEmail := traffic.Email
  994. oldClients, err := inboundSvc.GetClients(inbound)
  995. if err != nil {
  996. return false, err
  997. }
  998. found := false
  999. for _, oldClient := range oldClients {
  1000. if oldClient.Email == clientEmail {
  1001. found = true
  1002. break
  1003. }
  1004. }
  1005. if !found {
  1006. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1007. }
  1008. var settings map[string]any
  1009. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1010. if err != nil {
  1011. return false, err
  1012. }
  1013. clients := settings["clients"].([]any)
  1014. var newClients []any
  1015. for client_index := range clients {
  1016. c := clients[client_index].(map[string]any)
  1017. if c["email"] == clientEmail {
  1018. c["tgId"] = tgId
  1019. c["updated_at"] = time.Now().Unix() * 1000
  1020. newClients = append(newClients, any(c))
  1021. }
  1022. }
  1023. settings["clients"] = newClients
  1024. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1025. if err != nil {
  1026. return false, err
  1027. }
  1028. inbound.Settings = string(modifiedSettings)
  1029. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientEmail)
  1030. return needRestart, err
  1031. }
  1032. func (s *ClientService) CheckIsEnabledByEmail(inboundSvc *InboundService, clientEmail string) (bool, error) {
  1033. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  1034. if err != nil {
  1035. return false, err
  1036. }
  1037. if inbound == nil {
  1038. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1039. }
  1040. clients, err := inboundSvc.GetClients(inbound)
  1041. if err != nil {
  1042. return false, err
  1043. }
  1044. isEnable := false
  1045. for _, client := range clients {
  1046. if client.Email == clientEmail {
  1047. isEnable = client.Enable
  1048. break
  1049. }
  1050. }
  1051. return isEnable, err
  1052. }
  1053. func (s *ClientService) ToggleClientEnableByEmail(inboundSvc *InboundService, clientEmail string) (bool, bool, error) {
  1054. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  1055. if err != nil {
  1056. return false, false, err
  1057. }
  1058. if inbound == nil {
  1059. return false, false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1060. }
  1061. oldClients, err := inboundSvc.GetClients(inbound)
  1062. if err != nil {
  1063. return false, false, err
  1064. }
  1065. found := false
  1066. clientOldEnabled := false
  1067. for _, oldClient := range oldClients {
  1068. if oldClient.Email == clientEmail {
  1069. found = true
  1070. clientOldEnabled = oldClient.Enable
  1071. break
  1072. }
  1073. }
  1074. if !found {
  1075. return false, false, common.NewError("Client Not Found For Email:", clientEmail)
  1076. }
  1077. var settings map[string]any
  1078. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1079. if err != nil {
  1080. return false, false, err
  1081. }
  1082. clients := settings["clients"].([]any)
  1083. var newClients []any
  1084. for client_index := range clients {
  1085. c := clients[client_index].(map[string]any)
  1086. if c["email"] == clientEmail {
  1087. c["enable"] = !clientOldEnabled
  1088. c["updated_at"] = time.Now().Unix() * 1000
  1089. newClients = append(newClients, any(c))
  1090. }
  1091. }
  1092. settings["clients"] = newClients
  1093. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1094. if err != nil {
  1095. return false, false, err
  1096. }
  1097. inbound.Settings = string(modifiedSettings)
  1098. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientEmail)
  1099. if err != nil {
  1100. return false, needRestart, err
  1101. }
  1102. return !clientOldEnabled, needRestart, nil
  1103. }
  1104. func (s *ClientService) SetClientEnableByEmail(inboundSvc *InboundService, clientEmail string, enable bool) (bool, bool, error) {
  1105. current, err := s.CheckIsEnabledByEmail(inboundSvc, clientEmail)
  1106. if err != nil {
  1107. return false, false, err
  1108. }
  1109. if current == enable {
  1110. return false, false, nil
  1111. }
  1112. newEnabled, needRestart, err := s.ToggleClientEnableByEmail(inboundSvc, clientEmail)
  1113. if err != nil {
  1114. return false, needRestart, err
  1115. }
  1116. return newEnabled == enable, needRestart, nil
  1117. }
  1118. // applyClientFieldByEmail loads the inbound currently hosting clientEmail,
  1119. // confirms the client exists, applies mutate to the matching client (plus a
  1120. // refreshed updated_at), and hands a single-client update payload to
  1121. // UpdateInboundClient. The rebuilt clients array intentionally contains only
  1122. // the matched client — that is the input contract UpdateInboundClient expects
  1123. // (clients[0] is the new data; clientEmail locates the row to replace). It
  1124. // backs the single-field by-email setters below.
  1125. // applyClientFieldByEmail mutates a client field on every inbound the email is
  1126. // attached to. A multi-inbound client is one logical identity: patching only
  1127. // the first inbound's JSON would leave the siblings stale, and the next
  1128. // SyncInbound over a stale sibling would revert the edit in the normalized
  1129. // records (#5039).
  1130. func (s *ClientService) applyClientFieldByEmail(inboundSvc *InboundService, clientEmail string, mutate func(c map[string]any)) (bool, error) {
  1131. inboundIds, err := s.GetInboundIdsForEmail(database.GetDB(), clientEmail)
  1132. if err != nil {
  1133. return false, err
  1134. }
  1135. if len(inboundIds) == 0 {
  1136. // Legacy fallback for clients that only live in the inbound JSON and
  1137. // were never normalized into client_inbounds.
  1138. _, inbound, gErr := inboundSvc.GetClientInboundByEmail(clientEmail)
  1139. if gErr != nil {
  1140. return false, gErr
  1141. }
  1142. if inbound == nil {
  1143. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1144. }
  1145. inboundIds = []int{inbound.Id}
  1146. }
  1147. needRestart := false
  1148. found := false
  1149. for _, ibId := range inboundIds {
  1150. inbound, gErr := inboundSvc.GetInbound(ibId)
  1151. if gErr != nil {
  1152. return needRestart, gErr
  1153. }
  1154. var settings map[string]any
  1155. if uErr := json.Unmarshal([]byte(inbound.Settings), &settings); uErr != nil {
  1156. return needRestart, uErr
  1157. }
  1158. clients, _ := settings["clients"].([]any)
  1159. // UpdateInboundClient expects a single-client payload, so keep only the
  1160. // matching entry in the scratch copy; it splices the result back into
  1161. // the inbound's full client list itself.
  1162. var newClients []any
  1163. for client_index := range clients {
  1164. c, ok := clients[client_index].(map[string]any)
  1165. if !ok {
  1166. continue
  1167. }
  1168. if c["email"] == clientEmail {
  1169. mutate(c)
  1170. c["updated_at"] = time.Now().Unix() * 1000
  1171. newClients = append(newClients, any(c))
  1172. }
  1173. }
  1174. if len(newClients) == 0 {
  1175. continue
  1176. }
  1177. found = true
  1178. settings["clients"] = newClients
  1179. modifiedSettings, mErr := json.MarshalIndent(settings, "", " ")
  1180. if mErr != nil {
  1181. return needRestart, mErr
  1182. }
  1183. inbound.Settings = string(modifiedSettings)
  1184. nr, uErr := s.UpdateInboundClient(inboundSvc, inbound, clientEmail)
  1185. if uErr != nil {
  1186. return needRestart, uErr
  1187. }
  1188. needRestart = needRestart || nr
  1189. }
  1190. if !found {
  1191. return needRestart, common.NewError("Client Not Found For Email:", clientEmail)
  1192. }
  1193. return needRestart, nil
  1194. }
  1195. func (s *ClientService) ResetClientIpLimitByEmail(inboundSvc *InboundService, clientEmail string, count int) (bool, error) {
  1196. return s.applyClientFieldByEmail(inboundSvc, clientEmail, func(c map[string]any) {
  1197. c["limitIp"] = count
  1198. })
  1199. }
  1200. func (s *ClientService) ResetClientExpiryTimeByEmail(inboundSvc *InboundService, clientEmail string, expiry_time int64) (bool, error) {
  1201. return s.applyClientFieldByEmail(inboundSvc, clientEmail, func(c map[string]any) {
  1202. c["expiryTime"] = expiry_time
  1203. })
  1204. }
  1205. func (s *ClientService) ResetClientTrafficLimitByEmail(inboundSvc *InboundService, clientEmail string, totalGB int) (bool, error) {
  1206. if totalGB < 0 {
  1207. return false, common.NewError("totalGB must be >= 0")
  1208. }
  1209. return s.applyClientFieldByEmail(inboundSvc, clientEmail, func(c map[string]any) {
  1210. c["totalGB"] = totalGB * 1024 * 1024 * 1024
  1211. })
  1212. }