client_crud.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  1. package service
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "strings"
  8. "time"
  9. "github.com/google/uuid"
  10. "github.com/mhsanaei/3x-ui/v3/internal/database"
  11. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  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/xray"
  15. "gorm.io/gorm"
  16. )
  17. func hasForbiddenClientChar(s string) bool {
  18. for _, r := range s {
  19. if r == '/' || r == '\\' || r == ' ' || r < 0x20 || r == 0x7f {
  20. return true
  21. }
  22. }
  23. return false
  24. }
  25. func validateClientEmail(email string) error {
  26. if hasForbiddenClientChar(email) {
  27. return common.NewError("client email contains an invalid character:", email)
  28. }
  29. return nil
  30. }
  31. func validateClientSubID(subID string) error {
  32. if hasForbiddenClientChar(subID) {
  33. return common.NewError("client subId contains an invalid character:", subID)
  34. }
  35. return nil
  36. }
  37. func (s *ClientService) Create(inboundSvc *InboundService, payload *ClientCreatePayload) (bool, error) {
  38. if payload == nil {
  39. return false, common.NewError("empty payload")
  40. }
  41. client := payload.Client
  42. if strings.TrimSpace(client.Email) == "" {
  43. return false, common.NewError("client email is required")
  44. }
  45. if err := validateClientEmail(client.Email); err != nil {
  46. return false, err
  47. }
  48. if err := validateClientSubID(client.SubID); err != nil {
  49. return false, err
  50. }
  51. if len(payload.InboundIds) == 0 {
  52. return false, common.NewError("at least one inbound is required")
  53. }
  54. if client.SubID == "" {
  55. client.SubID = uuid.NewString()
  56. }
  57. if !client.Enable {
  58. client.Enable = true
  59. }
  60. now := time.Now().UnixMilli()
  61. if client.CreatedAt == 0 {
  62. client.CreatedAt = now
  63. }
  64. client.UpdatedAt = now
  65. existing := &model.ClientRecord{}
  66. err := database.GetDB().Where("email = ?", client.Email).First(existing).Error
  67. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  68. return false, err
  69. }
  70. emailTaken := !errors.Is(err, gorm.ErrRecordNotFound)
  71. if emailTaken {
  72. if existing.SubID == "" || existing.SubID != client.SubID {
  73. return false, common.NewError("email already in use:", client.Email)
  74. }
  75. // Reuse stored credentials when re-adding an existing identity, or
  76. // fillProtocolDefaults mints a fresh UUID that desyncs other inbounds.
  77. if client.ID == "" {
  78. client.ID = existing.UUID
  79. }
  80. if client.Password == "" {
  81. client.Password = existing.Password
  82. }
  83. if client.Auth == "" {
  84. client.Auth = existing.Auth
  85. }
  86. if client.Secret == "" {
  87. client.Secret = existing.Secret
  88. }
  89. }
  90. if client.SubID != "" {
  91. var subTaken int64
  92. if err := database.GetDB().Model(&model.ClientRecord{}).
  93. Where("sub_id = ? AND email <> ?", client.SubID, client.Email).
  94. Count(&subTaken).Error; err != nil {
  95. return false, err
  96. }
  97. if subTaken > 0 {
  98. return false, common.NewError("subId already in use:", client.SubID)
  99. }
  100. }
  101. needRestart := false
  102. for _, ibId := range payload.InboundIds {
  103. inbound, getErr := inboundSvc.GetInbound(ibId)
  104. if getErr != nil {
  105. return needRestart, getErr
  106. }
  107. if err := s.fillProtocolDefaults(&client, inbound); err != nil {
  108. return needRestart, err
  109. }
  110. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(client, inbound)}})
  111. if mErr != nil {
  112. return needRestart, mErr
  113. }
  114. nr, addErr := s.AddInboundClient(inboundSvc, &model.Inbound{
  115. Id: ibId,
  116. Settings: string(settingsPayload),
  117. })
  118. if addErr != nil {
  119. return needRestart, addErr
  120. }
  121. if nr {
  122. needRestart = true
  123. }
  124. }
  125. return needRestart, nil
  126. }
  127. func (s *ClientService) fillProtocolDefaults(c *model.Client, ib *model.Inbound) error {
  128. switch ib.Protocol {
  129. case model.VMESS, model.VLESS:
  130. if c.ID == "" {
  131. c.ID = uuid.NewString()
  132. }
  133. case model.Trojan:
  134. if c.Password == "" {
  135. c.Password = strings.ReplaceAll(uuid.NewString(), "-", "")
  136. }
  137. case model.Shadowsocks:
  138. method := shadowsocksMethodFromSettings(ib.Settings)
  139. if c.Password == "" || !validShadowsocksClientKey(method, c.Password) {
  140. c.Password = randomShadowsocksClientKey(method)
  141. }
  142. case model.Hysteria:
  143. if c.Auth == "" {
  144. c.Auth = strings.ReplaceAll(uuid.NewString(), "-", "")
  145. }
  146. case model.MTProto:
  147. if c.Secret == "" {
  148. c.Secret = model.GenerateFakeTLSSecret(mtprotoDomainFromSettings(ib.Settings))
  149. }
  150. }
  151. return nil
  152. }
  153. // defaultMtprotoDomain is the FakeTLS fronting domain used when an mtproto
  154. // inbound carries no fakeTlsDomain of its own; it mirrors the frontend default.
  155. const defaultMtprotoDomain = "www.cloudflare.com"
  156. // mtprotoDomainFromSettings returns the inbound-level FakeTLS domain, falling
  157. // back to the default when unset, so a generated client secret always fronts a
  158. // real hostname.
  159. func mtprotoDomainFromSettings(settings string) string {
  160. domain := ""
  161. if settings != "" {
  162. var m map[string]any
  163. if err := json.Unmarshal([]byte(settings), &m); err == nil {
  164. domain, _ = m["fakeTlsDomain"].(string)
  165. }
  166. }
  167. domain = strings.TrimSpace(domain)
  168. if domain == "" {
  169. return defaultMtprotoDomain
  170. }
  171. return domain
  172. }
  173. func clientWithInboundFlow(c model.Client, ib *model.Inbound) model.Client {
  174. if !inboundCanEnableTlsFlow(string(ib.Protocol), ib.StreamSettings, ib.Settings) {
  175. c.Flow = ""
  176. }
  177. return c
  178. }
  179. func shadowsocksMethodFromSettings(settings string) string {
  180. if settings == "" {
  181. return ""
  182. }
  183. var m map[string]any
  184. if err := json.Unmarshal([]byte(settings), &m); err != nil {
  185. return ""
  186. }
  187. method, _ := m["method"].(string)
  188. return method
  189. }
  190. func randomShadowsocksClientKey(method string) string {
  191. if n := shadowsocksKeyBytes(method); n > 0 {
  192. return random.Base64Bytes(n)
  193. }
  194. return strings.ReplaceAll(uuid.NewString(), "-", "")
  195. }
  196. func validShadowsocksClientKey(method, key string) bool {
  197. n := shadowsocksKeyBytes(method)
  198. if n == 0 {
  199. return key != ""
  200. }
  201. decoded, err := base64.StdEncoding.DecodeString(key)
  202. if err != nil {
  203. return false
  204. }
  205. return len(decoded) == n
  206. }
  207. func shadowsocksKeyBytes(method string) int {
  208. switch method {
  209. case "2022-blake3-aes-128-gcm":
  210. return 16
  211. case "2022-blake3-aes-256-gcm", "2022-blake3-chacha20-poly1305":
  212. return 32
  213. }
  214. return 0
  215. }
  216. // normalizeShadowsocksClientKeys rewrites any Shadowsocks-2022 client password
  217. // whose decoded length no longer matches settings.method, which happens after the
  218. // inbound method is switched between ciphers of different key sizes (e.g.
  219. // aes-256↔aes-128). A wrong-length uPSK makes xray reject the user, so the link
  220. // fails to connect; regenerating restores a valid key (clients must re-fetch).
  221. // Non-Shadowsocks / legacy-SS settings pass through unchanged.
  222. func normalizeShadowsocksClientKeys(settings string) (string, bool) {
  223. method := shadowsocksMethodFromSettings(settings)
  224. if shadowsocksKeyBytes(method) == 0 {
  225. return settings, false
  226. }
  227. var m map[string]any
  228. if err := json.Unmarshal([]byte(settings), &m); err != nil {
  229. return settings, false
  230. }
  231. clients, ok := m["clients"].([]any)
  232. if !ok {
  233. return settings, false
  234. }
  235. changed := false
  236. for i := range clients {
  237. c, ok := clients[i].(map[string]any)
  238. if !ok {
  239. continue
  240. }
  241. if pw, _ := c["password"].(string); validShadowsocksClientKey(method, pw) {
  242. continue
  243. }
  244. c["password"] = randomShadowsocksClientKey(method)
  245. clients[i] = c
  246. changed = true
  247. }
  248. if !changed {
  249. return settings, false
  250. }
  251. m["clients"] = clients
  252. bs, err := json.MarshalIndent(m, "", " ")
  253. if err != nil {
  254. return settings, false
  255. }
  256. return string(bs), true
  257. }
  258. func applyShadowsocksClientMethod(clients []any, settings map[string]any) {
  259. method, _ := settings["method"].(string)
  260. is2022 := strings.HasPrefix(method, "2022-blake3-")
  261. for i := range clients {
  262. cm, ok := clients[i].(map[string]any)
  263. if !ok {
  264. continue
  265. }
  266. if is2022 {
  267. if _, hasKey := cm["method"]; hasKey {
  268. delete(cm, "method")
  269. clients[i] = cm
  270. }
  271. continue
  272. }
  273. if method == "" {
  274. continue
  275. }
  276. if existing, _ := cm["method"].(string); existing != "" {
  277. continue
  278. }
  279. cm["method"] = method
  280. clients[i] = cm
  281. }
  282. }
  283. func (s *ClientService) Update(inboundSvc *InboundService, id int, updated model.Client, inboundFilter ...int) (bool, error) {
  284. existing, err := s.GetByID(id)
  285. if err != nil {
  286. return false, err
  287. }
  288. inboundIds, err := s.GetInboundIdsForRecord(id)
  289. if err != nil {
  290. return false, err
  291. }
  292. if len(inboundFilter) > 0 {
  293. allow := make(map[int]struct{}, len(inboundFilter))
  294. for _, fid := range inboundFilter {
  295. allow[fid] = struct{}{}
  296. }
  297. filtered := inboundIds[:0:0]
  298. for _, ibId := range inboundIds {
  299. if _, ok := allow[ibId]; ok {
  300. filtered = append(filtered, ibId)
  301. }
  302. }
  303. inboundIds = filtered
  304. }
  305. if strings.TrimSpace(updated.Email) == "" {
  306. return false, common.NewError("client email is required")
  307. }
  308. if err := validateClientEmail(updated.Email); err != nil {
  309. return false, err
  310. }
  311. if err := validateClientSubID(updated.SubID); err != nil {
  312. return false, err
  313. }
  314. if updated.SubID == "" {
  315. updated.SubID = existing.SubID
  316. }
  317. if updated.SubID == "" {
  318. updated.SubID = uuid.NewString()
  319. }
  320. updated.UpdatedAt = time.Now().UnixMilli()
  321. if updated.CreatedAt == 0 {
  322. updated.CreatedAt = existing.CreatedAt
  323. }
  324. // Preserve existing credentials when the caller omits them, so a partial
  325. // update (e.g. only changing traffic/expiry) doesn't silently rotate the
  326. // client's UUID/password/auth via fillProtocolDefaults. Supplying a new
  327. // value still rotates it intentionally.
  328. if updated.ID == "" {
  329. updated.ID = existing.UUID
  330. }
  331. if updated.Password == "" {
  332. updated.Password = existing.Password
  333. }
  334. if updated.Auth == "" {
  335. updated.Auth = existing.Auth
  336. }
  337. if updated.Secret == "" {
  338. updated.Secret = existing.Secret
  339. }
  340. if updated.Email != existing.Email {
  341. var collisionCount int64
  342. if err := database.GetDB().Model(&model.ClientRecord{}).
  343. Where("email = ? AND id <> ?", updated.Email, id).
  344. Count(&collisionCount).Error; err != nil {
  345. return false, err
  346. }
  347. if collisionCount > 0 {
  348. return false, common.NewError("Duplicate email:", updated.Email)
  349. }
  350. if err := database.GetDB().Model(&model.ClientRecord{}).
  351. Where("id = ?", id).
  352. Update("email", updated.Email).Error; err != nil {
  353. return false, err
  354. }
  355. }
  356. if updated.SubID != "" {
  357. var subCollision int64
  358. if err := database.GetDB().Model(&model.ClientRecord{}).
  359. Where("sub_id = ? AND id <> ?", updated.SubID, id).
  360. Count(&subCollision).Error; err != nil {
  361. return false, err
  362. }
  363. if subCollision > 0 {
  364. return false, common.NewError("Duplicate subId:", updated.SubID)
  365. }
  366. }
  367. needRestart := false
  368. for _, ibId := range inboundIds {
  369. inbound, getErr := inboundSvc.GetInbound(ibId)
  370. if getErr != nil {
  371. if errors.Is(getErr, gorm.ErrRecordNotFound) {
  372. if err := database.GetDB().
  373. Where("client_id = ? AND inbound_id = ?", id, ibId).
  374. Delete(&model.ClientInbound{}).Error; err != nil {
  375. return needRestart, err
  376. }
  377. continue
  378. }
  379. return needRestart, getErr
  380. }
  381. if existing.Email == "" {
  382. continue
  383. }
  384. if err := s.fillProtocolDefaults(&updated, inbound); err != nil {
  385. return needRestart, err
  386. }
  387. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(updated, inbound)}})
  388. if mErr != nil {
  389. return needRestart, mErr
  390. }
  391. nr, upErr := s.UpdateInboundClient(inboundSvc, &model.Inbound{
  392. Id: ibId,
  393. Settings: string(settingsPayload),
  394. }, existing.Email)
  395. if upErr != nil {
  396. return needRestart, upErr
  397. }
  398. if nr {
  399. needRestart = true
  400. }
  401. }
  402. reverseStr := ""
  403. if updated.Reverse != nil && strings.TrimSpace(updated.Reverse.Tag) != "" {
  404. if b, mErr := json.Marshal(updated.Reverse); mErr == nil {
  405. reverseStr = string(b)
  406. }
  407. }
  408. if err := database.GetDB().Model(&model.ClientRecord{}).
  409. Where("id = ?", id).
  410. Update("reverse", reverseStr).Error; err != nil {
  411. return needRestart, err
  412. }
  413. // Persist the group explicitly. SyncInbound deliberately preserves the
  414. // stored group when the inbound settings carry none — so a node snapshot or a
  415. // group-less settings rebuild can't wipe it (see SyncInbound + its tests).
  416. // That guard also meant clearing the group in the client editor never took
  417. // effect. The editor always round-trips the field, so apply it here,
  418. // including the empty string that removes the client from its group.
  419. if err := database.GetDB().Model(&model.ClientRecord{}).
  420. Where("id = ?", id).
  421. UpdateColumn("group_name", updated.Group).Error; err != nil {
  422. return needRestart, err
  423. }
  424. // Same shape as the group write above: SyncInbound keeps a stored ad-tag
  425. // when the incoming settings carry none, so clearing the override must be
  426. // applied here, where the editor always round-trips the field.
  427. if err := database.GetDB().Model(&model.ClientRecord{}).
  428. Where("id = ?", id).
  429. UpdateColumn("ad_tag", updated.AdTag).Error; err != nil {
  430. return needRestart, err
  431. }
  432. if err := database.GetDB().Model(&model.ClientRecord{}).
  433. Where("id = ?", id).
  434. UpdateColumn("enable", updated.Enable).Error; err != nil {
  435. return needRestart, err
  436. }
  437. if err := database.GetDB().Model(&model.ClientRecord{}).
  438. Where("id = ?", id).
  439. UpdateColumn("updated_at", time.Now().UnixMilli()).Error; err != nil {
  440. return needRestart, err
  441. }
  442. return needRestart, nil
  443. }
  444. func (s *ClientService) Delete(inboundSvc *InboundService, id int, keepTraffic bool) (bool, error) {
  445. existing, err := s.GetByID(id)
  446. if err != nil {
  447. return false, err
  448. }
  449. tombstoneClientEmail(existing.Email)
  450. inboundIds, err := s.GetInboundIdsForRecord(id)
  451. if err != nil {
  452. return false, err
  453. }
  454. needRestart := false
  455. for _, ibId := range inboundIds {
  456. if _, getErr := inboundSvc.GetInbound(ibId); getErr != nil {
  457. if errors.Is(getErr, gorm.ErrRecordNotFound) {
  458. continue
  459. }
  460. return needRestart, getErr
  461. }
  462. // Always delete by email — the client's stable identity. This removes
  463. // every matching entry from the inbound's settings even when the stored
  464. // credential (UUID/password/auth) drifted from the inbound JSON, or a
  465. // duplicate entry with the same email exists.
  466. if existing.Email == "" {
  467. continue
  468. }
  469. nr, delErr := s.DelInboundClientByEmail(inboundSvc, ibId, existing.Email, false, true)
  470. if delErr != nil {
  471. // The client is already absent from this inbound (data drift or a
  472. // retried delete). Skip it — deletion stays idempotent.
  473. if errors.Is(delErr, ErrClientNotInInbound) {
  474. continue
  475. }
  476. return needRestart, delErr
  477. }
  478. if nr {
  479. needRestart = true
  480. }
  481. }
  482. db := database.GetDB()
  483. if err := db.Transaction(func(tx *gorm.DB) error {
  484. if existing.Email != "" {
  485. if err := adjustGroupBaselinesForRemovedTraffic(tx, []string{existing.Email}); err != nil {
  486. return err
  487. }
  488. }
  489. if err := tx.Where("client_id = ?", id).Delete(&model.ClientInbound{}).Error; err != nil {
  490. return err
  491. }
  492. if err := tx.Where("client_id = ?", id).Delete(&model.ClientExternalLink{}).Error; err != nil {
  493. return err
  494. }
  495. if !keepTraffic && existing.Email != "" {
  496. if err := tx.Where("email = ?", existing.Email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  497. return err
  498. }
  499. if err := clearGlobalTraffic(tx, existing.Email); err != nil {
  500. return err
  501. }
  502. if err := tx.Where("client_email = ?", existing.Email).Delete(&model.InboundClientIps{}).Error; err != nil {
  503. return err
  504. }
  505. if err := tx.Where("email = ?", existing.Email).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  506. return err
  507. }
  508. }
  509. return tx.Delete(&model.ClientRecord{}, id).Error
  510. }); err != nil {
  511. return needRestart, err
  512. }
  513. return needRestart, nil
  514. }
  515. func (s *ClientService) Attach(inboundSvc *InboundService, id int, inboundIds []int) (bool, error) {
  516. existing, err := s.GetByID(id)
  517. if err != nil {
  518. return false, err
  519. }
  520. currentIds, err := s.GetInboundIdsForRecord(id)
  521. if err != nil {
  522. return false, err
  523. }
  524. have := make(map[int]struct{}, len(currentIds))
  525. for _, x := range currentIds {
  526. have[x] = struct{}{}
  527. }
  528. clientWire := existing.ToClient()
  529. flow, ffErr := s.EffectiveFlow(nil, id)
  530. if ffErr != nil {
  531. return false, ffErr
  532. }
  533. clientWire.Flow = flow
  534. clientWire.UpdatedAt = time.Now().UnixMilli()
  535. needRestart := false
  536. for _, ibId := range inboundIds {
  537. if _, attached := have[ibId]; attached {
  538. continue
  539. }
  540. inbound, getErr := inboundSvc.GetInbound(ibId)
  541. if getErr != nil {
  542. return needRestart, getErr
  543. }
  544. copyClient := *clientWire
  545. if err := s.fillProtocolDefaults(&copyClient, inbound); err != nil {
  546. return needRestart, err
  547. }
  548. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(copyClient, inbound)}})
  549. if mErr != nil {
  550. return needRestart, mErr
  551. }
  552. nr, addErr := s.AddInboundClient(inboundSvc, &model.Inbound{
  553. Id: ibId,
  554. Settings: string(settingsPayload),
  555. })
  556. if addErr != nil {
  557. return needRestart, addErr
  558. }
  559. if nr {
  560. needRestart = true
  561. }
  562. }
  563. return needRestart, nil
  564. }
  565. func (s *ClientService) CreateOne(inboundSvc *InboundService, inboundId int, client model.Client) (bool, error) {
  566. return s.Create(inboundSvc, &ClientCreatePayload{
  567. Client: client,
  568. InboundIds: []int{inboundId},
  569. })
  570. }
  571. func (s *ClientService) DetachByEmail(inboundSvc *InboundService, inboundId int, email string) (bool, error) {
  572. if email == "" {
  573. return false, common.NewError("client email is required")
  574. }
  575. rec, err := s.GetRecordByEmail(nil, email)
  576. if err != nil {
  577. return false, err
  578. }
  579. return s.Detach(inboundSvc, rec.Id, []int{inboundId})
  580. }
  581. func (s *ClientService) AttachByEmail(inboundSvc *InboundService, email string, inboundIds []int) (bool, error) {
  582. if email == "" {
  583. return false, common.NewError("client email is required")
  584. }
  585. rec, err := s.GetRecordByEmail(nil, email)
  586. if err != nil {
  587. return false, err
  588. }
  589. return s.Attach(inboundSvc, rec.Id, inboundIds)
  590. }
  591. func (s *ClientService) DetachByEmailMany(inboundSvc *InboundService, email string, inboundIds []int) (bool, error) {
  592. if email == "" {
  593. return false, common.NewError("client email is required")
  594. }
  595. rec, err := s.GetRecordByEmail(nil, email)
  596. if err != nil {
  597. return false, err
  598. }
  599. return s.Detach(inboundSvc, rec.Id, inboundIds)
  600. }
  601. func (s *ClientService) DeleteByEmail(inboundSvc *InboundService, email string, keepTraffic bool) (bool, error) {
  602. if email == "" {
  603. return false, common.NewError("client email is required")
  604. }
  605. rec, err := s.GetRecordByEmail(nil, email)
  606. if err == nil {
  607. return s.Delete(inboundSvc, rec.Id, keepTraffic)
  608. }
  609. if !errors.Is(err, gorm.ErrRecordNotFound) {
  610. return false, err
  611. }
  612. inboundIds, idsErr := s.findInboundIdsByClientEmail(email)
  613. if idsErr != nil {
  614. return false, idsErr
  615. }
  616. if len(inboundIds) == 0 {
  617. return false, common.NewError(fmt.Sprintf("client %q not found in any inbound or client record", email))
  618. }
  619. needRestart := false
  620. for _, ibId := range inboundIds {
  621. nr, delErr := s.DelInboundClientByEmail(inboundSvc, ibId, email, false, true)
  622. if delErr != nil {
  623. if errors.Is(delErr, ErrClientNotInInbound) {
  624. continue
  625. }
  626. return needRestart, delErr
  627. }
  628. if nr {
  629. needRestart = true
  630. }
  631. }
  632. if !keepTraffic {
  633. db := database.GetDB()
  634. if err := db.Where("email = ?", email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  635. return needRestart, err
  636. }
  637. if err := clearGlobalTraffic(db, email); err != nil {
  638. return needRestart, err
  639. }
  640. if err := db.Where("client_email = ?", email).Delete(&model.InboundClientIps{}).Error; err != nil {
  641. return needRestart, err
  642. }
  643. if err := db.Where("email = ?", email).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  644. return needRestart, err
  645. }
  646. }
  647. return needRestart, nil
  648. }
  649. func (s *ClientService) UpdateByEmail(inboundSvc *InboundService, email string, updated model.Client, inboundFilter ...int) (bool, error) {
  650. if email == "" {
  651. return false, common.NewError("client email is required")
  652. }
  653. rec, err := s.GetRecordByEmail(nil, email)
  654. if err != nil {
  655. return false, err
  656. }
  657. return s.Update(inboundSvc, rec.Id, updated, inboundFilter...)
  658. }
  659. func (s *ClientService) Detach(inboundSvc *InboundService, id int, inboundIds []int) (bool, error) {
  660. existing, err := s.GetByID(id)
  661. if err != nil {
  662. return false, err
  663. }
  664. currentIds, err := s.GetInboundIdsForRecord(id)
  665. if err != nil {
  666. return false, err
  667. }
  668. have := make(map[int]struct{}, len(currentIds))
  669. for _, x := range currentIds {
  670. have[x] = struct{}{}
  671. }
  672. needRestart := false
  673. for _, ibId := range inboundIds {
  674. if _, attached := have[ibId]; !attached {
  675. continue
  676. }
  677. if _, getErr := inboundSvc.GetInbound(ibId); getErr != nil {
  678. return needRestart, getErr
  679. }
  680. // Detach by email — the client's stable identity (see Delete).
  681. if existing.Email == "" {
  682. continue
  683. }
  684. nr, delErr := s.DelInboundClientByEmail(inboundSvc, ibId, existing.Email, true, false)
  685. if delErr != nil {
  686. if errors.Is(delErr, ErrClientNotInInbound) {
  687. continue
  688. }
  689. return needRestart, delErr
  690. }
  691. if nr {
  692. needRestart = true
  693. }
  694. }
  695. return needRestart, nil
  696. }