1
0

client_inbound_apply.go 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277
  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 link delta 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. detached := make([]string, 0, len(targets))
  164. for _, t := range targets {
  165. if t.email != "" {
  166. detached = append(detached, t.email)
  167. }
  168. }
  169. if err := s.ApplyInboundClientDelta(tx, inboundId, nil, detached); err != nil {
  170. return err
  171. }
  172. if oldInbound.NodeID != nil {
  173. return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID)
  174. }
  175. return nil
  176. }); txErr != nil {
  177. return needRestart, txErr
  178. }
  179. // Resolve the node push plan once for the whole batch instead of per email.
  180. var nodeRt runtime.Runtime
  181. nodePush := false
  182. if oldInbound.NodeID != nil {
  183. rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound)
  184. if perr != nil {
  185. return needRestart, perr
  186. }
  187. nodeRt, nodePush = rt, push
  188. // Large batches collapse into one reconcile push rather than M deletes.
  189. if nodePush && len(targets) > nodeBulkPushThreshold {
  190. nodePush = false
  191. }
  192. }
  193. // Apply runtime deletes after commit — outside the serialized writer so a
  194. // slow node call can't stall traffic accounting.
  195. nodePushFailed := false
  196. for _, t := range targets {
  197. if len(t.email) == 0 {
  198. continue
  199. }
  200. if oldInbound.NodeID == nil {
  201. if t.needApiDel && t.notDepleted {
  202. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  203. if rterr != nil {
  204. needRestart = true
  205. } else if err1 := rt.RemoveUser(context.Background(), oldInbound, t.email); err1 != nil {
  206. if !strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", t.email)) {
  207. needRestart = true
  208. }
  209. }
  210. }
  211. } else if nodePush {
  212. if err1 := nodeRt.DeleteUser(context.Background(), oldInbound, t.email); err1 != nil {
  213. logger.Warning("Error in deleting client on", nodeRt.Name(), ":", err1)
  214. nodePushFailed = true
  215. }
  216. }
  217. }
  218. if nodePush && !nodePushFailed {
  219. advancePushedInbound(nodeRt, prevSettings, oldInbound)
  220. }
  221. return needRestart, nil
  222. }
  223. func (s *ClientService) checkEmailsExistForClients(inboundSvc *InboundService, clients []model.Client) (string, error) {
  224. emailSubIDs, err := inboundSvc.emailSubIDsForClients(clients)
  225. if err != nil {
  226. return "", err
  227. }
  228. seen := make(map[string]string, len(clients))
  229. for _, client := range clients {
  230. if client.Email == "" {
  231. continue
  232. }
  233. key := strings.ToLower(client.Email)
  234. if prev, ok := seen[key]; ok {
  235. if prev != client.SubID || client.SubID == "" {
  236. return client.Email, nil
  237. }
  238. continue
  239. }
  240. seen[key] = client.SubID
  241. if existingSub, ok := emailSubIDs[key]; ok {
  242. if client.SubID == "" || existingSub == "" || existingSub != client.SubID {
  243. return client.Email, nil
  244. }
  245. }
  246. }
  247. return "", nil
  248. }
  249. func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model.Inbound) (bool, error) {
  250. defer lockInbound(data.Id).Unlock()
  251. clients, err := inboundSvc.GetClients(data)
  252. if err != nil {
  253. return false, err
  254. }
  255. var settings map[string]any
  256. err = json.Unmarshal([]byte(data.Settings), &settings)
  257. if err != nil {
  258. return false, err
  259. }
  260. interfaceClients := settings["clients"].([]any)
  261. nowTs := time.Now().Unix() * 1000
  262. for i := range interfaceClients {
  263. if cm, ok := interfaceClients[i].(map[string]any); ok {
  264. if _, ok2 := cm["created_at"]; !ok2 {
  265. cm["created_at"] = nowTs
  266. }
  267. cm["updated_at"] = nowTs
  268. existingSub, _ := cm["subId"].(string)
  269. if strings.TrimSpace(existingSub) == "" {
  270. cm["subId"] = random.NumLower(16)
  271. }
  272. interfaceClients[i] = cm
  273. }
  274. }
  275. existEmail, err := s.checkEmailsExistForClients(inboundSvc, clients)
  276. if err != nil {
  277. return false, err
  278. }
  279. if existEmail != "" {
  280. return false, common.NewError("Duplicate email:", existEmail)
  281. }
  282. oldInbound, err := inboundSvc.GetInbound(data.Id)
  283. if err != nil {
  284. return false, err
  285. }
  286. existingClients, err := inboundSvc.GetClients(oldInbound)
  287. if err != nil {
  288. return false, err
  289. }
  290. // A client already on this inbound is skipped instead of appended again:
  291. // checkEmailsExistForClients exempts a matching subId so one identity can
  292. // live on several inbounds, which let retried or raced adds duplicate the
  293. // same email inside a single settings array (#5770). clients and
  294. // interfaceClients are parsed from the same data.Settings array, so they
  295. // stay index-aligned while filtering.
  296. if len(existingClients) > 0 && len(clients) > 0 {
  297. existingEmails := make(map[string]struct{}, len(existingClients))
  298. for _, c := range existingClients {
  299. if c.Email != "" {
  300. existingEmails[strings.ToLower(c.Email)] = struct{}{}
  301. }
  302. }
  303. keptClients := make([]model.Client, 0, len(clients))
  304. keptWire := make([]any, 0, len(interfaceClients))
  305. for i, c := range clients {
  306. if c.Email != "" {
  307. if _, dup := existingEmails[strings.ToLower(c.Email)]; dup {
  308. continue
  309. }
  310. }
  311. keptClients = append(keptClients, c)
  312. if i < len(interfaceClients) {
  313. keptWire = append(keptWire, interfaceClients[i])
  314. }
  315. }
  316. if len(keptClients) == 0 {
  317. return false, nil
  318. }
  319. clients = keptClients
  320. interfaceClients = keptWire
  321. }
  322. if oldInbound.Protocol == model.WireGuard {
  323. if dErr := defaultWireguardClients(existingClients, clients, interfaceClients); dErr != nil {
  324. return false, dErr
  325. }
  326. }
  327. for _, client := range clients {
  328. if strings.TrimSpace(client.Email) == "" {
  329. return false, common.NewError("client email is required")
  330. }
  331. switch oldInbound.Protocol {
  332. case "trojan":
  333. if client.Password == "" {
  334. return false, common.NewError("empty client ID")
  335. }
  336. case "shadowsocks":
  337. if client.Email == "" {
  338. return false, common.NewError("empty client ID")
  339. }
  340. case "hysteria":
  341. if client.Auth == "" {
  342. return false, common.NewError("empty client ID")
  343. }
  344. case "wireguard":
  345. if client.PublicKey == "" {
  346. return false, common.NewError("wireguard client requires a key")
  347. }
  348. case "mtproto":
  349. if client.Secret == "" {
  350. return false, common.NewError("mtproto client requires a secret")
  351. }
  352. if client.AdTag != "" && !model.ValidMtprotoAdTag(client.AdTag) {
  353. return false, common.NewError("mtproto client ad tag must be 32 hex characters")
  354. }
  355. default:
  356. if client.ID == "" {
  357. return false, common.NewError("empty client ID")
  358. }
  359. }
  360. }
  361. var oldSettings map[string]any
  362. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  363. if err != nil {
  364. return false, err
  365. }
  366. if oldInbound.Protocol == model.Shadowsocks {
  367. applyShadowsocksClientMethod(interfaceClients, oldSettings)
  368. }
  369. oldClients, _ := oldSettings["clients"].([]any)
  370. oldClients = compactOrphans(database.GetDB(), oldClients)
  371. oldClients = append(oldClients, interfaceClients...)
  372. oldSettings["clients"] = oldClients
  373. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  374. if err != nil {
  375. return false, err
  376. }
  377. prevSettings := oldInbound.Settings
  378. oldInbound.Settings = string(newSettings)
  379. // From the stamped wire entries, not from clients: created_at / updated_at /
  380. // subId are written onto interfaceClients above, after clients was parsed.
  381. addedClients, err := settingsEntriesToClients(interfaceClients)
  382. if err != nil {
  383. return false, err
  384. }
  385. needRestart := false
  386. rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound)
  387. if perr != nil {
  388. return false, perr
  389. }
  390. // Persist client stats + inbound atomically, serialized against the traffic
  391. // poll to avoid the cross-transaction lock-order deadlock (runSerializedTx).
  392. if txErr := runSerializedTx(func(tx *gorm.DB) error {
  393. for i := range clients {
  394. if len(clients[i].Email) == 0 {
  395. continue
  396. }
  397. if e := inboundSvc.AddClientStat(tx, data.Id, &clients[i]); e != nil {
  398. return e
  399. }
  400. }
  401. if e := tx.Save(oldInbound).Error; e != nil {
  402. return e
  403. }
  404. if err := s.ApplyInboundClientDelta(tx, oldInbound.Id, addedClients, nil); err != nil {
  405. return err
  406. }
  407. if oldInbound.NodeID != nil {
  408. return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID)
  409. }
  410. return nil
  411. }); txErr != nil {
  412. return false, txErr
  413. }
  414. // Apply to the running runtime after commit — outside the serialized writer
  415. // so a slow node call can't stall traffic accounting.
  416. if oldInbound.NodeID == nil {
  417. if !push {
  418. needRestart = true
  419. } else if oldInbound.Protocol == model.MTProto {
  420. inboundSvc.applyLocalMtproto(oldInbound.Id)
  421. } else {
  422. for _, client := range clients {
  423. if len(client.Email) == 0 {
  424. needRestart = true
  425. continue
  426. }
  427. if !client.Enable {
  428. continue
  429. }
  430. cipher := ""
  431. if oldInbound.Protocol == "shadowsocks" {
  432. cipher, _ = oldSettings["method"].(string)
  433. }
  434. err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
  435. "email": client.Email,
  436. "id": client.ID,
  437. "auth": client.Auth,
  438. "security": client.Security,
  439. "flow": client.Flow,
  440. "password": client.Password,
  441. "cipher": cipher,
  442. "publicKey": client.PublicKey,
  443. "allowedIPs": client.AllowedIPs,
  444. "preSharedKey": client.PreSharedKey,
  445. "keepAlive": keepAliveStr(client.KeepAlive),
  446. })
  447. if err1 == nil {
  448. logger.Debug("Client added on", rt.Name(), ":", client.Email)
  449. } else {
  450. logger.Debug("Error in adding client on", rt.Name(), ":", err1)
  451. needRestart = true
  452. }
  453. }
  454. }
  455. } else {
  456. // Large batches would be M sequential per-client RPCs; the inbound's saved
  457. // settings already hold the final set, so mark dirty and let one reconcile
  458. // push converge the node instead.
  459. if push && len(clients) > nodeBulkPushThreshold {
  460. push = false
  461. }
  462. for _, client := range clients {
  463. if push {
  464. if err1 := rt.AddClient(context.Background(), oldInbound, client); err1 != nil {
  465. logger.Warning("Error in adding client on", rt.Name(), ":", err1)
  466. push = false
  467. }
  468. }
  469. }
  470. if push {
  471. advancePushedInbound(rt, prevSettings, oldInbound)
  472. }
  473. }
  474. return needRestart, nil
  475. }
  476. func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *model.Inbound, oldEmail string) (bool, error) {
  477. defer lockInbound(data.Id).Unlock()
  478. clients, err := inboundSvc.GetClients(data)
  479. if err != nil {
  480. return false, err
  481. }
  482. var settings map[string]any
  483. err = json.Unmarshal([]byte(data.Settings), &settings)
  484. if err != nil {
  485. return false, err
  486. }
  487. interfaceClients := settings["clients"].([]any)
  488. oldInbound, err := inboundSvc.GetInbound(data.Id)
  489. if err != nil {
  490. return false, err
  491. }
  492. oldClients, err := inboundSvc.GetClients(oldInbound)
  493. if err != nil {
  494. return false, err
  495. }
  496. newClientId := ""
  497. switch oldInbound.Protocol {
  498. case "trojan":
  499. newClientId = clients[0].Password
  500. case "shadowsocks":
  501. newClientId = clients[0].Email
  502. case "hysteria":
  503. newClientId = clients[0].Auth
  504. case "wireguard":
  505. newClientId = clients[0].Email
  506. case "mtproto":
  507. newClientId = clients[0].Email
  508. default:
  509. newClientId = clients[0].ID
  510. }
  511. // Locate the client to replace by email — the client's stable identity.
  512. // Credentials (uuid/password/auth) can drift from the inbound JSON, so they
  513. // are never used for matching.
  514. clientIndex := -1
  515. for index, oldClient := range oldClients {
  516. if strings.EqualFold(oldClient.Email, oldEmail) {
  517. oldEmail = oldClient.Email
  518. clientIndex = index
  519. break
  520. }
  521. }
  522. if newClientId == "" || clientIndex == -1 {
  523. return false, common.NewError("empty client ID")
  524. }
  525. if strings.TrimSpace(clients[0].Email) == "" {
  526. return false, common.NewError("client email is required")
  527. }
  528. if oldInbound.Protocol == model.MTProto && clients[0].AdTag != "" && !model.ValidMtprotoAdTag(clients[0].AdTag) {
  529. return false, common.NewError("mtproto client ad tag must be 32 hex characters")
  530. }
  531. if clients[0].Email != oldEmail {
  532. existEmail, err := s.checkEmailsExistForClients(inboundSvc, clients)
  533. if err != nil {
  534. return false, err
  535. }
  536. if existEmail != "" {
  537. return false, common.NewError("Duplicate email:", existEmail)
  538. }
  539. }
  540. // WireGuard keys are never rotated by an edit: when the incoming payload omits
  541. // them (a metadata-only change), carry the stored credentials forward so the
  542. // settings JSON and the running peer keep the client's identity.
  543. if oldInbound.Protocol == model.WireGuard && clientIndex >= 0 && clientIndex < len(oldClients) {
  544. old := oldClients[clientIndex]
  545. if clients[0].PrivateKey == "" {
  546. clients[0].PrivateKey = old.PrivateKey
  547. }
  548. if clients[0].PublicKey == "" {
  549. clients[0].PublicKey = old.PublicKey
  550. }
  551. if len(clients[0].AllowedIPs) == 0 {
  552. clients[0].AllowedIPs = old.AllowedIPs
  553. } else {
  554. normalized, nErr := normalizeWireguardAllowedIPs(clients[0].AllowedIPs)
  555. if nErr != nil {
  556. return false, nErr
  557. }
  558. if len(normalized) == 0 {
  559. clients[0].AllowedIPs = old.AllowedIPs
  560. } else {
  561. peers := make([]string, 0, len(oldClients))
  562. for i := range oldClients {
  563. if i == clientIndex {
  564. continue
  565. }
  566. peers = append(peers, oldClients[i].AllowedIPs...)
  567. }
  568. if hit := wireguardAllowedIPsCollision(normalized, peers); hit != "" {
  569. return false, common.NewError("wireguard: allowedIPs entry already used by another client:", hit)
  570. }
  571. clients[0].AllowedIPs = normalized
  572. }
  573. }
  574. if clients[0].PreSharedKey == "" {
  575. clients[0].PreSharedKey = old.PreSharedKey
  576. }
  577. if clients[0].KeepAlive == 0 {
  578. clients[0].KeepAlive = old.KeepAlive
  579. }
  580. }
  581. var oldSettings map[string]any
  582. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  583. if err != nil {
  584. return false, err
  585. }
  586. settingsClients, _ := oldSettings["clients"].([]any)
  587. var preservedCreated any
  588. var preservedSubID string
  589. var oldClientMap map[string]any
  590. if clientIndex >= 0 && clientIndex < len(settingsClients) {
  591. if oldMap, ok := settingsClients[clientIndex].(map[string]any); ok {
  592. oldClientMap = oldMap
  593. if v, ok2 := oldMap["created_at"]; ok2 {
  594. preservedCreated = v
  595. }
  596. preservedSubID, _ = oldMap["subId"].(string)
  597. }
  598. }
  599. if oldInbound.Protocol == model.Shadowsocks {
  600. applyShadowsocksClientMethod(interfaceClients, oldSettings)
  601. }
  602. if len(interfaceClients) > 0 {
  603. if newMap, ok := interfaceClients[0].(map[string]any); ok {
  604. if preservedCreated == nil {
  605. preservedCreated = time.Now().Unix() * 1000
  606. }
  607. newMap["created_at"] = preservedCreated
  608. newSub, _ := newMap["subId"].(string)
  609. if strings.TrimSpace(newSub) == "" {
  610. if strings.TrimSpace(preservedSubID) != "" {
  611. newMap["subId"] = preservedSubID
  612. } else {
  613. newMap["subId"] = random.NumLower(16)
  614. }
  615. }
  616. if v, ok2 := newMap["subId"].(string); ok2 {
  617. clients[0].SubID = v
  618. }
  619. if oldInbound.Protocol == model.WireGuard {
  620. newMap["privateKey"] = clients[0].PrivateKey
  621. newMap["publicKey"] = clients[0].PublicKey
  622. newMap["allowedIPs"] = clients[0].AllowedIPs
  623. if clients[0].PreSharedKey != "" {
  624. newMap["preSharedKey"] = clients[0].PreSharedKey
  625. }
  626. if clients[0].KeepAlive > 0 {
  627. newMap["keepAlive"] = clients[0].KeepAlive
  628. }
  629. }
  630. if oldClientMap != nil && sameClientConfigExceptUpdatedAt(oldClientMap, newMap) {
  631. if v, ok2 := oldClientMap["updated_at"]; ok2 {
  632. newMap["updated_at"] = v
  633. } else {
  634. delete(newMap, "updated_at")
  635. }
  636. } else {
  637. newMap["updated_at"] = time.Now().Unix() * 1000
  638. }
  639. interfaceClients[0] = newMap
  640. }
  641. }
  642. settingsClients[clientIndex] = interfaceClients[0]
  643. oldSettings["clients"] = settingsClients
  644. if oldInbound.Protocol == model.VLESS {
  645. hasVisionFlow := false
  646. for _, c := range settingsClients {
  647. cm, ok := c.(map[string]any)
  648. if !ok {
  649. continue
  650. }
  651. if flow, _ := cm["flow"].(string); flow == "xtls-rprx-vision" {
  652. hasVisionFlow = true
  653. break
  654. }
  655. }
  656. if !hasVisionFlow {
  657. delete(oldSettings, "testseed")
  658. }
  659. }
  660. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  661. if err != nil {
  662. return false, err
  663. }
  664. if string(newSettings) == oldInbound.Settings {
  665. return false, nil
  666. }
  667. prevSettings := oldInbound.Settings
  668. oldInbound.Settings = string(newSettings)
  669. // From the stamped wire entry, not from clients[0]: created_at, the
  670. // preserved subId and the WireGuard carry-forward land on interfaceClients.
  671. changedClients, err := settingsEntriesToClients(interfaceClients[:1])
  672. if err != nil {
  673. return false, err
  674. }
  675. var detachEmails []string
  676. if len(oldEmail) > 0 && oldEmail != clients[0].Email {
  677. detachEmails = []string{oldEmail}
  678. }
  679. needRestart := false
  680. // Resolve the push plan before the DB write so a node-state lookup failure
  681. // still aborts the whole update without committing anything (it used to roll
  682. // the transaction back). nodePushPlan only reads, so order doesn't matter.
  683. var rt runtime.Runtime
  684. var push bool
  685. if len(oldEmail) > 0 {
  686. var perr error
  687. rt, push, _, perr = inboundSvc.nodePushPlan(oldInbound)
  688. if perr != nil {
  689. return false, perr
  690. }
  691. }
  692. // Persist client stats + inbound atomically, serialized against the traffic
  693. // poll to avoid the cross-transaction lock-order deadlock (runSerializedTx).
  694. if txErr := runSerializedTx(func(tx *gorm.DB) error {
  695. if len(clients[0].Email) > 0 {
  696. if len(oldEmail) > 0 {
  697. emailUnchanged := strings.EqualFold(oldEmail, clients[0].Email)
  698. targetExists := int64(0)
  699. if !emailUnchanged {
  700. if e := tx.Model(xray.ClientTraffic{}).Where("email = ?", clients[0].Email).Count(&targetExists).Error; e != nil {
  701. return e
  702. }
  703. }
  704. if emailUnchanged || targetExists == 0 {
  705. if e := inboundSvc.UpdateClientStat(tx, oldEmail, &clients[0]); e != nil {
  706. return e
  707. }
  708. if e := inboundSvc.UpdateClientIPs(tx, oldEmail, clients[0].Email); e != nil {
  709. return e
  710. }
  711. } else {
  712. stillUsed, sErr := inboundSvc.emailUsedByOtherInbounds(oldEmail, data.Id)
  713. if sErr != nil {
  714. return sErr
  715. }
  716. if !stillUsed {
  717. if e := inboundSvc.DelClientStat(tx, oldEmail); e != nil {
  718. return e
  719. }
  720. if e := inboundSvc.DelClientIPs(tx, oldEmail); e != nil {
  721. return e
  722. }
  723. }
  724. if e := inboundSvc.UpdateClientStat(tx, clients[0].Email, &clients[0]); e != nil {
  725. return e
  726. }
  727. }
  728. } else {
  729. if e := inboundSvc.AddClientStat(tx, data.Id, &clients[0]); e != nil {
  730. return e
  731. }
  732. }
  733. } else {
  734. stillUsed, sErr := inboundSvc.emailUsedByOtherInbounds(oldEmail, data.Id)
  735. if sErr != nil {
  736. return sErr
  737. }
  738. if !stillUsed {
  739. if e := inboundSvc.DelClientStat(tx, oldEmail); e != nil {
  740. return e
  741. }
  742. if e := inboundSvc.DelClientIPs(tx, oldEmail); e != nil {
  743. return e
  744. }
  745. }
  746. }
  747. if e := tx.Save(oldInbound).Error; e != nil {
  748. return e
  749. }
  750. // Rename the client record in the same transaction as the settings JSON
  751. // so no concurrent SyncInbound can see one renamed without the other.
  752. // Byte-level compare (not EqualFold): case-only edits must rename too,
  753. // otherwise SyncInbound's case-sensitive lookup creates a duplicate row.
  754. if len(oldEmail) > 0 && oldEmail != clients[0].Email {
  755. var renameTaken int64
  756. if e := tx.Model(&model.ClientRecord{}).Where("email = ?", clients[0].Email).Count(&renameTaken).Error; e != nil {
  757. return e
  758. }
  759. if renameTaken == 0 {
  760. if e := tx.Model(&model.ClientRecord{}).Where("email = ?", oldEmail).Update("email", clients[0].Email).Error; e != nil {
  761. return e
  762. }
  763. }
  764. }
  765. // detachEmails covers the rename the guard above refused: the old record
  766. // keeps this inbound's link otherwise, which the full sync used to drop.
  767. if err := s.ApplyInboundClientDelta(tx, oldInbound.Id, changedClients, detachEmails); err != nil {
  768. return err
  769. }
  770. if oldInbound.NodeID != nil {
  771. return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID)
  772. }
  773. return nil
  774. }); txErr != nil {
  775. return false, txErr
  776. }
  777. // Apply to the running runtime after the DB is committed — outside the
  778. // serialized writer so a slow node call can't stall traffic accounting.
  779. if len(oldEmail) > 0 {
  780. if oldInbound.NodeID == nil {
  781. if !push {
  782. needRestart = true
  783. } else if oldInbound.Protocol == model.MTProto {
  784. inboundSvc.applyLocalMtproto(oldInbound.Id)
  785. } else {
  786. if oldClients[clientIndex].Enable {
  787. err1 := rt.RemoveUser(context.Background(), oldInbound, oldEmail)
  788. if err1 == nil {
  789. logger.Debug("Old client deleted on", rt.Name(), ":", oldEmail)
  790. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", oldEmail)) {
  791. logger.Debug("User is already deleted. Nothing to do more...")
  792. } else {
  793. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  794. needRestart = true
  795. }
  796. }
  797. if clients[0].Enable {
  798. cipher := ""
  799. if oldInbound.Protocol == "shadowsocks" {
  800. cipher, _ = oldSettings["method"].(string)
  801. }
  802. err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
  803. "email": clients[0].Email,
  804. "id": clients[0].ID,
  805. "security": clients[0].Security,
  806. "flow": clients[0].Flow,
  807. "auth": clients[0].Auth,
  808. "password": clients[0].Password,
  809. "cipher": cipher,
  810. "publicKey": clients[0].PublicKey,
  811. "allowedIPs": clients[0].AllowedIPs,
  812. "preSharedKey": clients[0].PreSharedKey,
  813. "keepAlive": keepAliveStr(clients[0].KeepAlive),
  814. })
  815. if err1 == nil {
  816. logger.Debug("Client edited on", rt.Name(), ":", clients[0].Email)
  817. } else {
  818. logger.Debug("Error in adding client on", rt.Name(), ":", err1)
  819. needRestart = true
  820. }
  821. }
  822. }
  823. } else if push {
  824. if err1 := rt.UpdateUser(context.Background(), oldInbound, oldEmail, clients[0]); err1 != nil {
  825. logger.Warning("Error in updating client on", rt.Name(), ":", err1)
  826. } else {
  827. advancePushedInbound(rt, prevSettings, oldInbound)
  828. }
  829. }
  830. } else {
  831. logger.Debug("Client old email not found")
  832. needRestart = true
  833. }
  834. return needRestart, nil
  835. }
  836. func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inboundId int, email string, keepTraffic bool, fullDelete bool) (bool, error) {
  837. defer lockInbound(inboundId).Unlock()
  838. oldInbound, err := inboundSvc.GetInbound(inboundId)
  839. if err != nil {
  840. logger.Error("Load Old Data Error")
  841. return false, err
  842. }
  843. var settings map[string]any
  844. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  845. return false, err
  846. }
  847. interfaceClients, ok := settings["clients"].([]any)
  848. if !ok {
  849. return false, common.NewError("invalid clients format in inbound settings")
  850. }
  851. var newClients []any
  852. needApiDel := false
  853. found := false
  854. for _, client := range interfaceClients {
  855. c, ok := client.(map[string]any)
  856. if !ok {
  857. continue
  858. }
  859. if cEmail, ok := c["email"].(string); ok && cEmail == email {
  860. found = true
  861. needApiDel, _ = c["enable"].(bool)
  862. } else {
  863. newClients = append(newClients, client)
  864. }
  865. }
  866. if !found {
  867. return false, fmt.Errorf("%w for email: %s", ErrClientNotInInbound, email)
  868. }
  869. db := database.GetDB()
  870. newClients = compactOrphans(db, newClients)
  871. if newClients == nil {
  872. newClients = []any{}
  873. }
  874. settings["clients"] = newClients
  875. newSettings, err := json.MarshalIndent(settings, "", " ")
  876. if err != nil {
  877. return false, err
  878. }
  879. prevSettings := oldInbound.Settings
  880. oldInbound.Settings = string(newSettings)
  881. emailShared, err := inboundSvc.emailUsedByOtherInbounds(email, inboundId)
  882. if err != nil {
  883. return false, err
  884. }
  885. needRestart := false
  886. // Decide what to delete and the push plan before the serialized DB write —
  887. // these are reads, and nodePushPlan failing should abort before committing.
  888. delStat := false
  889. if len(email) > 0 && !emailShared && !keepTraffic {
  890. traffic, tErr := inboundSvc.GetClientTrafficByEmail(email)
  891. if tErr != nil {
  892. return false, tErr
  893. }
  894. delStat = traffic != nil
  895. }
  896. // The runtime user is scoped to this inbound's tag + email, so the push plan
  897. // is resolved independently of emailShared — a sibling inbound still carrying
  898. // the email must not suppress removing the user from this inbound's Xray.
  899. var rt runtime.Runtime
  900. var push bool
  901. if len(email) > 0 && (oldInbound.NodeID != nil || needApiDel) {
  902. r, p, _, perr := inboundSvc.nodePushPlan(oldInbound)
  903. if perr != nil {
  904. return false, perr
  905. }
  906. rt, push = r, p
  907. }
  908. // Persist the deletion atomically, serialized against the traffic poll to
  909. // avoid the cross-transaction lock-order deadlock (runSerializedTx).
  910. if txErr := runSerializedTx(func(tx *gorm.DB) error {
  911. if !emailShared && !keepTraffic {
  912. if e := inboundSvc.DelClientIPs(tx, email); e != nil {
  913. logger.Error("Error in delete client IPs")
  914. return e
  915. }
  916. }
  917. if delStat {
  918. if e := inboundSvc.DelClientStat(tx, email); e != nil {
  919. logger.Error("Delete stats Data Error")
  920. return e
  921. }
  922. }
  923. if e := tx.Save(oldInbound).Error; e != nil {
  924. return e
  925. }
  926. if err := s.ApplyInboundClientDelta(tx, inboundId, nil, []string{email}); 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. current, err := s.CheckIsEnabledByEmail(inboundSvc, clientEmail)
  1055. if err != nil {
  1056. return false, false, err
  1057. }
  1058. target := !current
  1059. needRestart, err := s.applyClientFieldByEmail(inboundSvc, clientEmail, func(c map[string]any) {
  1060. c["enable"] = target
  1061. })
  1062. if err != nil {
  1063. return false, needRestart, err
  1064. }
  1065. return target, needRestart, nil
  1066. }
  1067. func (s *ClientService) SetClientEnableByEmail(inboundSvc *InboundService, clientEmail string, enable bool) (bool, bool, error) {
  1068. current, err := s.CheckIsEnabledByEmail(inboundSvc, clientEmail)
  1069. if err != nil {
  1070. return false, false, err
  1071. }
  1072. if current == enable {
  1073. return false, false, nil
  1074. }
  1075. needRestart, err := s.applyClientFieldByEmail(inboundSvc, clientEmail, func(c map[string]any) {
  1076. c["enable"] = enable
  1077. })
  1078. if err != nil {
  1079. return false, needRestart, err
  1080. }
  1081. return true, needRestart, nil
  1082. }
  1083. // applyClientFieldByEmail loads the inbound currently hosting clientEmail,
  1084. // confirms the client exists, applies mutate to the matching client (plus a
  1085. // refreshed updated_at), and hands a single-client update payload to
  1086. // UpdateInboundClient. The rebuilt clients array intentionally contains only
  1087. // the matched client — that is the input contract UpdateInboundClient expects
  1088. // (clients[0] is the new data; clientEmail locates the row to replace). It
  1089. // backs the single-field by-email setters below.
  1090. // applyClientFieldByEmail mutates a client field on every inbound the email is
  1091. // attached to. A multi-inbound client is one logical identity: patching only
  1092. // the first inbound's JSON would leave the siblings stale, and the next
  1093. // SyncInbound over a stale sibling would revert the edit in the normalized
  1094. // records (#5039).
  1095. func (s *ClientService) applyClientFieldByEmail(inboundSvc *InboundService, clientEmail string, mutate func(c map[string]any)) (bool, error) {
  1096. inboundIds, err := s.GetInboundIdsForEmail(database.GetDB(), clientEmail)
  1097. if err != nil {
  1098. return false, err
  1099. }
  1100. if len(inboundIds) == 0 {
  1101. // Legacy fallback for clients that only live in the inbound JSON and
  1102. // were never normalized into client_inbounds.
  1103. _, inbound, gErr := inboundSvc.GetClientInboundByEmail(clientEmail)
  1104. if gErr != nil {
  1105. return false, gErr
  1106. }
  1107. if inbound == nil {
  1108. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1109. }
  1110. inboundIds = []int{inbound.Id}
  1111. }
  1112. needRestart := false
  1113. found := false
  1114. for _, ibId := range inboundIds {
  1115. inbound, gErr := inboundSvc.GetInbound(ibId)
  1116. if gErr != nil {
  1117. return needRestart, gErr
  1118. }
  1119. var settings map[string]any
  1120. if uErr := json.Unmarshal([]byte(inbound.Settings), &settings); uErr != nil {
  1121. return needRestart, uErr
  1122. }
  1123. clients, _ := settings["clients"].([]any)
  1124. // UpdateInboundClient expects a single-client payload, so keep only the
  1125. // matching entry in the scratch copy; it splices the result back into
  1126. // the inbound's full client list itself.
  1127. var newClients []any
  1128. for client_index := range clients {
  1129. c, ok := clients[client_index].(map[string]any)
  1130. if !ok {
  1131. continue
  1132. }
  1133. if c["email"] == clientEmail {
  1134. mutate(c)
  1135. c["updated_at"] = time.Now().Unix() * 1000
  1136. newClients = append(newClients, any(c))
  1137. }
  1138. }
  1139. if len(newClients) == 0 {
  1140. continue
  1141. }
  1142. found = true
  1143. settings["clients"] = newClients
  1144. modifiedSettings, mErr := json.MarshalIndent(settings, "", " ")
  1145. if mErr != nil {
  1146. return needRestart, mErr
  1147. }
  1148. inbound.Settings = string(modifiedSettings)
  1149. nr, uErr := s.UpdateInboundClient(inboundSvc, inbound, clientEmail)
  1150. if uErr != nil {
  1151. return needRestart, uErr
  1152. }
  1153. needRestart = needRestart || nr
  1154. }
  1155. if !found {
  1156. return needRestart, common.NewError("Client Not Found For Email:", clientEmail)
  1157. }
  1158. return needRestart, nil
  1159. }
  1160. func (s *ClientService) ResetClientIpLimitByEmail(inboundSvc *InboundService, clientEmail string, count int) (bool, error) {
  1161. return s.applyClientFieldByEmail(inboundSvc, clientEmail, func(c map[string]any) {
  1162. c["limitIp"] = count
  1163. })
  1164. }
  1165. func (s *ClientService) ResetClientExpiryTimeByEmail(inboundSvc *InboundService, clientEmail string, expiry_time int64) (bool, error) {
  1166. return s.applyClientFieldByEmail(inboundSvc, clientEmail, func(c map[string]any) {
  1167. c["expiryTime"] = expiry_time
  1168. })
  1169. }
  1170. func (s *ClientService) ResetClientTrafficLimitByEmail(inboundSvc *InboundService, clientEmail string, totalGB int) (bool, error) {
  1171. if totalGB < 0 {
  1172. return false, common.NewError("totalGB must be >= 0")
  1173. }
  1174. return s.applyClientFieldByEmail(inboundSvc, clientEmail, func(c map[string]any) {
  1175. c["totalGB"] = totalGB * 1024 * 1024 * 1024
  1176. })
  1177. }