client_crud.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  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. if len(inboundIds) == 0 {
  407. merged := *existing
  408. applyClientRecordMerge(&merged, updated.ToRecord())
  409. if err := database.GetDB().Model(&model.ClientRecord{}).
  410. Where("id = ?", id).
  411. Updates(map[string]any{
  412. "sub_id": merged.SubID,
  413. "uuid": merged.UUID,
  414. "password": merged.Password,
  415. "auth": merged.Auth,
  416. "secret": merged.Secret,
  417. "flow": merged.Flow,
  418. "security": merged.Security,
  419. "wg_private_key": merged.PrivateKey,
  420. "wg_public_key": merged.PublicKey,
  421. "wg_allowed_ips": merged.AllowedIPs,
  422. "wg_pre_shared_key": merged.PreSharedKey,
  423. "wg_keep_alive": merged.KeepAlive,
  424. "limit_ip": merged.LimitIP,
  425. "total_gb": merged.TotalGB,
  426. "expiry_time": merged.ExpiryTime,
  427. "tg_id": merged.TgID,
  428. "comment": merged.Comment,
  429. "reset": merged.Reset,
  430. }).Error; err != nil {
  431. return needRestart, err
  432. }
  433. }
  434. reverseStr := ""
  435. if updated.Reverse != nil && strings.TrimSpace(updated.Reverse.Tag) != "" {
  436. if b, mErr := json.Marshal(updated.Reverse); mErr == nil {
  437. reverseStr = string(b)
  438. }
  439. }
  440. if err := database.GetDB().Model(&model.ClientRecord{}).
  441. Where("id = ?", id).
  442. Update("reverse", reverseStr).Error; err != nil {
  443. return needRestart, err
  444. }
  445. // Persist the group explicitly. SyncInbound deliberately preserves the
  446. // stored group when the inbound settings carry none — so a node snapshot or a
  447. // group-less settings rebuild can't wipe it (see SyncInbound + its tests).
  448. // That guard also meant clearing the group in the client editor never took
  449. // effect. The editor always round-trips the field, so apply it here,
  450. // including the empty string that removes the client from its group.
  451. if err := database.GetDB().Model(&model.ClientRecord{}).
  452. Where("id = ?", id).
  453. UpdateColumn("group_name", updated.Group).Error; err != nil {
  454. return needRestart, err
  455. }
  456. // Same shape as the group write above: SyncInbound keeps a stored ad-tag
  457. // when the incoming settings carry none, so clearing the override must be
  458. // applied here, where the editor always round-trips the field.
  459. if err := database.GetDB().Model(&model.ClientRecord{}).
  460. Where("id = ?", id).
  461. UpdateColumn("ad_tag", updated.AdTag).Error; err != nil {
  462. return needRestart, err
  463. }
  464. if err := database.GetDB().Model(&model.ClientRecord{}).
  465. Where("id = ?", id).
  466. UpdateColumn("enable", updated.Enable).Error; err != nil {
  467. return needRestart, err
  468. }
  469. if err := database.GetDB().Model(&model.ClientRecord{}).
  470. Where("id = ?", id).
  471. UpdateColumn("updated_at", time.Now().UnixMilli()).Error; err != nil {
  472. return needRestart, err
  473. }
  474. return needRestart, nil
  475. }
  476. func (s *ClientService) Delete(inboundSvc *InboundService, id int, keepTraffic bool) (bool, error) {
  477. existing, err := s.GetByID(id)
  478. if err != nil {
  479. return false, err
  480. }
  481. tombstoneClientEmail(existing.Email)
  482. inboundIds, err := s.GetInboundIdsForRecord(id)
  483. if err != nil {
  484. return false, err
  485. }
  486. needRestart := false
  487. var delErrs []error
  488. for _, ibId := range inboundIds {
  489. if _, getErr := inboundSvc.GetInbound(ibId); getErr != nil {
  490. if errors.Is(getErr, gorm.ErrRecordNotFound) {
  491. continue
  492. }
  493. delErrs = append(delErrs, fmt.Errorf("inbound %d: %w", ibId, getErr))
  494. continue
  495. }
  496. // Always delete by email — the client's stable identity. This removes
  497. // every matching entry from the inbound's settings even when the stored
  498. // credential (UUID/password/auth) drifted from the inbound JSON, or a
  499. // duplicate entry with the same email exists.
  500. if existing.Email == "" {
  501. continue
  502. }
  503. nr, delErr := s.DelInboundClientByEmail(inboundSvc, ibId, existing.Email, keepTraffic, true)
  504. if delErr != nil {
  505. // The client is already absent from this inbound (data drift or a
  506. // retried delete). Skip it — deletion stays idempotent.
  507. if errors.Is(delErr, ErrClientNotInInbound) {
  508. continue
  509. }
  510. delErrs = append(delErrs, fmt.Errorf("inbound %d: %w", ibId, delErr))
  511. continue
  512. }
  513. if nr {
  514. needRestart = true
  515. }
  516. }
  517. // A failed inbound still holds the client in its settings JSON: keep the
  518. // record so the next delete retries exactly the leftovers, and report it.
  519. if len(delErrs) > 0 {
  520. return needRestart, errors.Join(delErrs...)
  521. }
  522. db := database.GetDB()
  523. if err := db.Transaction(func(tx *gorm.DB) error {
  524. if existing.Email != "" {
  525. if err := adjustGroupBaselinesForRemovedTraffic(tx, []string{existing.Email}); err != nil {
  526. return err
  527. }
  528. }
  529. if err := tx.Where("client_id = ?", id).Delete(&model.ClientInbound{}).Error; err != nil {
  530. return err
  531. }
  532. if err := tx.Where("client_id = ?", id).Delete(&model.ClientExternalLink{}).Error; err != nil {
  533. return err
  534. }
  535. if !keepTraffic && existing.Email != "" {
  536. if err := tx.Where("email = ?", existing.Email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  537. return err
  538. }
  539. if err := clearGlobalTraffic(tx, existing.Email); err != nil {
  540. return err
  541. }
  542. if err := tx.Where("client_email = ?", existing.Email).Delete(&model.InboundClientIps{}).Error; err != nil {
  543. return err
  544. }
  545. if err := tx.Where("email = ?", existing.Email).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  546. return err
  547. }
  548. }
  549. return tx.Delete(&model.ClientRecord{}, id).Error
  550. }); err != nil {
  551. return needRestart, err
  552. }
  553. return needRestart, nil
  554. }
  555. func (s *ClientService) Attach(inboundSvc *InboundService, id int, inboundIds []int) (bool, error) {
  556. existing, err := s.GetByID(id)
  557. if err != nil {
  558. return false, err
  559. }
  560. currentIds, err := s.GetInboundIdsForRecord(id)
  561. if err != nil {
  562. return false, err
  563. }
  564. have := make(map[int]struct{}, len(currentIds))
  565. for _, x := range currentIds {
  566. have[x] = struct{}{}
  567. }
  568. clientWire := existing.ToClient()
  569. flow, ffErr := s.EffectiveFlow(nil, id)
  570. if ffErr != nil {
  571. return false, ffErr
  572. }
  573. clientWire.Flow = flow
  574. clientWire.UpdatedAt = time.Now().UnixMilli()
  575. needRestart := false
  576. for _, ibId := range inboundIds {
  577. if _, attached := have[ibId]; attached {
  578. continue
  579. }
  580. inbound, getErr := inboundSvc.GetInbound(ibId)
  581. if getErr != nil {
  582. return needRestart, getErr
  583. }
  584. copyClient := *clientWire
  585. if err := s.fillProtocolDefaults(&copyClient, inbound); err != nil {
  586. return needRestart, err
  587. }
  588. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(copyClient, inbound)}})
  589. if mErr != nil {
  590. return needRestart, mErr
  591. }
  592. nr, addErr := s.AddInboundClient(inboundSvc, &model.Inbound{
  593. Id: ibId,
  594. Settings: string(settingsPayload),
  595. })
  596. if addErr != nil {
  597. return needRestart, addErr
  598. }
  599. if nr {
  600. needRestart = true
  601. }
  602. }
  603. return needRestart, nil
  604. }
  605. func (s *ClientService) CreateOne(inboundSvc *InboundService, inboundId int, client model.Client) (bool, error) {
  606. return s.Create(inboundSvc, &ClientCreatePayload{
  607. Client: client,
  608. InboundIds: []int{inboundId},
  609. })
  610. }
  611. func (s *ClientService) DetachByEmail(inboundSvc *InboundService, inboundId int, email string) (bool, error) {
  612. if email == "" {
  613. return false, common.NewError("client email is required")
  614. }
  615. rec, err := s.GetRecordByEmail(nil, email)
  616. if err != nil {
  617. return false, err
  618. }
  619. return s.Detach(inboundSvc, rec.Id, []int{inboundId})
  620. }
  621. func (s *ClientService) AttachByEmail(inboundSvc *InboundService, email string, inboundIds []int) (bool, error) {
  622. if email == "" {
  623. return false, common.NewError("client email is required")
  624. }
  625. rec, err := s.GetRecordByEmail(nil, email)
  626. if err != nil {
  627. return false, err
  628. }
  629. return s.Attach(inboundSvc, rec.Id, inboundIds)
  630. }
  631. func (s *ClientService) DetachByEmailMany(inboundSvc *InboundService, email string, inboundIds []int) (bool, error) {
  632. if email == "" {
  633. return false, common.NewError("client email is required")
  634. }
  635. rec, err := s.GetRecordByEmail(nil, email)
  636. if err != nil {
  637. return false, err
  638. }
  639. return s.Detach(inboundSvc, rec.Id, inboundIds)
  640. }
  641. func (s *ClientService) DeleteByEmail(inboundSvc *InboundService, email string, keepTraffic bool) (bool, error) {
  642. if email == "" {
  643. return false, common.NewError("client email is required")
  644. }
  645. rec, err := s.GetRecordByEmail(nil, email)
  646. if err == nil {
  647. return s.Delete(inboundSvc, rec.Id, keepTraffic)
  648. }
  649. if !errors.Is(err, gorm.ErrRecordNotFound) {
  650. return false, err
  651. }
  652. inboundIds, idsErr := s.findInboundIdsByClientEmail(email)
  653. if idsErr != nil {
  654. return false, idsErr
  655. }
  656. if len(inboundIds) == 0 {
  657. return false, common.NewError(fmt.Sprintf("client %q not found in any inbound or client record", email))
  658. }
  659. needRestart := false
  660. var delErrs []error
  661. for _, ibId := range inboundIds {
  662. nr, delErr := s.DelInboundClientByEmail(inboundSvc, ibId, email, keepTraffic, true)
  663. if delErr != nil {
  664. if errors.Is(delErr, ErrClientNotInInbound) {
  665. continue
  666. }
  667. delErrs = append(delErrs, fmt.Errorf("inbound %d: %w", ibId, delErr))
  668. continue
  669. }
  670. if nr {
  671. needRestart = true
  672. }
  673. }
  674. if len(delErrs) > 0 {
  675. return needRestart, errors.Join(delErrs...)
  676. }
  677. if !keepTraffic {
  678. db := database.GetDB()
  679. if err := db.Where("email = ?", email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  680. return needRestart, err
  681. }
  682. if err := clearGlobalTraffic(db, email); err != nil {
  683. return needRestart, err
  684. }
  685. if err := db.Where("client_email = ?", email).Delete(&model.InboundClientIps{}).Error; err != nil {
  686. return needRestart, err
  687. }
  688. if err := db.Where("email = ?", email).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  689. return needRestart, err
  690. }
  691. }
  692. return needRestart, nil
  693. }
  694. func (s *ClientService) UpdateByEmail(inboundSvc *InboundService, email string, updated model.Client, inboundFilter ...int) (bool, error) {
  695. if email == "" {
  696. return false, common.NewError("client email is required")
  697. }
  698. rec, err := s.GetRecordByEmail(nil, email)
  699. if err != nil {
  700. return false, err
  701. }
  702. return s.Update(inboundSvc, rec.Id, updated, inboundFilter...)
  703. }
  704. func (s *ClientService) Detach(inboundSvc *InboundService, id int, inboundIds []int) (bool, error) {
  705. existing, err := s.GetByID(id)
  706. if err != nil {
  707. return false, err
  708. }
  709. currentIds, err := s.GetInboundIdsForRecord(id)
  710. if err != nil {
  711. return false, err
  712. }
  713. have := make(map[int]struct{}, len(currentIds))
  714. for _, x := range currentIds {
  715. have[x] = struct{}{}
  716. }
  717. needRestart := false
  718. for _, ibId := range inboundIds {
  719. if _, attached := have[ibId]; !attached {
  720. continue
  721. }
  722. if _, getErr := inboundSvc.GetInbound(ibId); getErr != nil {
  723. return needRestart, getErr
  724. }
  725. // Detach by email — the client's stable identity (see Delete).
  726. if existing.Email == "" {
  727. continue
  728. }
  729. nr, delErr := s.DelInboundClientByEmail(inboundSvc, ibId, existing.Email, true, false)
  730. if delErr != nil {
  731. if errors.Is(delErr, ErrClientNotInInbound) {
  732. continue
  733. }
  734. return needRestart, delErr
  735. }
  736. if nr {
  737. needRestart = true
  738. }
  739. }
  740. return needRestart, nil
  741. }