client_inbound_apply.go 34 KB

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