client_inbound_apply.go 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414
  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. // otherTunnelAllowedIPs maps every AllowedIPs entry claimed on another
  224. // WireGuard/AmneziaWG inbound to a description of which one holds it: the
  225. // per-inbound defaulters only check their own client list, so two inbounds
  226. // sharing a subnet could otherwise hand out the same address. Disabled
  227. // siblings count too, keeping their addresses reserved for a later re-enable.
  228. //
  229. // selfEmails skips this identity's own entries. Email is globally unique, so a
  230. // match there is never a real collision -- and Attach deliberately reuses one
  231. // address across every inbound it attaches the identity to.
  232. func (s *ClientService) otherTunnelAllowedIPs(db *gorm.DB, inboundSvc *InboundService, excludeID int, selfEmails map[string]struct{}) (map[string]string, error) {
  233. var inbounds []*model.Inbound
  234. err := db.Model(model.Inbound{}).
  235. Where("protocol IN ? AND id != ?", []model.Protocol{model.WireGuard, model.AmneziaWG}, excludeID).
  236. Find(&inbounds).Error
  237. if err != nil {
  238. return nil, err
  239. }
  240. used := make(map[string]string)
  241. for _, ib := range inbounds {
  242. clients, cErr := inboundSvc.GetClients(ib)
  243. if cErr != nil {
  244. continue
  245. }
  246. name := ib.Remark
  247. if name == "" {
  248. name = ib.Tag
  249. }
  250. label := fmt.Sprintf("inbound '%s' (#%d)", name, ib.Id)
  251. for _, c := range clients {
  252. if _, self := selfEmails[strings.ToLower(c.Email)]; self {
  253. continue
  254. }
  255. for _, addr := range c.AllowedIPs {
  256. used[addr] = label
  257. }
  258. }
  259. }
  260. return used, nil
  261. }
  262. func (s *ClientService) checkEmailsExistForClients(inboundSvc *InboundService, clients []model.Client) (string, error) {
  263. emailSubIDs, err := inboundSvc.emailSubIDsForClients(clients)
  264. if err != nil {
  265. return "", err
  266. }
  267. seen := make(map[string]string, len(clients))
  268. for _, client := range clients {
  269. if client.Email == "" {
  270. continue
  271. }
  272. key := strings.ToLower(client.Email)
  273. if prev, ok := seen[key]; ok {
  274. if prev != client.SubID || client.SubID == "" {
  275. return client.Email, nil
  276. }
  277. continue
  278. }
  279. seen[key] = client.SubID
  280. if existingSub, ok := emailSubIDs[key]; ok {
  281. if client.SubID == "" || existingSub == "" || existingSub != client.SubID {
  282. return client.Email, nil
  283. }
  284. }
  285. }
  286. return "", nil
  287. }
  288. func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model.Inbound) (bool, error) {
  289. defer lockInbound(data.Id).Unlock()
  290. clients, err := inboundSvc.GetClients(data)
  291. if err != nil {
  292. return false, err
  293. }
  294. var settings map[string]any
  295. err = json.Unmarshal([]byte(data.Settings), &settings)
  296. if err != nil {
  297. return false, err
  298. }
  299. interfaceClients := settings["clients"].([]any)
  300. nowTs := time.Now().Unix() * 1000
  301. for i := range interfaceClients {
  302. if cm, ok := interfaceClients[i].(map[string]any); ok {
  303. if _, ok2 := cm["created_at"]; !ok2 {
  304. cm["created_at"] = nowTs
  305. }
  306. cm["updated_at"] = nowTs
  307. existingSub, _ := cm["subId"].(string)
  308. if strings.TrimSpace(existingSub) == "" {
  309. cm["subId"] = random.NumLower(16)
  310. }
  311. interfaceClients[i] = cm
  312. }
  313. }
  314. existEmail, err := s.checkEmailsExistForClients(inboundSvc, clients)
  315. if err != nil {
  316. return false, err
  317. }
  318. if existEmail != "" {
  319. return false, common.NewError("Duplicate email:", existEmail)
  320. }
  321. oldInbound, err := inboundSvc.GetInbound(data.Id)
  322. if err != nil {
  323. return false, err
  324. }
  325. existingClients, err := inboundSvc.GetClients(oldInbound)
  326. if err != nil {
  327. return false, err
  328. }
  329. // A client already on this inbound is skipped instead of appended again:
  330. // checkEmailsExistForClients exempts a matching subId so one identity can
  331. // live on several inbounds, which let retried or raced adds duplicate the
  332. // same email inside a single settings array (#5770). clients and
  333. // interfaceClients are parsed from the same data.Settings array, so they
  334. // stay index-aligned while filtering.
  335. if len(existingClients) > 0 && len(clients) > 0 {
  336. existingEmails := make(map[string]struct{}, len(existingClients))
  337. for _, c := range existingClients {
  338. if c.Email != "" {
  339. existingEmails[strings.ToLower(c.Email)] = struct{}{}
  340. }
  341. }
  342. keptClients := make([]model.Client, 0, len(clients))
  343. keptWire := make([]any, 0, len(interfaceClients))
  344. for i, c := range clients {
  345. if c.Email != "" {
  346. if _, dup := existingEmails[strings.ToLower(c.Email)]; dup {
  347. continue
  348. }
  349. }
  350. keptClients = append(keptClients, c)
  351. if i < len(interfaceClients) {
  352. keptWire = append(keptWire, interfaceClients[i])
  353. }
  354. }
  355. if len(keptClients) == 0 {
  356. return false, nil
  357. }
  358. clients = keptClients
  359. interfaceClients = keptWire
  360. }
  361. var selfEmails map[string]struct{}
  362. if oldInbound.Protocol == model.WireGuard || oldInbound.Protocol == model.AmneziaWG {
  363. selfEmails = make(map[string]struct{}, len(clients))
  364. for _, c := range clients {
  365. if c.Email != "" {
  366. selfEmails[strings.ToLower(c.Email)] = struct{}{}
  367. }
  368. }
  369. crossUsed, cErr := s.otherTunnelAllowedIPs(database.GetDB(), inboundSvc, oldInbound.Id, selfEmails)
  370. if cErr != nil {
  371. return false, cErr
  372. }
  373. if oldInbound.Protocol == model.WireGuard {
  374. if dErr := defaultWireguardClients(oldInbound.Settings, existingClients, clients, interfaceClients, crossUsed); dErr != nil {
  375. return false, dErr
  376. }
  377. }
  378. if oldInbound.Protocol == model.AmneziaWG {
  379. if dErr := defaultAmneziaWGClients(oldInbound.Settings, existingClients, clients, interfaceClients, crossUsed); dErr != nil {
  380. return false, dErr
  381. }
  382. }
  383. }
  384. var portCtx portConflictContext
  385. if oldInbound.Protocol == model.AmneziaWG {
  386. portCtx, err = inboundSvc.loadPortConflictContext(database.GetDB())
  387. if err != nil {
  388. return false, err
  389. }
  390. }
  391. for _, client := range clients {
  392. if strings.TrimSpace(client.Email) == "" {
  393. return false, common.NewError("client email is required")
  394. }
  395. switch oldInbound.Protocol {
  396. case "trojan":
  397. if client.Password == "" {
  398. return false, common.NewError("empty client ID")
  399. }
  400. case "shadowsocks":
  401. if client.Email == "" {
  402. return false, common.NewError("empty client ID")
  403. }
  404. case "hysteria":
  405. if client.Auth == "" {
  406. return false, common.NewError("empty client ID")
  407. }
  408. case "wireguard", "amneziawg":
  409. if client.PublicKey == "" {
  410. return false, common.NewError("wireguard client requires a key")
  411. }
  412. case "mtproto":
  413. if client.Secret == "" {
  414. return false, common.NewError("mtproto client requires a secret")
  415. }
  416. if client.AdTag != "" && !model.ValidMtprotoAdTag(client.AdTag) {
  417. return false, common.NewError("mtproto client ad tag must be 32 hex characters")
  418. }
  419. default:
  420. if client.ID == "" {
  421. return false, common.NewError("empty client ID")
  422. }
  423. }
  424. if oldInbound.Protocol == model.AmneziaWG {
  425. if hit := inboundSvc.checkForwardedPortsConflict(portCtx, client.ForwardedPorts); hit != "" {
  426. return false, common.NewError("amneziawg: forwardedPorts collides with", hit)
  427. }
  428. }
  429. }
  430. var oldSettings map[string]any
  431. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  432. if err != nil {
  433. return false, err
  434. }
  435. if oldInbound.Protocol == model.Shadowsocks {
  436. applyShadowsocksClientMethod(interfaceClients, oldSettings)
  437. }
  438. oldClients, _ := oldSettings["clients"].([]any)
  439. oldClients = compactOrphans(database.GetDB(), oldClients)
  440. oldClients = append(oldClients, interfaceClients...)
  441. oldSettings["clients"] = oldClients
  442. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  443. if err != nil {
  444. return false, err
  445. }
  446. prevSettings := oldInbound.Settings
  447. oldInbound.Settings = string(newSettings)
  448. // From the stamped wire entries, not from clients: created_at / updated_at /
  449. // subId are written onto interfaceClients above, after clients was parsed.
  450. addedClients, err := settingsEntriesToClients(interfaceClients)
  451. if err != nil {
  452. return false, err
  453. }
  454. needRestart := false
  455. rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound)
  456. if perr != nil {
  457. return false, perr
  458. }
  459. // Persist client stats + inbound atomically, serialized against the traffic
  460. // poll to avoid the cross-transaction lock-order deadlock (runSerializedTx).
  461. if txErr := runSerializedTx(func(tx *gorm.DB) error {
  462. // lockInbound is per-inbound, so the pre-tx cross-inbound checks race
  463. // concurrent writers on other inbounds — re-run them in here (#6225).
  464. if oldInbound.Protocol == model.WireGuard || oldInbound.Protocol == model.AmneziaWG {
  465. crossUsed, cErr := s.otherTunnelAllowedIPs(tx, inboundSvc, oldInbound.Id, selfEmails)
  466. if cErr != nil {
  467. return cErr
  468. }
  469. crossAddrs := make([]string, 0, len(crossUsed))
  470. for addr := range crossUsed {
  471. crossAddrs = append(crossAddrs, addr)
  472. }
  473. for i := range clients {
  474. if hit := wireguardAllowedIPsCollision(clients[i].AllowedIPs, crossAddrs); hit != "" {
  475. return common.NewError("allowedIPs entry", hit, "is already used by a client on", crossUsed[hit])
  476. }
  477. }
  478. }
  479. if oldInbound.Protocol == model.AmneziaWG {
  480. txPortCtx, pErr := inboundSvc.loadPortConflictContext(tx)
  481. if pErr != nil {
  482. return pErr
  483. }
  484. for i := range clients {
  485. if hit := inboundSvc.checkForwardedPortsConflict(txPortCtx, clients[i].ForwardedPorts); hit != "" {
  486. return common.NewError("amneziawg: forwardedPorts collides with", hit)
  487. }
  488. }
  489. }
  490. for i := range clients {
  491. if len(clients[i].Email) == 0 {
  492. continue
  493. }
  494. if e := inboundSvc.AddClientStat(tx, data.Id, &clients[i]); e != nil {
  495. return e
  496. }
  497. }
  498. if e := tx.Save(oldInbound).Error; e != nil {
  499. return e
  500. }
  501. if err := s.ApplyInboundClientDelta(tx, oldInbound.Id, addedClients, nil); err != nil {
  502. return err
  503. }
  504. if oldInbound.NodeID != nil {
  505. return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID)
  506. }
  507. return nil
  508. }); txErr != nil {
  509. return false, txErr
  510. }
  511. // Apply to the running runtime after commit — outside the serialized writer
  512. // so a slow node call can't stall traffic accounting.
  513. if oldInbound.NodeID == nil {
  514. if !push {
  515. needRestart = true
  516. } else if oldInbound.Protocol == model.MTProto {
  517. inboundSvc.applyLocalMtproto(oldInbound.Id)
  518. } else if oldInbound.Protocol == model.AmneziaWG {
  519. inboundSvc.applyLocalAmneziaWG(oldInbound.Id)
  520. } else {
  521. for _, client := range clients {
  522. if len(client.Email) == 0 {
  523. needRestart = true
  524. continue
  525. }
  526. if !client.Enable {
  527. continue
  528. }
  529. cipher := ""
  530. if oldInbound.Protocol == "shadowsocks" {
  531. cipher, _ = oldSettings["method"].(string)
  532. }
  533. err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
  534. "email": client.Email,
  535. "id": client.ID,
  536. "auth": client.Auth,
  537. "security": client.Security,
  538. "flow": client.Flow,
  539. "password": client.Password,
  540. "cipher": cipher,
  541. "publicKey": client.PublicKey,
  542. "allowedIPs": client.AllowedIPs,
  543. "preSharedKey": client.PreSharedKey,
  544. "keepAlive": keepAliveStr(client.KeepAlive),
  545. })
  546. if err1 == nil {
  547. logger.Debug("Client added on", rt.Name(), ":", client.Email)
  548. } else {
  549. logger.Debug("Error in adding client on", rt.Name(), ":", err1)
  550. needRestart = true
  551. }
  552. }
  553. }
  554. } else {
  555. // Large batches would be M sequential per-client RPCs; the inbound's saved
  556. // settings already hold the final set, so mark dirty and let one reconcile
  557. // push converge the node instead.
  558. if push && len(clients) > nodeBulkPushThreshold {
  559. push = false
  560. }
  561. for _, client := range clients {
  562. if push {
  563. if err1 := rt.AddClient(context.Background(), oldInbound, client); err1 != nil {
  564. logger.Warning("Error in adding client on", rt.Name(), ":", err1)
  565. push = false
  566. }
  567. }
  568. }
  569. if push {
  570. advancePushedInbound(rt, prevSettings, oldInbound)
  571. }
  572. }
  573. return needRestart, nil
  574. }
  575. func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *model.Inbound, oldEmail string) (bool, error) {
  576. defer lockInbound(data.Id).Unlock()
  577. clients, err := inboundSvc.GetClients(data)
  578. if err != nil {
  579. return false, err
  580. }
  581. var settings map[string]any
  582. err = json.Unmarshal([]byte(data.Settings), &settings)
  583. if err != nil {
  584. return false, err
  585. }
  586. interfaceClients := settings["clients"].([]any)
  587. oldInbound, err := inboundSvc.GetInbound(data.Id)
  588. if err != nil {
  589. return false, err
  590. }
  591. oldClients, err := inboundSvc.GetClients(oldInbound)
  592. if err != nil {
  593. return false, err
  594. }
  595. newClientId := ""
  596. switch oldInbound.Protocol {
  597. case "trojan":
  598. newClientId = clients[0].Password
  599. case "shadowsocks":
  600. newClientId = clients[0].Email
  601. case "hysteria":
  602. newClientId = clients[0].Auth
  603. case "wireguard", "amneziawg":
  604. newClientId = clients[0].Email
  605. case "mtproto":
  606. newClientId = clients[0].Email
  607. default:
  608. newClientId = clients[0].ID
  609. }
  610. // Locate the client to replace by email — the client's stable identity.
  611. // Credentials (uuid/password/auth) can drift from the inbound JSON, so they
  612. // are never used for matching.
  613. clientIndex := -1
  614. for index, oldClient := range oldClients {
  615. if strings.EqualFold(oldClient.Email, oldEmail) {
  616. oldEmail = oldClient.Email
  617. clientIndex = index
  618. break
  619. }
  620. }
  621. if newClientId == "" || clientIndex == -1 {
  622. return false, common.NewError("empty client ID")
  623. }
  624. if strings.TrimSpace(clients[0].Email) == "" {
  625. return false, common.NewError("client email is required")
  626. }
  627. if oldInbound.Protocol == model.MTProto && clients[0].AdTag != "" && !model.ValidMtprotoAdTag(clients[0].AdTag) {
  628. return false, common.NewError("mtproto client ad tag must be 32 hex characters")
  629. }
  630. if clients[0].Email != oldEmail {
  631. existEmail, err := s.checkEmailsExistForClients(inboundSvc, clients)
  632. if err != nil {
  633. return false, err
  634. }
  635. if existEmail != "" {
  636. return false, common.NewError("Duplicate email:", existEmail)
  637. }
  638. }
  639. // WireGuard/AmneziaWG keys are never rotated by an edit: when the incoming
  640. // payload omits them (a metadata-only change), carry the stored credentials
  641. // forward so the settings JSON and the running peer keep the client's identity.
  642. if (oldInbound.Protocol == model.WireGuard || oldInbound.Protocol == model.AmneziaWG) && clientIndex >= 0 && clientIndex < len(oldClients) {
  643. old := oldClients[clientIndex]
  644. if clients[0].PrivateKey == "" {
  645. clients[0].PrivateKey = old.PrivateKey
  646. }
  647. if clients[0].PublicKey == "" {
  648. clients[0].PublicKey = old.PublicKey
  649. }
  650. if len(clients[0].AllowedIPs) == 0 {
  651. clients[0].AllowedIPs = old.AllowedIPs
  652. } else {
  653. normalized, nErr := normalizeWireguardAllowedIPs(clients[0].AllowedIPs)
  654. if nErr != nil {
  655. return false, nErr
  656. }
  657. if len(normalized) == 0 {
  658. clients[0].AllowedIPs = old.AllowedIPs
  659. } else {
  660. peers := make([]string, 0, len(oldClients))
  661. for i := range oldClients {
  662. if i == clientIndex {
  663. continue
  664. }
  665. peers = append(peers, oldClients[i].AllowedIPs...)
  666. }
  667. if hit := wireguardAllowedIPsCollision(normalized, peers); hit != "" {
  668. return false, common.NewError("wireguard: allowedIPs entry already used by another client:", hit)
  669. }
  670. clients[0].AllowedIPs = normalized
  671. }
  672. }
  673. if clients[0].PreSharedKey == "" {
  674. clients[0].PreSharedKey = old.PreSharedKey
  675. }
  676. if clients[0].KeepAlive == 0 {
  677. clients[0].KeepAlive = old.KeepAlive
  678. }
  679. // ForwardedPorts is AmneziaWG-only (WireGuard's own inbound never
  680. // reads it), same carry-forward reasoning as the fields above: a
  681. // partial edit (e.g. a Telegram-bot enable/expiry toggle, or an API
  682. // call that omits the field) must not silently drop a client's
  683. // existing port-forwarding spec.
  684. if oldInbound.Protocol == model.AmneziaWG && clients[0].ForwardedPorts == "" {
  685. clients[0].ForwardedPorts = old.ForwardedPorts
  686. }
  687. }
  688. if oldInbound.Protocol == model.AmneziaWG {
  689. portCtx, err := inboundSvc.loadPortConflictContext(database.GetDB())
  690. if err != nil {
  691. return false, err
  692. }
  693. if hit := inboundSvc.checkForwardedPortsConflict(portCtx, clients[0].ForwardedPorts); hit != "" {
  694. return false, common.NewError("amneziawg: forwardedPorts collides with", hit)
  695. }
  696. }
  697. var oldSettings map[string]any
  698. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  699. if err != nil {
  700. return false, err
  701. }
  702. settingsClients, _ := oldSettings["clients"].([]any)
  703. var preservedCreated any
  704. var preservedSubID string
  705. var oldClientMap map[string]any
  706. if clientIndex >= 0 && clientIndex < len(settingsClients) {
  707. if oldMap, ok := settingsClients[clientIndex].(map[string]any); ok {
  708. oldClientMap = oldMap
  709. if v, ok2 := oldMap["created_at"]; ok2 {
  710. preservedCreated = v
  711. }
  712. preservedSubID, _ = oldMap["subId"].(string)
  713. }
  714. }
  715. if oldInbound.Protocol == model.Shadowsocks {
  716. applyShadowsocksClientMethod(interfaceClients, oldSettings)
  717. }
  718. if len(interfaceClients) > 0 {
  719. if newMap, ok := interfaceClients[0].(map[string]any); ok {
  720. if preservedCreated == nil {
  721. preservedCreated = time.Now().Unix() * 1000
  722. }
  723. newMap["created_at"] = preservedCreated
  724. newSub, _ := newMap["subId"].(string)
  725. if strings.TrimSpace(newSub) == "" {
  726. if strings.TrimSpace(preservedSubID) != "" {
  727. newMap["subId"] = preservedSubID
  728. } else {
  729. newMap["subId"] = random.NumLower(16)
  730. }
  731. }
  732. if v, ok2 := newMap["subId"].(string); ok2 {
  733. clients[0].SubID = v
  734. }
  735. if oldInbound.Protocol == model.WireGuard || oldInbound.Protocol == model.AmneziaWG {
  736. newMap["privateKey"] = clients[0].PrivateKey
  737. newMap["publicKey"] = clients[0].PublicKey
  738. newMap["allowedIPs"] = clients[0].AllowedIPs
  739. if clients[0].PreSharedKey != "" {
  740. newMap["preSharedKey"] = clients[0].PreSharedKey
  741. }
  742. if clients[0].KeepAlive > 0 {
  743. newMap["keepAlive"] = clients[0].KeepAlive
  744. }
  745. if oldInbound.Protocol == model.AmneziaWG && clients[0].ForwardedPorts != "" {
  746. newMap["forwardedPorts"] = clients[0].ForwardedPorts
  747. }
  748. }
  749. if oldClientMap != nil && sameClientConfigExceptUpdatedAt(oldClientMap, newMap) {
  750. if v, ok2 := oldClientMap["updated_at"]; ok2 {
  751. newMap["updated_at"] = v
  752. } else {
  753. delete(newMap, "updated_at")
  754. }
  755. } else {
  756. newMap["updated_at"] = time.Now().Unix() * 1000
  757. }
  758. interfaceClients[0] = newMap
  759. }
  760. }
  761. settingsClients[clientIndex] = interfaceClients[0]
  762. oldSettings["clients"] = settingsClients
  763. if oldInbound.Protocol == model.VLESS {
  764. hasVisionFlow := false
  765. for _, c := range settingsClients {
  766. cm, ok := c.(map[string]any)
  767. if !ok {
  768. continue
  769. }
  770. if flow, _ := cm["flow"].(string); flow == "xtls-rprx-vision" {
  771. hasVisionFlow = true
  772. break
  773. }
  774. }
  775. if !hasVisionFlow {
  776. delete(oldSettings, "testseed")
  777. }
  778. }
  779. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  780. if err != nil {
  781. return false, err
  782. }
  783. if string(newSettings) == oldInbound.Settings {
  784. return false, nil
  785. }
  786. prevSettings := oldInbound.Settings
  787. oldInbound.Settings = string(newSettings)
  788. // From the stamped wire entry, not from clients[0]: created_at, the
  789. // preserved subId and the WireGuard carry-forward land on interfaceClients.
  790. changedClients, err := settingsEntriesToClients(interfaceClients[:1])
  791. if err != nil {
  792. return false, err
  793. }
  794. var detachEmails []string
  795. if len(oldEmail) > 0 && oldEmail != clients[0].Email {
  796. detachEmails = []string{oldEmail}
  797. }
  798. needRestart := false
  799. // Resolve the push plan before the DB write so a node-state lookup failure
  800. // still aborts the whole update without committing anything (it used to roll
  801. // the transaction back). nodePushPlan only reads, so order doesn't matter.
  802. var rt runtime.Runtime
  803. var push bool
  804. if len(oldEmail) > 0 {
  805. var perr error
  806. rt, push, _, perr = inboundSvc.nodePushPlan(oldInbound)
  807. if perr != nil {
  808. return false, perr
  809. }
  810. }
  811. // Persist client stats + inbound atomically, serialized against the traffic
  812. // poll to avoid the cross-transaction lock-order deadlock (runSerializedTx).
  813. if txErr := runSerializedTx(func(tx *gorm.DB) error {
  814. // Same re-check-inside-the-writer rule as AddInboundClient (#6225):
  815. // the pre-tx pass can race a concurrent writer on another inbound.
  816. if oldInbound.Protocol == model.AmneziaWG {
  817. txPortCtx, pErr := inboundSvc.loadPortConflictContext(tx)
  818. if pErr != nil {
  819. return pErr
  820. }
  821. if hit := inboundSvc.checkForwardedPortsConflict(txPortCtx, clients[0].ForwardedPorts); hit != "" {
  822. return common.NewError("amneziawg: forwardedPorts collides with", hit)
  823. }
  824. }
  825. if len(clients[0].Email) > 0 {
  826. if len(oldEmail) > 0 {
  827. emailUnchanged := strings.EqualFold(oldEmail, clients[0].Email)
  828. targetExists := int64(0)
  829. if !emailUnchanged {
  830. if e := tx.Model(xray.ClientTraffic{}).Where("email = ?", clients[0].Email).Count(&targetExists).Error; e != nil {
  831. return e
  832. }
  833. }
  834. if emailUnchanged || targetExists == 0 {
  835. if e := inboundSvc.UpdateClientStat(tx, oldEmail, &clients[0]); e != nil {
  836. return e
  837. }
  838. if e := inboundSvc.UpdateClientIPs(tx, oldEmail, clients[0].Email); e != nil {
  839. return e
  840. }
  841. } else {
  842. stillUsed, sErr := inboundSvc.emailUsedByOtherInbounds(oldEmail, data.Id)
  843. if sErr != nil {
  844. return sErr
  845. }
  846. if !stillUsed {
  847. if e := inboundSvc.DelClientStat(tx, oldEmail); e != nil {
  848. return e
  849. }
  850. if e := inboundSvc.DelClientIPs(tx, oldEmail); e != nil {
  851. return e
  852. }
  853. }
  854. if e := inboundSvc.UpdateClientStat(tx, clients[0].Email, &clients[0]); e != nil {
  855. return e
  856. }
  857. }
  858. } else {
  859. if e := inboundSvc.AddClientStat(tx, data.Id, &clients[0]); e != nil {
  860. return e
  861. }
  862. }
  863. } else {
  864. stillUsed, sErr := inboundSvc.emailUsedByOtherInbounds(oldEmail, data.Id)
  865. if sErr != nil {
  866. return sErr
  867. }
  868. if !stillUsed {
  869. if e := inboundSvc.DelClientStat(tx, oldEmail); e != nil {
  870. return e
  871. }
  872. if e := inboundSvc.DelClientIPs(tx, oldEmail); e != nil {
  873. return e
  874. }
  875. }
  876. }
  877. if e := tx.Save(oldInbound).Error; e != nil {
  878. return e
  879. }
  880. // Rename the client record in the same transaction as the settings JSON
  881. // so no concurrent SyncInbound can see one renamed without the other.
  882. // Byte-level compare (not EqualFold): case-only edits must rename too,
  883. // otherwise SyncInbound's case-sensitive lookup creates a duplicate row.
  884. if len(oldEmail) > 0 && oldEmail != clients[0].Email {
  885. var renameTaken int64
  886. if e := tx.Model(&model.ClientRecord{}).Where("email = ?", clients[0].Email).Count(&renameTaken).Error; e != nil {
  887. return e
  888. }
  889. if renameTaken == 0 {
  890. if e := tx.Model(&model.ClientRecord{}).Where("email = ?", oldEmail).Update("email", clients[0].Email).Error; e != nil {
  891. return e
  892. }
  893. }
  894. }
  895. // detachEmails covers the rename the guard above refused: the old record
  896. // keeps this inbound's link otherwise, which the full sync used to drop.
  897. if err := s.ApplyInboundClientDelta(tx, oldInbound.Id, changedClients, detachEmails); err != nil {
  898. return err
  899. }
  900. if oldInbound.NodeID != nil {
  901. return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID)
  902. }
  903. return nil
  904. }); txErr != nil {
  905. return false, txErr
  906. }
  907. // Apply to the running runtime after the DB is committed — outside the
  908. // serialized writer so a slow node call can't stall traffic accounting.
  909. if len(oldEmail) > 0 {
  910. if oldInbound.NodeID == nil {
  911. if !push {
  912. needRestart = true
  913. } else if oldInbound.Protocol == model.MTProto {
  914. inboundSvc.applyLocalMtproto(oldInbound.Id)
  915. } else if oldInbound.Protocol == model.AmneziaWG {
  916. inboundSvc.applyLocalAmneziaWG(oldInbound.Id)
  917. } else {
  918. if oldClients[clientIndex].Enable {
  919. err1 := rt.RemoveUser(context.Background(), oldInbound, oldEmail)
  920. if err1 == nil {
  921. logger.Debug("Old client deleted on", rt.Name(), ":", oldEmail)
  922. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", oldEmail)) {
  923. logger.Debug("User is already deleted. Nothing to do more...")
  924. } else {
  925. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  926. needRestart = true
  927. }
  928. }
  929. if clients[0].Enable {
  930. cipher := ""
  931. if oldInbound.Protocol == "shadowsocks" {
  932. cipher, _ = oldSettings["method"].(string)
  933. }
  934. err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
  935. "email": clients[0].Email,
  936. "id": clients[0].ID,
  937. "security": clients[0].Security,
  938. "flow": clients[0].Flow,
  939. "auth": clients[0].Auth,
  940. "password": clients[0].Password,
  941. "cipher": cipher,
  942. "publicKey": clients[0].PublicKey,
  943. "allowedIPs": clients[0].AllowedIPs,
  944. "preSharedKey": clients[0].PreSharedKey,
  945. "keepAlive": keepAliveStr(clients[0].KeepAlive),
  946. })
  947. if err1 == nil {
  948. logger.Debug("Client edited on", rt.Name(), ":", clients[0].Email)
  949. } else {
  950. logger.Debug("Error in adding client on", rt.Name(), ":", err1)
  951. needRestart = true
  952. }
  953. }
  954. }
  955. } else if push {
  956. if err1 := rt.UpdateUser(context.Background(), oldInbound, oldEmail, clients[0]); err1 != nil {
  957. logger.Warning("Error in updating client on", rt.Name(), ":", err1)
  958. } else {
  959. advancePushedInbound(rt, prevSettings, oldInbound)
  960. }
  961. }
  962. } else {
  963. logger.Debug("Client old email not found")
  964. needRestart = true
  965. }
  966. return needRestart, nil
  967. }
  968. func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inboundId int, email string, keepTraffic bool, fullDelete bool) (bool, error) {
  969. defer lockInbound(inboundId).Unlock()
  970. oldInbound, err := inboundSvc.GetInbound(inboundId)
  971. if err != nil {
  972. logger.Error("Load Old Data Error")
  973. return false, err
  974. }
  975. var settings map[string]any
  976. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  977. return false, err
  978. }
  979. interfaceClients, ok := settings["clients"].([]any)
  980. if !ok {
  981. return false, common.NewError("invalid clients format in inbound settings")
  982. }
  983. var newClients []any
  984. needApiDel := false
  985. found := false
  986. for _, client := range interfaceClients {
  987. c, ok := client.(map[string]any)
  988. if !ok {
  989. continue
  990. }
  991. if cEmail, ok := c["email"].(string); ok && cEmail == email {
  992. found = true
  993. needApiDel, _ = c["enable"].(bool)
  994. } else {
  995. newClients = append(newClients, client)
  996. }
  997. }
  998. if !found {
  999. return false, fmt.Errorf("%w for email: %s", ErrClientNotInInbound, email)
  1000. }
  1001. db := database.GetDB()
  1002. newClients = compactOrphans(db, newClients)
  1003. if newClients == nil {
  1004. newClients = []any{}
  1005. }
  1006. settings["clients"] = newClients
  1007. newSettings, err := json.MarshalIndent(settings, "", " ")
  1008. if err != nil {
  1009. return false, err
  1010. }
  1011. prevSettings := oldInbound.Settings
  1012. oldInbound.Settings = string(newSettings)
  1013. emailShared, err := inboundSvc.emailUsedByOtherInbounds(email, inboundId)
  1014. if err != nil {
  1015. return false, err
  1016. }
  1017. needRestart := false
  1018. // Decide what to delete and the push plan before the serialized DB write —
  1019. // these are reads, and nodePushPlan failing should abort before committing.
  1020. delStat := false
  1021. if len(email) > 0 && !emailShared && !keepTraffic {
  1022. traffic, tErr := inboundSvc.GetClientTrafficByEmail(email)
  1023. if tErr != nil {
  1024. return false, tErr
  1025. }
  1026. delStat = traffic != nil
  1027. }
  1028. // The runtime user is scoped to this inbound's tag + email, so the push plan
  1029. // is resolved independently of emailShared — a sibling inbound still carrying
  1030. // the email must not suppress removing the user from this inbound's Xray.
  1031. var rt runtime.Runtime
  1032. var push bool
  1033. if len(email) > 0 && (oldInbound.NodeID != nil || needApiDel) {
  1034. r, p, _, perr := inboundSvc.nodePushPlan(oldInbound)
  1035. if perr != nil {
  1036. return false, perr
  1037. }
  1038. rt, push = r, p
  1039. }
  1040. // Persist the deletion atomically, serialized against the traffic poll to
  1041. // avoid the cross-transaction lock-order deadlock (runSerializedTx).
  1042. if txErr := runSerializedTx(func(tx *gorm.DB) error {
  1043. if !emailShared && !keepTraffic {
  1044. if e := inboundSvc.DelClientIPs(tx, email); e != nil {
  1045. logger.Error("Error in delete client IPs")
  1046. return e
  1047. }
  1048. }
  1049. if delStat {
  1050. if e := inboundSvc.DelClientStat(tx, email); e != nil {
  1051. logger.Error("Delete stats Data Error")
  1052. return e
  1053. }
  1054. }
  1055. if e := tx.Save(oldInbound).Error; e != nil {
  1056. return e
  1057. }
  1058. if err := s.ApplyInboundClientDelta(tx, inboundId, nil, []string{email}); err != nil {
  1059. return err
  1060. }
  1061. if oldInbound.NodeID != nil {
  1062. return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID)
  1063. }
  1064. return nil
  1065. }); txErr != nil {
  1066. return false, txErr
  1067. }
  1068. // Apply the runtime delete after commit — outside the serialized writer so a
  1069. // slow node call can't stall traffic accounting. Independent of emailShared:
  1070. // Xray users are keyed by inbound tag, so the user must be removed from this
  1071. // inbound's runtime even when the same email survives in another inbound.
  1072. if len(email) > 0 {
  1073. if oldInbound.NodeID == nil {
  1074. if oldInbound.Protocol == model.MTProto {
  1075. // mtg serves the full secret set, so any client delete re-applies
  1076. // it (removing the last client stops the sidecar) regardless of the
  1077. // client's enable state.
  1078. inboundSvc.applyLocalMtproto(oldInbound.Id)
  1079. } else if oldInbound.Protocol == model.AmneziaWG {
  1080. // Same reasoning as MTProto above: the interface config is
  1081. // regenerated from the full peer set, so any delete re-applies it.
  1082. inboundSvc.applyLocalAmneziaWG(oldInbound.Id)
  1083. } else if needApiDel {
  1084. // Local inbound: a disabled client isn't in the running Xray, so only
  1085. // a live one (needApiDel) needs an API removal.
  1086. if !push {
  1087. needRestart = true
  1088. } else if err1 := rt.RemoveUser(context.Background(), oldInbound, email); err1 == nil {
  1089. logger.Debug("Client deleted on", rt.Name(), ":", email)
  1090. needRestart = false
  1091. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  1092. logger.Debug("User is already deleted. Nothing to do more...")
  1093. } else {
  1094. logger.Debug("Error in deleting client on", rt.Name(), ":", email)
  1095. needRestart = true
  1096. }
  1097. }
  1098. } else {
  1099. // Node inbound: propagate the delete regardless of the enable flag —
  1100. // the node's own DB still carries a disabled client and would
  1101. // resurrect it on the next snapshot otherwise. A full client delete
  1102. // must remove the node's client record too, not just detach it from
  1103. // this inbound (#5797).
  1104. if push {
  1105. var err1 error
  1106. if fullDelete {
  1107. err1 = rt.DeleteClient(context.Background(), email)
  1108. } else {
  1109. err1 = rt.DeleteUser(context.Background(), oldInbound, email)
  1110. }
  1111. if err1 != nil {
  1112. logger.Warning("Error in deleting client on", rt.Name(), ":", err1)
  1113. } else {
  1114. advancePushedInbound(rt, prevSettings, oldInbound)
  1115. }
  1116. }
  1117. }
  1118. }
  1119. return needRestart, nil
  1120. }
  1121. func (s *ClientService) SetClientTelegramUserID(inboundSvc *InboundService, trafficId int, tgId int64) (bool, error) {
  1122. traffic, inbound, err := inboundSvc.GetClientInboundByTrafficID(trafficId)
  1123. if err != nil {
  1124. return false, err
  1125. }
  1126. if inbound == nil {
  1127. return false, common.NewError("Inbound Not Found For Traffic ID:", trafficId)
  1128. }
  1129. clientEmail := traffic.Email
  1130. oldClients, err := inboundSvc.GetClients(inbound)
  1131. if err != nil {
  1132. return false, err
  1133. }
  1134. found := false
  1135. for _, oldClient := range oldClients {
  1136. if oldClient.Email == clientEmail {
  1137. found = true
  1138. break
  1139. }
  1140. }
  1141. if !found {
  1142. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1143. }
  1144. var settings map[string]any
  1145. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1146. if err != nil {
  1147. return false, err
  1148. }
  1149. clients := settings["clients"].([]any)
  1150. var newClients []any
  1151. for client_index := range clients {
  1152. c := clients[client_index].(map[string]any)
  1153. if c["email"] == clientEmail {
  1154. c["tgId"] = tgId
  1155. c["updated_at"] = time.Now().Unix() * 1000
  1156. newClients = append(newClients, any(c))
  1157. }
  1158. }
  1159. settings["clients"] = newClients
  1160. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1161. if err != nil {
  1162. return false, err
  1163. }
  1164. inbound.Settings = string(modifiedSettings)
  1165. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientEmail)
  1166. return needRestart, err
  1167. }
  1168. func (s *ClientService) CheckIsEnabledByEmail(inboundSvc *InboundService, clientEmail string) (bool, error) {
  1169. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  1170. if err != nil {
  1171. return false, err
  1172. }
  1173. if inbound == nil {
  1174. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1175. }
  1176. clients, err := inboundSvc.GetClients(inbound)
  1177. if err != nil {
  1178. return false, err
  1179. }
  1180. isEnable := false
  1181. for _, client := range clients {
  1182. if client.Email == clientEmail {
  1183. isEnable = client.Enable
  1184. break
  1185. }
  1186. }
  1187. return isEnable, err
  1188. }
  1189. func (s *ClientService) ToggleClientEnableByEmail(inboundSvc *InboundService, clientEmail string) (bool, bool, error) {
  1190. current, err := s.CheckIsEnabledByEmail(inboundSvc, clientEmail)
  1191. if err != nil {
  1192. return false, false, err
  1193. }
  1194. target := !current
  1195. needRestart, err := s.applyClientFieldByEmail(inboundSvc, clientEmail, func(c map[string]any) {
  1196. c["enable"] = target
  1197. })
  1198. if err != nil {
  1199. return false, needRestart, err
  1200. }
  1201. return target, needRestart, nil
  1202. }
  1203. func (s *ClientService) SetClientEnableByEmail(inboundSvc *InboundService, clientEmail string, enable bool) (bool, bool, error) {
  1204. current, err := s.CheckIsEnabledByEmail(inboundSvc, clientEmail)
  1205. if err != nil {
  1206. return false, false, err
  1207. }
  1208. if current == enable {
  1209. return false, false, nil
  1210. }
  1211. needRestart, err := s.applyClientFieldByEmail(inboundSvc, clientEmail, func(c map[string]any) {
  1212. c["enable"] = enable
  1213. })
  1214. if err != nil {
  1215. return false, needRestart, err
  1216. }
  1217. return true, needRestart, nil
  1218. }
  1219. // applyClientFieldByEmail loads the inbound currently hosting clientEmail,
  1220. // confirms the client exists, applies mutate to the matching client (plus a
  1221. // refreshed updated_at), and hands a single-client update payload to
  1222. // UpdateInboundClient. The rebuilt clients array intentionally contains only
  1223. // the matched client — that is the input contract UpdateInboundClient expects
  1224. // (clients[0] is the new data; clientEmail locates the row to replace). It
  1225. // backs the single-field by-email setters below.
  1226. // applyClientFieldByEmail mutates a client field on every inbound the email is
  1227. // attached to. A multi-inbound client is one logical identity: patching only
  1228. // the first inbound's JSON would leave the siblings stale, and the next
  1229. // SyncInbound over a stale sibling would revert the edit in the normalized
  1230. // records (#5039).
  1231. func (s *ClientService) applyClientFieldByEmail(inboundSvc *InboundService, clientEmail string, mutate func(c map[string]any)) (bool, error) {
  1232. inboundIds, err := s.GetInboundIdsForEmail(database.GetDB(), clientEmail)
  1233. if err != nil {
  1234. return false, err
  1235. }
  1236. if len(inboundIds) == 0 {
  1237. // Legacy fallback for clients that only live in the inbound JSON and
  1238. // were never normalized into client_inbounds.
  1239. _, inbound, gErr := inboundSvc.GetClientInboundByEmail(clientEmail)
  1240. if gErr != nil {
  1241. return false, gErr
  1242. }
  1243. if inbound == nil {
  1244. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1245. }
  1246. inboundIds = []int{inbound.Id}
  1247. }
  1248. needRestart := false
  1249. found := false
  1250. for _, ibId := range inboundIds {
  1251. inbound, gErr := inboundSvc.GetInbound(ibId)
  1252. if gErr != nil {
  1253. return needRestart, gErr
  1254. }
  1255. var settings map[string]any
  1256. if uErr := json.Unmarshal([]byte(inbound.Settings), &settings); uErr != nil {
  1257. return needRestart, uErr
  1258. }
  1259. clients, _ := settings["clients"].([]any)
  1260. // UpdateInboundClient expects a single-client payload, so keep only the
  1261. // matching entry in the scratch copy; it splices the result back into
  1262. // the inbound's full client list itself.
  1263. var newClients []any
  1264. for client_index := range clients {
  1265. c, ok := clients[client_index].(map[string]any)
  1266. if !ok {
  1267. continue
  1268. }
  1269. if c["email"] == clientEmail {
  1270. mutate(c)
  1271. c["updated_at"] = time.Now().Unix() * 1000
  1272. newClients = append(newClients, any(c))
  1273. }
  1274. }
  1275. if len(newClients) == 0 {
  1276. continue
  1277. }
  1278. found = true
  1279. settings["clients"] = newClients
  1280. modifiedSettings, mErr := json.MarshalIndent(settings, "", " ")
  1281. if mErr != nil {
  1282. return needRestart, mErr
  1283. }
  1284. inbound.Settings = string(modifiedSettings)
  1285. nr, uErr := s.UpdateInboundClient(inboundSvc, inbound, clientEmail)
  1286. if uErr != nil {
  1287. return needRestart, uErr
  1288. }
  1289. needRestart = needRestart || nr
  1290. }
  1291. if !found {
  1292. return needRestart, common.NewError("Client Not Found For Email:", clientEmail)
  1293. }
  1294. return needRestart, nil
  1295. }
  1296. func (s *ClientService) ResetClientIpLimitByEmail(inboundSvc *InboundService, clientEmail string, count int) (bool, error) {
  1297. return s.applyClientFieldByEmail(inboundSvc, clientEmail, func(c map[string]any) {
  1298. c["limitIp"] = count
  1299. })
  1300. }
  1301. func (s *ClientService) ResetClientExpiryTimeByEmail(inboundSvc *InboundService, clientEmail string, expiry_time int64) (bool, error) {
  1302. return s.applyClientFieldByEmail(inboundSvc, clientEmail, func(c map[string]any) {
  1303. c["expiryTime"] = expiry_time
  1304. })
  1305. }
  1306. func (s *ClientService) ResetClientTrafficLimitByEmail(inboundSvc *InboundService, clientEmail string, totalGB int) (bool, error) {
  1307. if totalGB < 0 {
  1308. return false, common.NewError("totalGB must be >= 0")
  1309. }
  1310. return s.applyClientFieldByEmail(inboundSvc, clientEmail, func(c map[string]any) {
  1311. c["totalGB"] = totalGB * 1024 * 1024 * 1024
  1312. })
  1313. }