client_crud.go 23 KB

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