client_crud.go 24 KB

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