1
0

client_inbound_apply.go 44 KB

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