client_crud.go 20 KB

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