client_crud.go 22 KB

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