1
0

client_inbound_apply.go 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186
  1. package service
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "strings"
  7. "time"
  8. "github.com/mhsanaei/3x-ui/v3/internal/database"
  9. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  10. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  11. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  12. "github.com/mhsanaei/3x-ui/v3/internal/util/random"
  13. "github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
  14. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  15. "gorm.io/gorm"
  16. )
  17. // delInboundClients removes several clients from a single inbound in one pass:
  18. // one settings rewrite, one runtime sweep, one Save and one SyncInbound for the
  19. // whole batch, instead of repeating the full per-client cycle. It mirrors the
  20. // semantics of DelInboundClientByEmail for each removed client. needRestart is
  21. // the OR across all removals.
  22. func (s *ClientService) delInboundClients(inboundSvc *InboundService, inboundId int, recs []*model.ClientRecord, keepTraffic bool) (bool, error) {
  23. if len(recs) == 0 {
  24. return false, nil
  25. }
  26. defer lockInbound(inboundId).Unlock()
  27. oldInbound, err := inboundSvc.GetInbound(inboundId)
  28. if err != nil {
  29. logger.Error("Load Old Data Error")
  30. return false, err
  31. }
  32. var settings map[string]any
  33. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  34. return false, err
  35. }
  36. // Match by email — the client's stable identity (see Delete). Removes every
  37. // entry carrying a wanted email, independent of credential drift.
  38. wanted := make(map[string]struct{}, len(recs))
  39. for _, rec := range recs {
  40. if rec.Email != "" {
  41. wanted[rec.Email] = struct{}{}
  42. }
  43. }
  44. interfaceClients, ok := settings["clients"].([]any)
  45. if !ok {
  46. return false, common.NewError("invalid clients format in inbound settings")
  47. }
  48. type removedClient struct {
  49. email string
  50. needApiDel bool
  51. }
  52. removed := make([]removedClient, 0, len(wanted))
  53. newClients := make([]any, 0, len(interfaceClients))
  54. for _, client := range interfaceClients {
  55. c, ok := client.(map[string]any)
  56. if !ok {
  57. newClients = append(newClients, client)
  58. continue
  59. }
  60. email, _ := c["email"].(string)
  61. if _, hit := wanted[email]; hit && email != "" {
  62. enable, _ := c["enable"].(bool)
  63. removed = append(removed, removedClient{email: email, needApiDel: enable})
  64. continue
  65. }
  66. newClients = append(newClients, client)
  67. }
  68. if len(removed) == 0 {
  69. return false, nil
  70. }
  71. db := database.GetDB()
  72. newClients = compactOrphans(db, newClients)
  73. if newClients == nil {
  74. newClients = []any{}
  75. }
  76. settings["clients"] = newClients
  77. newSettings, err := json.MarshalIndent(settings, "", " ")
  78. if err != nil {
  79. return false, err
  80. }
  81. oldInbound.Settings = string(newSettings)
  82. var sharedSet map[string]bool
  83. if !keepTraffic {
  84. removedEmails := make([]string, 0, len(removed))
  85. for _, r := range removed {
  86. if r.email != "" {
  87. removedEmails = append(removedEmails, r.email)
  88. }
  89. }
  90. var sharedErr error
  91. sharedSet, sharedErr = inboundSvc.emailsUsedByOtherInbounds(removedEmails, inboundId)
  92. if sharedErr != nil {
  93. return false, sharedErr
  94. }
  95. }
  96. needRestart := false
  97. // Read each client's live state before the DB write (DelClientStat would
  98. // erase the enable flag we need to decide on a runtime removal).
  99. type delTarget struct {
  100. email string
  101. emailShared bool
  102. notDepleted bool
  103. needApiDel bool
  104. }
  105. targets := make([]delTarget, 0, len(removed))
  106. for _, r := range removed {
  107. email := r.email
  108. emailShared := sharedSet[strings.ToLower(strings.TrimSpace(email))]
  109. notDepleted := false
  110. if len(email) > 0 {
  111. var enables []bool
  112. if err := db.Model(xray.ClientTraffic{}).Where("email = ?", email).Limit(1).Pluck("enable", &enables).Error; err != nil {
  113. logger.Error("Get stats error")
  114. return needRestart, err
  115. }
  116. notDepleted = len(enables) > 0 && enables[0]
  117. }
  118. targets = append(targets, delTarget{email: email, emailShared: emailShared, notDepleted: notDepleted, needApiDel: r.needApiDel})
  119. }
  120. // Persist the batch deletion atomically, serialized against the traffic poll
  121. // to avoid the cross-transaction lock-order deadlock (runSerializedTx).
  122. if txErr := runSerializedTx(func(tx *gorm.DB) error {
  123. for _, t := range targets {
  124. if t.emailShared || keepTraffic {
  125. continue
  126. }
  127. if e := inboundSvc.DelClientIPs(tx, t.email); e != nil {
  128. logger.Error("Error in delete client IPs")
  129. return e
  130. }
  131. if len(t.email) > 0 {
  132. if e := inboundSvc.DelClientStat(tx, t.email); e != nil {
  133. logger.Error("Delete stats Data Error")
  134. return e
  135. }
  136. }
  137. }
  138. if e := tx.Save(oldInbound).Error; e != nil {
  139. return e
  140. }
  141. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  142. if gcErr != nil {
  143. return gcErr
  144. }
  145. if err := s.SyncInbound(tx, inboundId, finalClients); err != nil {
  146. return err
  147. }
  148. if oldInbound.NodeID != nil {
  149. return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID)
  150. }
  151. return nil
  152. }); txErr != nil {
  153. return needRestart, txErr
  154. }
  155. // Resolve the node push plan once for the whole batch instead of per email.
  156. var nodeRt runtime.Runtime
  157. nodePush := false
  158. if oldInbound.NodeID != nil {
  159. rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound)
  160. if perr != nil {
  161. return needRestart, perr
  162. }
  163. nodeRt, nodePush = rt, push
  164. // Large batches collapse into one reconcile push rather than M deletes.
  165. if nodePush && len(targets) > nodeBulkPushThreshold {
  166. nodePush = false
  167. }
  168. }
  169. // Apply runtime deletes after commit — outside the serialized writer so a
  170. // slow node call can't stall traffic accounting.
  171. for _, t := range targets {
  172. if len(t.email) == 0 {
  173. continue
  174. }
  175. if oldInbound.NodeID == nil {
  176. if t.needApiDel && t.notDepleted {
  177. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  178. if rterr != nil {
  179. needRestart = true
  180. } else if err1 := rt.RemoveUser(context.Background(), oldInbound, t.email); err1 != nil {
  181. if !strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", t.email)) {
  182. needRestart = true
  183. }
  184. }
  185. }
  186. } else if nodePush {
  187. if err1 := nodeRt.DeleteUser(context.Background(), oldInbound, t.email); err1 != nil {
  188. logger.Warning("Error in deleting client on", nodeRt.Name(), ":", err1)
  189. }
  190. }
  191. }
  192. return needRestart, nil
  193. }
  194. func (s *ClientService) checkEmailsExistForClients(inboundSvc *InboundService, clients []model.Client, emailSubIDs map[string]string) (string, error) {
  195. if emailSubIDs == nil {
  196. var err error
  197. emailSubIDs, err = inboundSvc.getAllEmailSubIDs()
  198. if err != nil {
  199. return "", err
  200. }
  201. }
  202. seen := make(map[string]string, len(clients))
  203. for _, client := range clients {
  204. if client.Email == "" {
  205. continue
  206. }
  207. key := strings.ToLower(client.Email)
  208. if prev, ok := seen[key]; ok {
  209. if prev != client.SubID || client.SubID == "" {
  210. return client.Email, nil
  211. }
  212. continue
  213. }
  214. seen[key] = client.SubID
  215. if existingSub, ok := emailSubIDs[key]; ok {
  216. if client.SubID == "" || existingSub == "" || existingSub != client.SubID {
  217. return client.Email, nil
  218. }
  219. }
  220. }
  221. return "", nil
  222. }
  223. func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model.Inbound) (bool, error) {
  224. return s.addInboundClient(inboundSvc, data, nil)
  225. }
  226. // addInboundClient is AddInboundClient with an optional precomputed email→subId
  227. // map. Bulk callers pass a single snapshot so the global getAllEmailSubIDs scan
  228. // runs once for the whole batch instead of once per target inbound; a nil map
  229. // makes it compute its own (the single-add path).
  230. func (s *ClientService) addInboundClient(inboundSvc *InboundService, data *model.Inbound, emailSubIDs map[string]string) (bool, error) {
  231. defer lockInbound(data.Id).Unlock()
  232. clients, err := inboundSvc.GetClients(data)
  233. if err != nil {
  234. return false, err
  235. }
  236. var settings map[string]any
  237. err = json.Unmarshal([]byte(data.Settings), &settings)
  238. if err != nil {
  239. return false, err
  240. }
  241. interfaceClients := settings["clients"].([]any)
  242. nowTs := time.Now().Unix() * 1000
  243. for i := range interfaceClients {
  244. if cm, ok := interfaceClients[i].(map[string]any); ok {
  245. if _, ok2 := cm["created_at"]; !ok2 {
  246. cm["created_at"] = nowTs
  247. }
  248. cm["updated_at"] = nowTs
  249. existingSub, _ := cm["subId"].(string)
  250. if strings.TrimSpace(existingSub) == "" {
  251. cm["subId"] = random.NumLower(16)
  252. }
  253. interfaceClients[i] = cm
  254. }
  255. }
  256. existEmail, err := s.checkEmailsExistForClients(inboundSvc, clients, emailSubIDs)
  257. if err != nil {
  258. return false, err
  259. }
  260. if existEmail != "" {
  261. return false, common.NewError("Duplicate email:", existEmail)
  262. }
  263. oldInbound, err := inboundSvc.GetInbound(data.Id)
  264. if err != nil {
  265. return false, err
  266. }
  267. if oldInbound.Protocol == model.WireGuard {
  268. existing, gcErr := inboundSvc.GetClients(oldInbound)
  269. if gcErr != nil {
  270. return false, gcErr
  271. }
  272. if dErr := defaultWireguardClients(existing, clients, interfaceClients); dErr != nil {
  273. return false, dErr
  274. }
  275. }
  276. for _, client := range clients {
  277. if strings.TrimSpace(client.Email) == "" {
  278. return false, common.NewError("client email is required")
  279. }
  280. switch oldInbound.Protocol {
  281. case "trojan":
  282. if client.Password == "" {
  283. return false, common.NewError("empty client ID")
  284. }
  285. case "shadowsocks":
  286. if client.Email == "" {
  287. return false, common.NewError("empty client ID")
  288. }
  289. case "hysteria":
  290. if client.Auth == "" {
  291. return false, common.NewError("empty client ID")
  292. }
  293. case "wireguard":
  294. if client.PublicKey == "" {
  295. return false, common.NewError("wireguard client requires a key")
  296. }
  297. default:
  298. if client.ID == "" {
  299. return false, common.NewError("empty client ID")
  300. }
  301. }
  302. }
  303. var oldSettings map[string]any
  304. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  305. if err != nil {
  306. return false, err
  307. }
  308. if oldInbound.Protocol == model.Shadowsocks {
  309. applyShadowsocksClientMethod(interfaceClients, oldSettings)
  310. }
  311. oldClients, _ := oldSettings["clients"].([]any)
  312. oldClients = compactOrphans(database.GetDB(), oldClients)
  313. oldClients = append(oldClients, interfaceClients...)
  314. oldSettings["clients"] = oldClients
  315. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  316. if err != nil {
  317. return false, err
  318. }
  319. oldInbound.Settings = string(newSettings)
  320. needRestart := false
  321. rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound)
  322. if perr != nil {
  323. return false, perr
  324. }
  325. // Persist client stats + inbound atomically, serialized against the traffic
  326. // poll to avoid the cross-transaction lock-order deadlock (runSerializedTx).
  327. if txErr := runSerializedTx(func(tx *gorm.DB) error {
  328. for i := range clients {
  329. if len(clients[i].Email) == 0 {
  330. continue
  331. }
  332. if e := inboundSvc.AddClientStat(tx, data.Id, &clients[i]); e != nil {
  333. return e
  334. }
  335. }
  336. if e := tx.Save(oldInbound).Error; e != nil {
  337. return e
  338. }
  339. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  340. if gcErr != nil {
  341. return gcErr
  342. }
  343. if err := s.SyncInbound(tx, oldInbound.Id, finalClients); err != nil {
  344. return err
  345. }
  346. if oldInbound.NodeID != nil {
  347. return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID)
  348. }
  349. return nil
  350. }); txErr != nil {
  351. return false, txErr
  352. }
  353. // Apply to the running runtime after commit — outside the serialized writer
  354. // so a slow node call can't stall traffic accounting.
  355. if oldInbound.NodeID == nil {
  356. if !push {
  357. needRestart = true
  358. } else {
  359. for _, client := range clients {
  360. if len(client.Email) == 0 {
  361. needRestart = true
  362. continue
  363. }
  364. if !client.Enable {
  365. continue
  366. }
  367. cipher := ""
  368. if oldInbound.Protocol == "shadowsocks" {
  369. cipher = oldSettings["method"].(string)
  370. }
  371. err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
  372. "email": client.Email,
  373. "id": client.ID,
  374. "auth": client.Auth,
  375. "security": client.Security,
  376. "flow": client.Flow,
  377. "password": client.Password,
  378. "cipher": cipher,
  379. "publicKey": client.PublicKey,
  380. "allowedIPs": client.AllowedIPs,
  381. "preSharedKey": client.PreSharedKey,
  382. "keepAlive": keepAliveStr(client.KeepAlive),
  383. })
  384. if err1 == nil {
  385. logger.Debug("Client added on", rt.Name(), ":", client.Email)
  386. } else {
  387. logger.Debug("Error in adding client on", rt.Name(), ":", err1)
  388. needRestart = true
  389. }
  390. }
  391. }
  392. } else {
  393. // Large batches would be M sequential per-client RPCs; the inbound's saved
  394. // settings already hold the final set, so mark dirty and let one reconcile
  395. // push converge the node instead.
  396. if push && len(clients) > nodeBulkPushThreshold {
  397. push = false
  398. }
  399. for _, client := range clients {
  400. if push {
  401. if err1 := rt.AddClient(context.Background(), oldInbound, client); err1 != nil {
  402. logger.Warning("Error in adding client on", rt.Name(), ":", err1)
  403. push = false
  404. }
  405. }
  406. }
  407. }
  408. return needRestart, nil
  409. }
  410. func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *model.Inbound, oldEmail string) (bool, error) {
  411. defer lockInbound(data.Id).Unlock()
  412. clients, err := inboundSvc.GetClients(data)
  413. if err != nil {
  414. return false, err
  415. }
  416. var settings map[string]any
  417. err = json.Unmarshal([]byte(data.Settings), &settings)
  418. if err != nil {
  419. return false, err
  420. }
  421. interfaceClients := settings["clients"].([]any)
  422. oldInbound, err := inboundSvc.GetInbound(data.Id)
  423. if err != nil {
  424. return false, err
  425. }
  426. oldClients, err := inboundSvc.GetClients(oldInbound)
  427. if err != nil {
  428. return false, err
  429. }
  430. newClientId := ""
  431. switch oldInbound.Protocol {
  432. case "trojan":
  433. newClientId = clients[0].Password
  434. case "shadowsocks":
  435. newClientId = clients[0].Email
  436. case "hysteria":
  437. newClientId = clients[0].Auth
  438. case "wireguard":
  439. newClientId = clients[0].Email
  440. default:
  441. newClientId = clients[0].ID
  442. }
  443. // Locate the client to replace by email — the client's stable identity.
  444. // Credentials (uuid/password/auth) can drift from the inbound JSON, so they
  445. // are never used for matching.
  446. clientIndex := -1
  447. for index, oldClient := range oldClients {
  448. if strings.EqualFold(oldClient.Email, oldEmail) {
  449. oldEmail = oldClient.Email
  450. clientIndex = index
  451. break
  452. }
  453. }
  454. if newClientId == "" || clientIndex == -1 {
  455. return false, common.NewError("empty client ID")
  456. }
  457. if strings.TrimSpace(clients[0].Email) == "" {
  458. return false, common.NewError("client email is required")
  459. }
  460. if clients[0].Email != oldEmail {
  461. existEmail, err := s.checkEmailsExistForClients(inboundSvc, clients, nil)
  462. if err != nil {
  463. return false, err
  464. }
  465. if existEmail != "" {
  466. return false, common.NewError("Duplicate email:", existEmail)
  467. }
  468. }
  469. // WireGuard keys are never rotated by an edit: when the incoming payload omits
  470. // them (a metadata-only change), carry the stored credentials forward so the
  471. // settings JSON and the running peer keep the client's identity.
  472. if oldInbound.Protocol == model.WireGuard && clientIndex >= 0 && clientIndex < len(oldClients) {
  473. old := oldClients[clientIndex]
  474. if clients[0].PrivateKey == "" {
  475. clients[0].PrivateKey = old.PrivateKey
  476. }
  477. if clients[0].PublicKey == "" {
  478. clients[0].PublicKey = old.PublicKey
  479. }
  480. if len(clients[0].AllowedIPs) == 0 {
  481. clients[0].AllowedIPs = old.AllowedIPs
  482. } else {
  483. normalized, nErr := normalizeWireguardAllowedIPs(clients[0].AllowedIPs)
  484. if nErr != nil {
  485. return false, nErr
  486. }
  487. if len(normalized) == 0 {
  488. clients[0].AllowedIPs = old.AllowedIPs
  489. } else {
  490. peers := make([]string, 0, len(oldClients))
  491. for i := range oldClients {
  492. if i == clientIndex {
  493. continue
  494. }
  495. peers = append(peers, oldClients[i].AllowedIPs...)
  496. }
  497. if hit := wireguardAllowedIPsCollision(normalized, peers); hit != "" {
  498. return false, common.NewError("wireguard: allowedIPs entry already used by another client:", hit)
  499. }
  500. clients[0].AllowedIPs = normalized
  501. }
  502. }
  503. if clients[0].PreSharedKey == "" {
  504. clients[0].PreSharedKey = old.PreSharedKey
  505. }
  506. if clients[0].KeepAlive == 0 {
  507. clients[0].KeepAlive = old.KeepAlive
  508. }
  509. }
  510. var oldSettings map[string]any
  511. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  512. if err != nil {
  513. return false, err
  514. }
  515. settingsClients, _ := oldSettings["clients"].([]any)
  516. var preservedCreated any
  517. var preservedSubID string
  518. if clientIndex >= 0 && clientIndex < len(settingsClients) {
  519. if oldMap, ok := settingsClients[clientIndex].(map[string]any); ok {
  520. if v, ok2 := oldMap["created_at"]; ok2 {
  521. preservedCreated = v
  522. }
  523. preservedSubID, _ = oldMap["subId"].(string)
  524. }
  525. }
  526. if len(interfaceClients) > 0 {
  527. if newMap, ok := interfaceClients[0].(map[string]any); ok {
  528. if preservedCreated == nil {
  529. preservedCreated = time.Now().Unix() * 1000
  530. }
  531. newMap["created_at"] = preservedCreated
  532. newMap["updated_at"] = time.Now().Unix() * 1000
  533. newSub, _ := newMap["subId"].(string)
  534. if strings.TrimSpace(newSub) == "" {
  535. if strings.TrimSpace(preservedSubID) != "" {
  536. newMap["subId"] = preservedSubID
  537. } else {
  538. newMap["subId"] = random.NumLower(16)
  539. }
  540. }
  541. if oldInbound.Protocol == model.WireGuard {
  542. newMap["privateKey"] = clients[0].PrivateKey
  543. newMap["publicKey"] = clients[0].PublicKey
  544. newMap["allowedIPs"] = clients[0].AllowedIPs
  545. if clients[0].PreSharedKey != "" {
  546. newMap["preSharedKey"] = clients[0].PreSharedKey
  547. }
  548. if clients[0].KeepAlive > 0 {
  549. newMap["keepAlive"] = clients[0].KeepAlive
  550. }
  551. }
  552. interfaceClients[0] = newMap
  553. }
  554. }
  555. if oldInbound.Protocol == model.Shadowsocks {
  556. applyShadowsocksClientMethod(interfaceClients, oldSettings)
  557. }
  558. settingsClients[clientIndex] = interfaceClients[0]
  559. oldSettings["clients"] = settingsClients
  560. if oldInbound.Protocol == model.VLESS {
  561. hasVisionFlow := false
  562. for _, c := range settingsClients {
  563. cm, ok := c.(map[string]any)
  564. if !ok {
  565. continue
  566. }
  567. if flow, _ := cm["flow"].(string); flow == "xtls-rprx-vision" {
  568. hasVisionFlow = true
  569. break
  570. }
  571. }
  572. if !hasVisionFlow {
  573. delete(oldSettings, "testseed")
  574. }
  575. }
  576. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  577. if err != nil {
  578. return false, err
  579. }
  580. oldInbound.Settings = string(newSettings)
  581. needRestart := false
  582. // Resolve the push plan before the DB write so a node-state lookup failure
  583. // still aborts the whole update without committing anything (it used to roll
  584. // the transaction back). nodePushPlan only reads, so order doesn't matter.
  585. var rt runtime.Runtime
  586. var push bool
  587. if len(oldEmail) > 0 {
  588. var perr error
  589. rt, push, _, perr = inboundSvc.nodePushPlan(oldInbound)
  590. if perr != nil {
  591. return false, perr
  592. }
  593. }
  594. // Persist client stats + inbound atomically, serialized against the traffic
  595. // poll to avoid the cross-transaction lock-order deadlock (runSerializedTx).
  596. if txErr := runSerializedTx(func(tx *gorm.DB) error {
  597. if len(clients[0].Email) > 0 {
  598. if len(oldEmail) > 0 {
  599. emailUnchanged := strings.EqualFold(oldEmail, clients[0].Email)
  600. targetExists := int64(0)
  601. if !emailUnchanged {
  602. if e := tx.Model(xray.ClientTraffic{}).Where("email = ?", clients[0].Email).Count(&targetExists).Error; e != nil {
  603. return e
  604. }
  605. }
  606. if emailUnchanged || targetExists == 0 {
  607. if e := inboundSvc.UpdateClientStat(tx, oldEmail, &clients[0]); e != nil {
  608. return e
  609. }
  610. if e := inboundSvc.UpdateClientIPs(tx, oldEmail, clients[0].Email); e != nil {
  611. return e
  612. }
  613. } else {
  614. stillUsed, sErr := inboundSvc.emailUsedByOtherInbounds(oldEmail, data.Id)
  615. if sErr != nil {
  616. return sErr
  617. }
  618. if !stillUsed {
  619. if e := inboundSvc.DelClientStat(tx, oldEmail); e != nil {
  620. return e
  621. }
  622. if e := inboundSvc.DelClientIPs(tx, oldEmail); e != nil {
  623. return e
  624. }
  625. }
  626. if e := inboundSvc.UpdateClientStat(tx, clients[0].Email, &clients[0]); e != nil {
  627. return e
  628. }
  629. }
  630. } else {
  631. if e := inboundSvc.AddClientStat(tx, data.Id, &clients[0]); e != nil {
  632. return e
  633. }
  634. }
  635. } else {
  636. stillUsed, sErr := inboundSvc.emailUsedByOtherInbounds(oldEmail, data.Id)
  637. if sErr != nil {
  638. return sErr
  639. }
  640. if !stillUsed {
  641. if e := inboundSvc.DelClientStat(tx, oldEmail); e != nil {
  642. return e
  643. }
  644. if e := inboundSvc.DelClientIPs(tx, oldEmail); e != nil {
  645. return e
  646. }
  647. }
  648. }
  649. if e := tx.Save(oldInbound).Error; e != nil {
  650. return e
  651. }
  652. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  653. if gcErr != nil {
  654. return gcErr
  655. }
  656. if err := s.SyncInbound(tx, oldInbound.Id, finalClients); err != nil {
  657. return err
  658. }
  659. if oldInbound.NodeID != nil {
  660. return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID)
  661. }
  662. return nil
  663. }); txErr != nil {
  664. return false, txErr
  665. }
  666. // Apply to the running runtime after the DB is committed — outside the
  667. // serialized writer so a slow node call can't stall traffic accounting.
  668. if len(oldEmail) > 0 {
  669. if oldInbound.NodeID == nil {
  670. if !push {
  671. needRestart = true
  672. } else {
  673. if oldClients[clientIndex].Enable {
  674. err1 := rt.RemoveUser(context.Background(), oldInbound, oldEmail)
  675. if err1 == nil {
  676. logger.Debug("Old client deleted on", rt.Name(), ":", oldEmail)
  677. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", oldEmail)) {
  678. logger.Debug("User is already deleted. Nothing to do more...")
  679. } else {
  680. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  681. needRestart = true
  682. }
  683. }
  684. if clients[0].Enable {
  685. cipher := ""
  686. if oldInbound.Protocol == "shadowsocks" {
  687. cipher = oldSettings["method"].(string)
  688. }
  689. err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
  690. "email": clients[0].Email,
  691. "id": clients[0].ID,
  692. "security": clients[0].Security,
  693. "flow": clients[0].Flow,
  694. "auth": clients[0].Auth,
  695. "password": clients[0].Password,
  696. "cipher": cipher,
  697. "publicKey": clients[0].PublicKey,
  698. "allowedIPs": clients[0].AllowedIPs,
  699. "preSharedKey": clients[0].PreSharedKey,
  700. "keepAlive": keepAliveStr(clients[0].KeepAlive),
  701. })
  702. if err1 == nil {
  703. logger.Debug("Client edited on", rt.Name(), ":", clients[0].Email)
  704. } else {
  705. logger.Debug("Error in adding client on", rt.Name(), ":", err1)
  706. needRestart = true
  707. }
  708. }
  709. }
  710. } else if push {
  711. if err1 := rt.UpdateUser(context.Background(), oldInbound, oldEmail, clients[0]); err1 != nil {
  712. logger.Warning("Error in updating client on", rt.Name(), ":", err1)
  713. }
  714. }
  715. } else {
  716. logger.Debug("Client old email not found")
  717. needRestart = true
  718. }
  719. return needRestart, nil
  720. }
  721. func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inboundId int, email string, keepTraffic bool) (bool, error) {
  722. defer lockInbound(inboundId).Unlock()
  723. oldInbound, err := inboundSvc.GetInbound(inboundId)
  724. if err != nil {
  725. logger.Error("Load Old Data Error")
  726. return false, err
  727. }
  728. var settings map[string]any
  729. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  730. return false, err
  731. }
  732. interfaceClients, ok := settings["clients"].([]any)
  733. if !ok {
  734. return false, common.NewError("invalid clients format in inbound settings")
  735. }
  736. var newClients []any
  737. needApiDel := false
  738. found := false
  739. for _, client := range interfaceClients {
  740. c, ok := client.(map[string]any)
  741. if !ok {
  742. continue
  743. }
  744. if cEmail, ok := c["email"].(string); ok && cEmail == email {
  745. found = true
  746. needApiDel, _ = c["enable"].(bool)
  747. } else {
  748. newClients = append(newClients, client)
  749. }
  750. }
  751. if !found {
  752. return false, fmt.Errorf("%w for email: %s", ErrClientNotInInbound, email)
  753. }
  754. db := database.GetDB()
  755. newClients = compactOrphans(db, newClients)
  756. if newClients == nil {
  757. newClients = []any{}
  758. }
  759. settings["clients"] = newClients
  760. newSettings, err := json.MarshalIndent(settings, "", " ")
  761. if err != nil {
  762. return false, err
  763. }
  764. oldInbound.Settings = string(newSettings)
  765. emailShared, err := inboundSvc.emailUsedByOtherInbounds(email, inboundId)
  766. if err != nil {
  767. return false, err
  768. }
  769. needRestart := false
  770. // Decide what to delete and the push plan before the serialized DB write —
  771. // these are reads, and nodePushPlan failing should abort before committing.
  772. delStat := false
  773. if len(email) > 0 && !emailShared && !keepTraffic {
  774. traffic, tErr := inboundSvc.GetClientTrafficByEmail(email)
  775. if tErr != nil {
  776. return false, tErr
  777. }
  778. delStat = traffic != nil
  779. }
  780. // The runtime user is scoped to this inbound's tag + email, so the push plan
  781. // is resolved independently of emailShared — a sibling inbound still carrying
  782. // the email must not suppress removing the user from this inbound's Xray.
  783. var rt runtime.Runtime
  784. var push bool
  785. if len(email) > 0 && (oldInbound.NodeID != nil || needApiDel) {
  786. r, p, _, perr := inboundSvc.nodePushPlan(oldInbound)
  787. if perr != nil {
  788. return false, perr
  789. }
  790. rt, push = r, p
  791. }
  792. // Persist the deletion atomically, serialized against the traffic poll to
  793. // avoid the cross-transaction lock-order deadlock (runSerializedTx).
  794. if txErr := runSerializedTx(func(tx *gorm.DB) error {
  795. if !emailShared && !keepTraffic {
  796. if e := inboundSvc.DelClientIPs(tx, email); e != nil {
  797. logger.Error("Error in delete client IPs")
  798. return e
  799. }
  800. }
  801. if delStat {
  802. if e := inboundSvc.DelClientStat(tx, email); e != nil {
  803. logger.Error("Delete stats Data Error")
  804. return e
  805. }
  806. }
  807. if e := tx.Save(oldInbound).Error; e != nil {
  808. return e
  809. }
  810. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  811. if gcErr != nil {
  812. return gcErr
  813. }
  814. if err := s.SyncInbound(tx, inboundId, finalClients); err != nil {
  815. return err
  816. }
  817. if oldInbound.NodeID != nil {
  818. return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID)
  819. }
  820. return nil
  821. }); txErr != nil {
  822. return false, txErr
  823. }
  824. // Apply the runtime delete after commit — outside the serialized writer so a
  825. // slow node call can't stall traffic accounting. Independent of emailShared:
  826. // Xray users are keyed by inbound tag, so the user must be removed from this
  827. // inbound's runtime even when the same email survives in another inbound.
  828. if len(email) > 0 {
  829. if oldInbound.NodeID == nil {
  830. // Local inbound: a disabled client isn't in the running Xray, so only
  831. // a live one (needApiDel) needs an API removal.
  832. if needApiDel {
  833. if !push {
  834. needRestart = true
  835. } else if err1 := rt.RemoveUser(context.Background(), oldInbound, email); err1 == nil {
  836. logger.Debug("Client deleted on", rt.Name(), ":", email)
  837. needRestart = false
  838. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  839. logger.Debug("User is already deleted. Nothing to do more...")
  840. } else {
  841. logger.Debug("Error in deleting client on", rt.Name(), ":", email)
  842. needRestart = true
  843. }
  844. }
  845. } else {
  846. // Node inbound: propagate the delete regardless of the enable flag —
  847. // the node's own DB still carries a disabled client and would
  848. // resurrect it on the next snapshot otherwise.
  849. if push {
  850. if err1 := rt.DeleteUser(context.Background(), oldInbound, email); err1 != nil {
  851. logger.Warning("Error in deleting client on", rt.Name(), ":", err1)
  852. }
  853. }
  854. }
  855. }
  856. return needRestart, nil
  857. }
  858. func (s *ClientService) SetClientTelegramUserID(inboundSvc *InboundService, trafficId int, tgId int64) (bool, error) {
  859. traffic, inbound, err := inboundSvc.GetClientInboundByTrafficID(trafficId)
  860. if err != nil {
  861. return false, err
  862. }
  863. if inbound == nil {
  864. return false, common.NewError("Inbound Not Found For Traffic ID:", trafficId)
  865. }
  866. clientEmail := traffic.Email
  867. oldClients, err := inboundSvc.GetClients(inbound)
  868. if err != nil {
  869. return false, err
  870. }
  871. found := false
  872. for _, oldClient := range oldClients {
  873. if oldClient.Email == clientEmail {
  874. found = true
  875. break
  876. }
  877. }
  878. if !found {
  879. return false, common.NewError("Client Not Found For Email:", clientEmail)
  880. }
  881. var settings map[string]any
  882. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  883. if err != nil {
  884. return false, err
  885. }
  886. clients := settings["clients"].([]any)
  887. var newClients []any
  888. for client_index := range clients {
  889. c := clients[client_index].(map[string]any)
  890. if c["email"] == clientEmail {
  891. c["tgId"] = tgId
  892. c["updated_at"] = time.Now().Unix() * 1000
  893. newClients = append(newClients, any(c))
  894. }
  895. }
  896. settings["clients"] = newClients
  897. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  898. if err != nil {
  899. return false, err
  900. }
  901. inbound.Settings = string(modifiedSettings)
  902. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientEmail)
  903. return needRestart, err
  904. }
  905. func (s *ClientService) CheckIsEnabledByEmail(inboundSvc *InboundService, clientEmail string) (bool, error) {
  906. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  907. if err != nil {
  908. return false, err
  909. }
  910. if inbound == nil {
  911. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  912. }
  913. clients, err := inboundSvc.GetClients(inbound)
  914. if err != nil {
  915. return false, err
  916. }
  917. isEnable := false
  918. for _, client := range clients {
  919. if client.Email == clientEmail {
  920. isEnable = client.Enable
  921. break
  922. }
  923. }
  924. return isEnable, err
  925. }
  926. func (s *ClientService) ToggleClientEnableByEmail(inboundSvc *InboundService, clientEmail string) (bool, bool, error) {
  927. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  928. if err != nil {
  929. return false, false, err
  930. }
  931. if inbound == nil {
  932. return false, false, common.NewError("Inbound Not Found For Email:", clientEmail)
  933. }
  934. oldClients, err := inboundSvc.GetClients(inbound)
  935. if err != nil {
  936. return false, false, err
  937. }
  938. found := false
  939. clientOldEnabled := false
  940. for _, oldClient := range oldClients {
  941. if oldClient.Email == clientEmail {
  942. found = true
  943. clientOldEnabled = oldClient.Enable
  944. break
  945. }
  946. }
  947. if !found {
  948. return false, false, common.NewError("Client Not Found For Email:", clientEmail)
  949. }
  950. var settings map[string]any
  951. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  952. if err != nil {
  953. return false, false, err
  954. }
  955. clients := settings["clients"].([]any)
  956. var newClients []any
  957. for client_index := range clients {
  958. c := clients[client_index].(map[string]any)
  959. if c["email"] == clientEmail {
  960. c["enable"] = !clientOldEnabled
  961. c["updated_at"] = time.Now().Unix() * 1000
  962. newClients = append(newClients, any(c))
  963. }
  964. }
  965. settings["clients"] = newClients
  966. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  967. if err != nil {
  968. return false, false, err
  969. }
  970. inbound.Settings = string(modifiedSettings)
  971. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientEmail)
  972. if err != nil {
  973. return false, needRestart, err
  974. }
  975. return !clientOldEnabled, needRestart, nil
  976. }
  977. func (s *ClientService) SetClientEnableByEmail(inboundSvc *InboundService, clientEmail string, enable bool) (bool, bool, error) {
  978. current, err := s.CheckIsEnabledByEmail(inboundSvc, clientEmail)
  979. if err != nil {
  980. return false, false, err
  981. }
  982. if current == enable {
  983. return false, false, nil
  984. }
  985. newEnabled, needRestart, err := s.ToggleClientEnableByEmail(inboundSvc, clientEmail)
  986. if err != nil {
  987. return false, needRestart, err
  988. }
  989. return newEnabled == enable, needRestart, nil
  990. }
  991. // applyClientFieldByEmail loads the inbound currently hosting clientEmail,
  992. // confirms the client exists, applies mutate to the matching client (plus a
  993. // refreshed updated_at), and hands a single-client update payload to
  994. // UpdateInboundClient. The rebuilt clients array intentionally contains only
  995. // the matched client — that is the input contract UpdateInboundClient expects
  996. // (clients[0] is the new data; clientEmail locates the row to replace). It
  997. // backs the single-field by-email setters below.
  998. // applyClientFieldByEmail mutates a client field on every inbound the email is
  999. // attached to. A multi-inbound client is one logical identity: patching only
  1000. // the first inbound's JSON would leave the siblings stale, and the next
  1001. // SyncInbound over a stale sibling would revert the edit in the normalized
  1002. // records (#5039).
  1003. func (s *ClientService) applyClientFieldByEmail(inboundSvc *InboundService, clientEmail string, mutate func(c map[string]any)) (bool, error) {
  1004. inboundIds, err := s.GetInboundIdsForEmail(database.GetDB(), clientEmail)
  1005. if err != nil {
  1006. return false, err
  1007. }
  1008. if len(inboundIds) == 0 {
  1009. // Legacy fallback for clients that only live in the inbound JSON and
  1010. // were never normalized into client_inbounds.
  1011. _, inbound, gErr := inboundSvc.GetClientInboundByEmail(clientEmail)
  1012. if gErr != nil {
  1013. return false, gErr
  1014. }
  1015. if inbound == nil {
  1016. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1017. }
  1018. inboundIds = []int{inbound.Id}
  1019. }
  1020. needRestart := false
  1021. found := false
  1022. for _, ibId := range inboundIds {
  1023. inbound, gErr := inboundSvc.GetInbound(ibId)
  1024. if gErr != nil {
  1025. return needRestart, gErr
  1026. }
  1027. var settings map[string]any
  1028. if uErr := json.Unmarshal([]byte(inbound.Settings), &settings); uErr != nil {
  1029. return needRestart, uErr
  1030. }
  1031. clients, _ := settings["clients"].([]any)
  1032. // UpdateInboundClient expects a single-client payload, so keep only the
  1033. // matching entry in the scratch copy; it splices the result back into
  1034. // the inbound's full client list itself.
  1035. var newClients []any
  1036. for client_index := range clients {
  1037. c, ok := clients[client_index].(map[string]any)
  1038. if !ok {
  1039. continue
  1040. }
  1041. if c["email"] == clientEmail {
  1042. mutate(c)
  1043. c["updated_at"] = time.Now().Unix() * 1000
  1044. newClients = append(newClients, any(c))
  1045. }
  1046. }
  1047. if len(newClients) == 0 {
  1048. continue
  1049. }
  1050. found = true
  1051. settings["clients"] = newClients
  1052. modifiedSettings, mErr := json.MarshalIndent(settings, "", " ")
  1053. if mErr != nil {
  1054. return needRestart, mErr
  1055. }
  1056. inbound.Settings = string(modifiedSettings)
  1057. nr, uErr := s.UpdateInboundClient(inboundSvc, inbound, clientEmail)
  1058. if uErr != nil {
  1059. return needRestart, uErr
  1060. }
  1061. needRestart = needRestart || nr
  1062. }
  1063. if !found {
  1064. return needRestart, common.NewError("Client Not Found For Email:", clientEmail)
  1065. }
  1066. return needRestart, nil
  1067. }
  1068. func (s *ClientService) ResetClientIpLimitByEmail(inboundSvc *InboundService, clientEmail string, count int) (bool, error) {
  1069. return s.applyClientFieldByEmail(inboundSvc, clientEmail, func(c map[string]any) {
  1070. c["limitIp"] = count
  1071. })
  1072. }
  1073. func (s *ClientService) ResetClientExpiryTimeByEmail(inboundSvc *InboundService, clientEmail string, expiry_time int64) (bool, error) {
  1074. return s.applyClientFieldByEmail(inboundSvc, clientEmail, func(c map[string]any) {
  1075. c["expiryTime"] = expiry_time
  1076. })
  1077. }
  1078. func (s *ClientService) ResetClientTrafficLimitByEmail(inboundSvc *InboundService, clientEmail string, totalGB int) (bool, error) {
  1079. if totalGB < 0 {
  1080. return false, common.NewError("totalGB must be >= 0")
  1081. }
  1082. return s.applyClientFieldByEmail(inboundSvc, clientEmail, func(c map[string]any) {
  1083. c["totalGB"] = totalGB * 1024 * 1024 * 1024
  1084. })
  1085. }