1
0

client_crud.go 23 KB

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