1
0

client_crud.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  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. }
  351. if updated.SubID != "" {
  352. var subCollision int64
  353. if err := database.GetDB().Model(&model.ClientRecord{}).
  354. Where("sub_id = ? AND id <> ?", updated.SubID, id).
  355. Count(&subCollision).Error; err != nil {
  356. return false, err
  357. }
  358. if subCollision > 0 {
  359. return false, common.NewError("Duplicate subId:", updated.SubID)
  360. }
  361. }
  362. needRestart := false
  363. for _, ibId := range inboundIds {
  364. inbound, getErr := inboundSvc.GetInbound(ibId)
  365. if getErr != nil {
  366. if errors.Is(getErr, gorm.ErrRecordNotFound) {
  367. if err := database.GetDB().
  368. Where("client_id = ? AND inbound_id = ?", id, ibId).
  369. Delete(&model.ClientInbound{}).Error; err != nil {
  370. return needRestart, err
  371. }
  372. continue
  373. }
  374. return needRestart, getErr
  375. }
  376. if existing.Email == "" {
  377. continue
  378. }
  379. if err := s.fillProtocolDefaults(&updated, inbound); err != nil {
  380. return needRestart, err
  381. }
  382. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(updated, inbound)}})
  383. if mErr != nil {
  384. return needRestart, mErr
  385. }
  386. nr, upErr := s.UpdateInboundClient(inboundSvc, &model.Inbound{
  387. Id: ibId,
  388. Settings: string(settingsPayload),
  389. }, existing.Email)
  390. if upErr != nil {
  391. return needRestart, upErr
  392. }
  393. if nr {
  394. needRestart = true
  395. }
  396. }
  397. // UpdateInboundClient renames the record atomically with each inbound's
  398. // settings JSON; this direct write only covers records with no inbound left.
  399. if updated.Email != existing.Email {
  400. if err := database.GetDB().Model(&model.ClientRecord{}).
  401. Where("id = ? AND email = ?", id, existing.Email).
  402. Update("email", updated.Email).Error; err != nil {
  403. return needRestart, err
  404. }
  405. }
  406. reverseStr := ""
  407. if updated.Reverse != nil && strings.TrimSpace(updated.Reverse.Tag) != "" {
  408. if b, mErr := json.Marshal(updated.Reverse); mErr == nil {
  409. reverseStr = string(b)
  410. }
  411. }
  412. if err := database.GetDB().Model(&model.ClientRecord{}).
  413. Where("id = ?", id).
  414. Update("reverse", reverseStr).Error; err != nil {
  415. return needRestart, err
  416. }
  417. // Persist the group explicitly. SyncInbound deliberately preserves the
  418. // stored group when the inbound settings carry none — so a node snapshot or a
  419. // group-less settings rebuild can't wipe it (see SyncInbound + its tests).
  420. // That guard also meant clearing the group in the client editor never took
  421. // effect. The editor always round-trips the field, so apply it here,
  422. // including the empty string that removes the client from its group.
  423. if err := database.GetDB().Model(&model.ClientRecord{}).
  424. Where("id = ?", id).
  425. UpdateColumn("group_name", updated.Group).Error; err != nil {
  426. return needRestart, err
  427. }
  428. // Same shape as the group write above: SyncInbound keeps a stored ad-tag
  429. // when the incoming settings carry none, so clearing the override must be
  430. // applied here, where the editor always round-trips the field.
  431. if err := database.GetDB().Model(&model.ClientRecord{}).
  432. Where("id = ?", id).
  433. UpdateColumn("ad_tag", updated.AdTag).Error; err != nil {
  434. return needRestart, err
  435. }
  436. if err := database.GetDB().Model(&model.ClientRecord{}).
  437. Where("id = ?", id).
  438. UpdateColumn("enable", updated.Enable).Error; err != nil {
  439. return needRestart, err
  440. }
  441. if err := database.GetDB().Model(&model.ClientRecord{}).
  442. Where("id = ?", id).
  443. UpdateColumn("updated_at", time.Now().UnixMilli()).Error; err != nil {
  444. return needRestart, err
  445. }
  446. return needRestart, nil
  447. }
  448. func (s *ClientService) Delete(inboundSvc *InboundService, id int, keepTraffic bool) (bool, error) {
  449. existing, err := s.GetByID(id)
  450. if err != nil {
  451. return false, err
  452. }
  453. tombstoneClientEmail(existing.Email)
  454. inboundIds, err := s.GetInboundIdsForRecord(id)
  455. if err != nil {
  456. return false, err
  457. }
  458. needRestart := false
  459. for _, ibId := range inboundIds {
  460. if _, getErr := inboundSvc.GetInbound(ibId); getErr != nil {
  461. if errors.Is(getErr, gorm.ErrRecordNotFound) {
  462. continue
  463. }
  464. return needRestart, getErr
  465. }
  466. // Always delete by email — the client's stable identity. This removes
  467. // every matching entry from the inbound's settings even when the stored
  468. // credential (UUID/password/auth) drifted from the inbound JSON, or a
  469. // duplicate entry with the same email exists.
  470. if existing.Email == "" {
  471. continue
  472. }
  473. nr, delErr := s.DelInboundClientByEmail(inboundSvc, ibId, existing.Email, false, true)
  474. if delErr != nil {
  475. // The client is already absent from this inbound (data drift or a
  476. // retried delete). Skip it — deletion stays idempotent.
  477. if errors.Is(delErr, ErrClientNotInInbound) {
  478. continue
  479. }
  480. return needRestart, delErr
  481. }
  482. if nr {
  483. needRestart = true
  484. }
  485. }
  486. db := database.GetDB()
  487. if err := db.Transaction(func(tx *gorm.DB) error {
  488. if existing.Email != "" {
  489. if err := adjustGroupBaselinesForRemovedTraffic(tx, []string{existing.Email}); err != nil {
  490. return err
  491. }
  492. }
  493. if err := tx.Where("client_id = ?", id).Delete(&model.ClientInbound{}).Error; err != nil {
  494. return err
  495. }
  496. if err := tx.Where("client_id = ?", id).Delete(&model.ClientExternalLink{}).Error; err != nil {
  497. return err
  498. }
  499. if !keepTraffic && existing.Email != "" {
  500. if err := tx.Where("email = ?", existing.Email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  501. return err
  502. }
  503. if err := clearGlobalTraffic(tx, existing.Email); err != nil {
  504. return err
  505. }
  506. if err := tx.Where("client_email = ?", existing.Email).Delete(&model.InboundClientIps{}).Error; err != nil {
  507. return err
  508. }
  509. if err := tx.Where("email = ?", existing.Email).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  510. return err
  511. }
  512. }
  513. return tx.Delete(&model.ClientRecord{}, id).Error
  514. }); err != nil {
  515. return needRestart, err
  516. }
  517. return needRestart, nil
  518. }
  519. func (s *ClientService) Attach(inboundSvc *InboundService, id int, inboundIds []int) (bool, error) {
  520. existing, err := s.GetByID(id)
  521. if err != nil {
  522. return false, err
  523. }
  524. currentIds, err := s.GetInboundIdsForRecord(id)
  525. if err != nil {
  526. return false, err
  527. }
  528. have := make(map[int]struct{}, len(currentIds))
  529. for _, x := range currentIds {
  530. have[x] = struct{}{}
  531. }
  532. clientWire := existing.ToClient()
  533. flow, ffErr := s.EffectiveFlow(nil, id)
  534. if ffErr != nil {
  535. return false, ffErr
  536. }
  537. clientWire.Flow = flow
  538. clientWire.UpdatedAt = time.Now().UnixMilli()
  539. needRestart := false
  540. for _, ibId := range inboundIds {
  541. if _, attached := have[ibId]; attached {
  542. continue
  543. }
  544. inbound, getErr := inboundSvc.GetInbound(ibId)
  545. if getErr != nil {
  546. return needRestart, getErr
  547. }
  548. copyClient := *clientWire
  549. if err := s.fillProtocolDefaults(&copyClient, inbound); err != nil {
  550. return needRestart, err
  551. }
  552. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(copyClient, inbound)}})
  553. if mErr != nil {
  554. return needRestart, mErr
  555. }
  556. nr, addErr := s.AddInboundClient(inboundSvc, &model.Inbound{
  557. Id: ibId,
  558. Settings: string(settingsPayload),
  559. })
  560. if addErr != nil {
  561. return needRestart, addErr
  562. }
  563. if nr {
  564. needRestart = true
  565. }
  566. }
  567. return needRestart, nil
  568. }
  569. func (s *ClientService) CreateOne(inboundSvc *InboundService, inboundId int, client model.Client) (bool, error) {
  570. return s.Create(inboundSvc, &ClientCreatePayload{
  571. Client: client,
  572. InboundIds: []int{inboundId},
  573. })
  574. }
  575. func (s *ClientService) DetachByEmail(inboundSvc *InboundService, inboundId int, email string) (bool, error) {
  576. if email == "" {
  577. return false, common.NewError("client email is required")
  578. }
  579. rec, err := s.GetRecordByEmail(nil, email)
  580. if err != nil {
  581. return false, err
  582. }
  583. return s.Detach(inboundSvc, rec.Id, []int{inboundId})
  584. }
  585. func (s *ClientService) AttachByEmail(inboundSvc *InboundService, email string, inboundIds []int) (bool, error) {
  586. if email == "" {
  587. return false, common.NewError("client email is required")
  588. }
  589. rec, err := s.GetRecordByEmail(nil, email)
  590. if err != nil {
  591. return false, err
  592. }
  593. return s.Attach(inboundSvc, rec.Id, inboundIds)
  594. }
  595. func (s *ClientService) DetachByEmailMany(inboundSvc *InboundService, email string, inboundIds []int) (bool, error) {
  596. if email == "" {
  597. return false, common.NewError("client email is required")
  598. }
  599. rec, err := s.GetRecordByEmail(nil, email)
  600. if err != nil {
  601. return false, err
  602. }
  603. return s.Detach(inboundSvc, rec.Id, inboundIds)
  604. }
  605. func (s *ClientService) DeleteByEmail(inboundSvc *InboundService, email string, keepTraffic bool) (bool, error) {
  606. if email == "" {
  607. return false, common.NewError("client email is required")
  608. }
  609. rec, err := s.GetRecordByEmail(nil, email)
  610. if err == nil {
  611. return s.Delete(inboundSvc, rec.Id, keepTraffic)
  612. }
  613. if !errors.Is(err, gorm.ErrRecordNotFound) {
  614. return false, err
  615. }
  616. inboundIds, idsErr := s.findInboundIdsByClientEmail(email)
  617. if idsErr != nil {
  618. return false, idsErr
  619. }
  620. if len(inboundIds) == 0 {
  621. return false, common.NewError(fmt.Sprintf("client %q not found in any inbound or client record", email))
  622. }
  623. needRestart := false
  624. for _, ibId := range inboundIds {
  625. nr, delErr := s.DelInboundClientByEmail(inboundSvc, ibId, email, false, true)
  626. if delErr != nil {
  627. if errors.Is(delErr, ErrClientNotInInbound) {
  628. continue
  629. }
  630. return needRestart, delErr
  631. }
  632. if nr {
  633. needRestart = true
  634. }
  635. }
  636. if !keepTraffic {
  637. db := database.GetDB()
  638. if err := db.Where("email = ?", email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  639. return needRestart, err
  640. }
  641. if err := clearGlobalTraffic(db, email); err != nil {
  642. return needRestart, err
  643. }
  644. if err := db.Where("client_email = ?", email).Delete(&model.InboundClientIps{}).Error; err != nil {
  645. return needRestart, err
  646. }
  647. if err := db.Where("email = ?", email).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  648. return needRestart, err
  649. }
  650. }
  651. return needRestart, nil
  652. }
  653. func (s *ClientService) UpdateByEmail(inboundSvc *InboundService, email string, updated model.Client, inboundFilter ...int) (bool, error) {
  654. if email == "" {
  655. return false, common.NewError("client email is required")
  656. }
  657. rec, err := s.GetRecordByEmail(nil, email)
  658. if err != nil {
  659. return false, err
  660. }
  661. return s.Update(inboundSvc, rec.Id, updated, inboundFilter...)
  662. }
  663. func (s *ClientService) Detach(inboundSvc *InboundService, id int, inboundIds []int) (bool, error) {
  664. existing, err := s.GetByID(id)
  665. if err != nil {
  666. return false, err
  667. }
  668. currentIds, err := s.GetInboundIdsForRecord(id)
  669. if err != nil {
  670. return false, err
  671. }
  672. have := make(map[int]struct{}, len(currentIds))
  673. for _, x := range currentIds {
  674. have[x] = struct{}{}
  675. }
  676. needRestart := false
  677. for _, ibId := range inboundIds {
  678. if _, attached := have[ibId]; !attached {
  679. continue
  680. }
  681. if _, getErr := inboundSvc.GetInbound(ibId); getErr != nil {
  682. return needRestart, getErr
  683. }
  684. // Detach by email — the client's stable identity (see Delete).
  685. if existing.Email == "" {
  686. continue
  687. }
  688. nr, delErr := s.DelInboundClientByEmail(inboundSvc, ibId, existing.Email, true, false)
  689. if delErr != nil {
  690. if errors.Is(delErr, ErrClientNotInInbound) {
  691. continue
  692. }
  693. return needRestart, delErr
  694. }
  695. if nr {
  696. needRestart = true
  697. }
  698. }
  699. return needRestart, nil
  700. }