client_inbound_apply.go 45 KB

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