client_inbound_apply.go 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305
  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. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  747. if gcErr != nil {
  748. return gcErr
  749. }
  750. if err := s.SyncInbound(tx, oldInbound.Id, finalClients); err != nil {
  751. return err
  752. }
  753. if oldInbound.NodeID != nil {
  754. return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID)
  755. }
  756. return nil
  757. }); txErr != nil {
  758. return false, txErr
  759. }
  760. // Apply to the running runtime after the DB is committed — outside the
  761. // serialized writer so a slow node call can't stall traffic accounting.
  762. if len(oldEmail) > 0 {
  763. if oldInbound.NodeID == nil {
  764. if !push {
  765. needRestart = true
  766. } else if oldInbound.Protocol == model.MTProto {
  767. inboundSvc.applyLocalMtproto(oldInbound.Id)
  768. } else {
  769. if oldClients[clientIndex].Enable {
  770. err1 := rt.RemoveUser(context.Background(), oldInbound, oldEmail)
  771. if err1 == nil {
  772. logger.Debug("Old client deleted on", rt.Name(), ":", oldEmail)
  773. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", oldEmail)) {
  774. logger.Debug("User is already deleted. Nothing to do more...")
  775. } else {
  776. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  777. needRestart = true
  778. }
  779. }
  780. if clients[0].Enable {
  781. cipher := ""
  782. if oldInbound.Protocol == "shadowsocks" {
  783. cipher = oldSettings["method"].(string)
  784. }
  785. err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
  786. "email": clients[0].Email,
  787. "id": clients[0].ID,
  788. "security": clients[0].Security,
  789. "flow": clients[0].Flow,
  790. "auth": clients[0].Auth,
  791. "password": clients[0].Password,
  792. "cipher": cipher,
  793. "publicKey": clients[0].PublicKey,
  794. "allowedIPs": clients[0].AllowedIPs,
  795. "preSharedKey": clients[0].PreSharedKey,
  796. "keepAlive": keepAliveStr(clients[0].KeepAlive),
  797. })
  798. if err1 == nil {
  799. logger.Debug("Client edited on", rt.Name(), ":", clients[0].Email)
  800. } else {
  801. logger.Debug("Error in adding client on", rt.Name(), ":", err1)
  802. needRestart = true
  803. }
  804. }
  805. }
  806. } else if push {
  807. if err1 := rt.UpdateUser(context.Background(), oldInbound, oldEmail, clients[0]); err1 != nil {
  808. logger.Warning("Error in updating client on", rt.Name(), ":", err1)
  809. } else {
  810. advancePushedInbound(rt, prevSettings, oldInbound)
  811. }
  812. }
  813. } else {
  814. logger.Debug("Client old email not found")
  815. needRestart = true
  816. }
  817. return needRestart, nil
  818. }
  819. func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inboundId int, email string, keepTraffic bool, fullDelete bool) (bool, error) {
  820. defer lockInbound(inboundId).Unlock()
  821. oldInbound, err := inboundSvc.GetInbound(inboundId)
  822. if err != nil {
  823. logger.Error("Load Old Data Error")
  824. return false, err
  825. }
  826. var settings map[string]any
  827. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  828. return false, err
  829. }
  830. interfaceClients, ok := settings["clients"].([]any)
  831. if !ok {
  832. return false, common.NewError("invalid clients format in inbound settings")
  833. }
  834. var newClients []any
  835. needApiDel := false
  836. found := false
  837. for _, client := range interfaceClients {
  838. c, ok := client.(map[string]any)
  839. if !ok {
  840. continue
  841. }
  842. if cEmail, ok := c["email"].(string); ok && cEmail == email {
  843. found = true
  844. needApiDel, _ = c["enable"].(bool)
  845. } else {
  846. newClients = append(newClients, client)
  847. }
  848. }
  849. if !found {
  850. return false, fmt.Errorf("%w for email: %s", ErrClientNotInInbound, email)
  851. }
  852. db := database.GetDB()
  853. newClients = compactOrphans(db, newClients)
  854. if newClients == nil {
  855. newClients = []any{}
  856. }
  857. settings["clients"] = newClients
  858. newSettings, err := json.MarshalIndent(settings, "", " ")
  859. if err != nil {
  860. return false, err
  861. }
  862. prevSettings := oldInbound.Settings
  863. oldInbound.Settings = string(newSettings)
  864. emailShared, err := inboundSvc.emailUsedByOtherInbounds(email, inboundId)
  865. if err != nil {
  866. return false, err
  867. }
  868. needRestart := false
  869. // Decide what to delete and the push plan before the serialized DB write —
  870. // these are reads, and nodePushPlan failing should abort before committing.
  871. delStat := false
  872. if len(email) > 0 && !emailShared && !keepTraffic {
  873. traffic, tErr := inboundSvc.GetClientTrafficByEmail(email)
  874. if tErr != nil {
  875. return false, tErr
  876. }
  877. delStat = traffic != nil
  878. }
  879. // The runtime user is scoped to this inbound's tag + email, so the push plan
  880. // is resolved independently of emailShared — a sibling inbound still carrying
  881. // the email must not suppress removing the user from this inbound's Xray.
  882. var rt runtime.Runtime
  883. var push bool
  884. if len(email) > 0 && (oldInbound.NodeID != nil || needApiDel) {
  885. r, p, _, perr := inboundSvc.nodePushPlan(oldInbound)
  886. if perr != nil {
  887. return false, perr
  888. }
  889. rt, push = r, p
  890. }
  891. // Persist the deletion atomically, serialized against the traffic poll to
  892. // avoid the cross-transaction lock-order deadlock (runSerializedTx).
  893. if txErr := runSerializedTx(func(tx *gorm.DB) error {
  894. if !emailShared && !keepTraffic {
  895. if e := inboundSvc.DelClientIPs(tx, email); e != nil {
  896. logger.Error("Error in delete client IPs")
  897. return e
  898. }
  899. }
  900. if delStat {
  901. if e := inboundSvc.DelClientStat(tx, email); e != nil {
  902. logger.Error("Delete stats Data Error")
  903. return e
  904. }
  905. }
  906. if e := tx.Save(oldInbound).Error; e != nil {
  907. return e
  908. }
  909. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  910. if gcErr != nil {
  911. return gcErr
  912. }
  913. if err := s.SyncInbound(tx, inboundId, finalClients); err != nil {
  914. return err
  915. }
  916. if oldInbound.NodeID != nil {
  917. return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID)
  918. }
  919. return nil
  920. }); txErr != nil {
  921. return false, txErr
  922. }
  923. // Apply the runtime delete after commit — outside the serialized writer so a
  924. // slow node call can't stall traffic accounting. Independent of emailShared:
  925. // Xray users are keyed by inbound tag, so the user must be removed from this
  926. // inbound's runtime even when the same email survives in another inbound.
  927. if len(email) > 0 {
  928. if oldInbound.NodeID == nil {
  929. if oldInbound.Protocol == model.MTProto {
  930. // mtg serves the full secret set, so any client delete re-applies
  931. // it (removing the last client stops the sidecar) regardless of the
  932. // client's enable state.
  933. inboundSvc.applyLocalMtproto(oldInbound.Id)
  934. } else if needApiDel {
  935. // Local inbound: a disabled client isn't in the running Xray, so only
  936. // a live one (needApiDel) needs an API removal.
  937. if !push {
  938. needRestart = true
  939. } else if err1 := rt.RemoveUser(context.Background(), oldInbound, email); err1 == nil {
  940. logger.Debug("Client deleted on", rt.Name(), ":", email)
  941. needRestart = false
  942. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  943. logger.Debug("User is already deleted. Nothing to do more...")
  944. } else {
  945. logger.Debug("Error in deleting client on", rt.Name(), ":", email)
  946. needRestart = true
  947. }
  948. }
  949. } else {
  950. // Node inbound: propagate the delete regardless of the enable flag —
  951. // the node's own DB still carries a disabled client and would
  952. // resurrect it on the next snapshot otherwise. A full client delete
  953. // must remove the node's client record too, not just detach it from
  954. // this inbound (#5797).
  955. if push {
  956. var err1 error
  957. if fullDelete {
  958. err1 = rt.DeleteClient(context.Background(), email)
  959. } else {
  960. err1 = rt.DeleteUser(context.Background(), oldInbound, email)
  961. }
  962. if err1 != nil {
  963. logger.Warning("Error in deleting client on", rt.Name(), ":", err1)
  964. } else {
  965. advancePushedInbound(rt, prevSettings, oldInbound)
  966. }
  967. }
  968. }
  969. }
  970. return needRestart, nil
  971. }
  972. func (s *ClientService) SetClientTelegramUserID(inboundSvc *InboundService, trafficId int, tgId int64) (bool, error) {
  973. traffic, inbound, err := inboundSvc.GetClientInboundByTrafficID(trafficId)
  974. if err != nil {
  975. return false, err
  976. }
  977. if inbound == nil {
  978. return false, common.NewError("Inbound Not Found For Traffic ID:", trafficId)
  979. }
  980. clientEmail := traffic.Email
  981. oldClients, err := inboundSvc.GetClients(inbound)
  982. if err != nil {
  983. return false, err
  984. }
  985. found := false
  986. for _, oldClient := range oldClients {
  987. if oldClient.Email == clientEmail {
  988. found = true
  989. break
  990. }
  991. }
  992. if !found {
  993. return false, common.NewError("Client Not Found For Email:", clientEmail)
  994. }
  995. var settings map[string]any
  996. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  997. if err != nil {
  998. return false, err
  999. }
  1000. clients := settings["clients"].([]any)
  1001. var newClients []any
  1002. for client_index := range clients {
  1003. c := clients[client_index].(map[string]any)
  1004. if c["email"] == clientEmail {
  1005. c["tgId"] = tgId
  1006. c["updated_at"] = time.Now().Unix() * 1000
  1007. newClients = append(newClients, any(c))
  1008. }
  1009. }
  1010. settings["clients"] = newClients
  1011. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1012. if err != nil {
  1013. return false, err
  1014. }
  1015. inbound.Settings = string(modifiedSettings)
  1016. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientEmail)
  1017. return needRestart, err
  1018. }
  1019. func (s *ClientService) CheckIsEnabledByEmail(inboundSvc *InboundService, clientEmail string) (bool, error) {
  1020. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  1021. if err != nil {
  1022. return false, err
  1023. }
  1024. if inbound == nil {
  1025. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1026. }
  1027. clients, err := inboundSvc.GetClients(inbound)
  1028. if err != nil {
  1029. return false, err
  1030. }
  1031. isEnable := false
  1032. for _, client := range clients {
  1033. if client.Email == clientEmail {
  1034. isEnable = client.Enable
  1035. break
  1036. }
  1037. }
  1038. return isEnable, err
  1039. }
  1040. func (s *ClientService) ToggleClientEnableByEmail(inboundSvc *InboundService, clientEmail string) (bool, bool, error) {
  1041. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  1042. if err != nil {
  1043. return false, false, err
  1044. }
  1045. if inbound == nil {
  1046. return false, false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1047. }
  1048. oldClients, err := inboundSvc.GetClients(inbound)
  1049. if err != nil {
  1050. return false, false, err
  1051. }
  1052. found := false
  1053. clientOldEnabled := false
  1054. for _, oldClient := range oldClients {
  1055. if oldClient.Email == clientEmail {
  1056. found = true
  1057. clientOldEnabled = oldClient.Enable
  1058. break
  1059. }
  1060. }
  1061. if !found {
  1062. return false, false, common.NewError("Client Not Found For Email:", clientEmail)
  1063. }
  1064. var settings map[string]any
  1065. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1066. if err != nil {
  1067. return false, false, err
  1068. }
  1069. clients := settings["clients"].([]any)
  1070. var newClients []any
  1071. for client_index := range clients {
  1072. c := clients[client_index].(map[string]any)
  1073. if c["email"] == clientEmail {
  1074. c["enable"] = !clientOldEnabled
  1075. c["updated_at"] = time.Now().Unix() * 1000
  1076. newClients = append(newClients, any(c))
  1077. }
  1078. }
  1079. settings["clients"] = newClients
  1080. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1081. if err != nil {
  1082. return false, false, err
  1083. }
  1084. inbound.Settings = string(modifiedSettings)
  1085. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientEmail)
  1086. if err != nil {
  1087. return false, needRestart, err
  1088. }
  1089. return !clientOldEnabled, needRestart, nil
  1090. }
  1091. func (s *ClientService) SetClientEnableByEmail(inboundSvc *InboundService, clientEmail string, enable bool) (bool, bool, error) {
  1092. current, err := s.CheckIsEnabledByEmail(inboundSvc, clientEmail)
  1093. if err != nil {
  1094. return false, false, err
  1095. }
  1096. if current == enable {
  1097. return false, false, nil
  1098. }
  1099. newEnabled, needRestart, err := s.ToggleClientEnableByEmail(inboundSvc, clientEmail)
  1100. if err != nil {
  1101. return false, needRestart, err
  1102. }
  1103. return newEnabled == enable, needRestart, nil
  1104. }
  1105. // applyClientFieldByEmail loads the inbound currently hosting clientEmail,
  1106. // confirms the client exists, applies mutate to the matching client (plus a
  1107. // refreshed updated_at), and hands a single-client update payload to
  1108. // UpdateInboundClient. The rebuilt clients array intentionally contains only
  1109. // the matched client — that is the input contract UpdateInboundClient expects
  1110. // (clients[0] is the new data; clientEmail locates the row to replace). It
  1111. // backs the single-field by-email setters below.
  1112. // applyClientFieldByEmail mutates a client field on every inbound the email is
  1113. // attached to. A multi-inbound client is one logical identity: patching only
  1114. // the first inbound's JSON would leave the siblings stale, and the next
  1115. // SyncInbound over a stale sibling would revert the edit in the normalized
  1116. // records (#5039).
  1117. func (s *ClientService) applyClientFieldByEmail(inboundSvc *InboundService, clientEmail string, mutate func(c map[string]any)) (bool, error) {
  1118. inboundIds, err := s.GetInboundIdsForEmail(database.GetDB(), clientEmail)
  1119. if err != nil {
  1120. return false, err
  1121. }
  1122. if len(inboundIds) == 0 {
  1123. // Legacy fallback for clients that only live in the inbound JSON and
  1124. // were never normalized into client_inbounds.
  1125. _, inbound, gErr := inboundSvc.GetClientInboundByEmail(clientEmail)
  1126. if gErr != nil {
  1127. return false, gErr
  1128. }
  1129. if inbound == nil {
  1130. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1131. }
  1132. inboundIds = []int{inbound.Id}
  1133. }
  1134. needRestart := false
  1135. found := false
  1136. for _, ibId := range inboundIds {
  1137. inbound, gErr := inboundSvc.GetInbound(ibId)
  1138. if gErr != nil {
  1139. return needRestart, gErr
  1140. }
  1141. var settings map[string]any
  1142. if uErr := json.Unmarshal([]byte(inbound.Settings), &settings); uErr != nil {
  1143. return needRestart, uErr
  1144. }
  1145. clients, _ := settings["clients"].([]any)
  1146. // UpdateInboundClient expects a single-client payload, so keep only the
  1147. // matching entry in the scratch copy; it splices the result back into
  1148. // the inbound's full client list itself.
  1149. var newClients []any
  1150. for client_index := range clients {
  1151. c, ok := clients[client_index].(map[string]any)
  1152. if !ok {
  1153. continue
  1154. }
  1155. if c["email"] == clientEmail {
  1156. mutate(c)
  1157. c["updated_at"] = time.Now().Unix() * 1000
  1158. newClients = append(newClients, any(c))
  1159. }
  1160. }
  1161. if len(newClients) == 0 {
  1162. continue
  1163. }
  1164. found = true
  1165. settings["clients"] = newClients
  1166. modifiedSettings, mErr := json.MarshalIndent(settings, "", " ")
  1167. if mErr != nil {
  1168. return needRestart, mErr
  1169. }
  1170. inbound.Settings = string(modifiedSettings)
  1171. nr, uErr := s.UpdateInboundClient(inboundSvc, inbound, clientEmail)
  1172. if uErr != nil {
  1173. return needRestart, uErr
  1174. }
  1175. needRestart = needRestart || nr
  1176. }
  1177. if !found {
  1178. return needRestart, common.NewError("Client Not Found For Email:", clientEmail)
  1179. }
  1180. return needRestart, nil
  1181. }
  1182. func (s *ClientService) ResetClientIpLimitByEmail(inboundSvc *InboundService, clientEmail string, count int) (bool, error) {
  1183. return s.applyClientFieldByEmail(inboundSvc, clientEmail, func(c map[string]any) {
  1184. c["limitIp"] = count
  1185. })
  1186. }
  1187. func (s *ClientService) ResetClientExpiryTimeByEmail(inboundSvc *InboundService, clientEmail string, expiry_time int64) (bool, error) {
  1188. return s.applyClientFieldByEmail(inboundSvc, clientEmail, func(c map[string]any) {
  1189. c["expiryTime"] = expiry_time
  1190. })
  1191. }
  1192. func (s *ClientService) ResetClientTrafficLimitByEmail(inboundSvc *InboundService, clientEmail string, totalGB int) (bool, error) {
  1193. if totalGB < 0 {
  1194. return false, common.NewError("totalGB must be >= 0")
  1195. }
  1196. return s.applyClientFieldByEmail(inboundSvc, clientEmail, func(c map[string]any) {
  1197. c["totalGB"] = totalGB * 1024 * 1024 * 1024
  1198. })
  1199. }