client_crud.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  1. package service
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "net/netip"
  8. "runtime/debug"
  9. "strings"
  10. "sync"
  11. "sync/atomic"
  12. "time"
  13. "unicode"
  14. "github.com/google/uuid"
  15. "github.com/mhsanaei/3x-ui/v3/internal/database"
  16. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  17. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  18. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  19. "github.com/mhsanaei/3x-ui/v3/internal/util/random"
  20. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  21. "gorm.io/gorm"
  22. )
  23. func hasForbiddenClientChar(s string) bool {
  24. for _, r := range s {
  25. if r == '/' || r == '\\' || r < 0x20 || r == 0x7f || unicode.IsSpace(r) {
  26. return true
  27. }
  28. }
  29. return false
  30. }
  31. func validateClientEmail(email string) error {
  32. if hasForbiddenClientChar(email) {
  33. return common.NewError("client email contains an invalid character:", email)
  34. }
  35. return nil
  36. }
  37. func validateClientSubID(subID string) error {
  38. if hasForbiddenClientChar(subID) {
  39. return common.NewError("client subId contains an invalid character:", subID)
  40. }
  41. return nil
  42. }
  43. // Rejected rather than coerced: an unknown cycle would leave the operator with
  44. // a field that reads as configured while no job ever selects the client.
  45. func validateClientTrafficReset(period string, day int) error {
  46. switch period {
  47. case "", "never", "hourly", "daily", "weekly", "monthly":
  48. default:
  49. return common.NewError("client trafficReset must be never, hourly, daily, weekly or monthly, got:", period)
  50. }
  51. if day < 0 || day > 31 {
  52. return common.NewError("client trafficResetDay must be between 0 and 31, got:", day)
  53. }
  54. return nil
  55. }
  56. // Rejected rather than clamped: nextCalendarRenewal would silently move an
  57. // out-of-range day, and a negative one drops out of the renewal query entirely.
  58. func validateClientResetDay(day int) error {
  59. if day < 0 || day > 31 {
  60. return common.NewError("client resetDay must be between 0 and 31, got:", day)
  61. }
  62. return nil
  63. }
  64. // Rejected rather than coerced: a negative cap reads as "unlimited" to a caller
  65. // but selects nothing, so the client would silently stop renewing.
  66. func validateClientResetMax(resetMax int) error {
  67. if resetMax < 0 {
  68. return common.NewError("client resetMax must not be negative, got:", resetMax)
  69. }
  70. return nil
  71. }
  72. // normalizeClientTrafficReset stores what the inbound path would store, so the
  73. // day never reaches the DB as a 0 that three layers downstream each clamp to 1.
  74. func normalizeClientTrafficReset(c *model.Client) {
  75. if c.TrafficReset == "" {
  76. c.TrafficReset = "never"
  77. }
  78. c.TrafficResetDay = normalizeTrafficResetDay(c.TrafficResetDay)
  79. }
  80. // ClientResetCycle is the slice of a client the reset job needs: enough to know
  81. // whether it is due, and whether its disable is the quota's doing or the operator's.
  82. type ClientResetCycle struct {
  83. Email string
  84. TrafficResetDay int
  85. Enable bool
  86. Total int64
  87. Used int64
  88. }
  89. // Depleted reports a client the quota switched off. A reset restores that one;
  90. // a client disabled below its quota was switched off by hand and stays off.
  91. func (c ClientResetCycle) Depleted() bool {
  92. return c.Total > 0 && c.Used >= c.Total
  93. }
  94. // GetClientsByTrafficReset returns the clients whose own reset cycle matches the
  95. // period, independent of the cycle configured on the inbounds they belong to.
  96. func (s *ClientService) GetClientsByTrafficReset(period string) ([]ClientResetCycle, error) {
  97. var cycles []ClientResetCycle
  98. err := database.GetDB().Table("clients c").
  99. Select("c.email, c.traffic_reset_day, c.enable, COALESCE(ct.total, 0) AS total, COALESCE(ct.up, 0) + COALESCE(ct.down, 0) AS used").
  100. Joins("LEFT JOIN client_traffics ct ON ct.email = c.email").
  101. Where("c.traffic_reset = ?", period).
  102. Scan(&cycles).Error
  103. if err != nil {
  104. return nil, err
  105. }
  106. return cycles, nil
  107. }
  108. // Create applies the client to every requested inbound: one failing inbound no
  109. // longer aborts the others, so the error can name several and needRestart holds.
  110. func (s *ClientService) Create(inboundSvc *InboundService, payload *ClientCreatePayload) (bool, error) {
  111. if payload == nil {
  112. return false, common.NewError("empty payload")
  113. }
  114. client := payload.Client
  115. if strings.TrimSpace(client.Email) == "" {
  116. return false, common.NewError("client email is required")
  117. }
  118. if err := validateClientEmail(client.Email); err != nil {
  119. return false, err
  120. }
  121. if err := validateClientSubID(client.SubID); err != nil {
  122. return false, err
  123. }
  124. if err := validateClientResetDay(client.ResetDay); err != nil {
  125. return false, err
  126. }
  127. if err := validateClientResetMax(client.ResetMax); err != nil {
  128. return false, err
  129. }
  130. if err := validateClientTrafficReset(client.TrafficReset, client.TrafficResetDay); err != nil {
  131. return false, err
  132. }
  133. normalizeClientTrafficReset(&client)
  134. if len(payload.InboundIds) == 0 {
  135. return false, common.NewError("at least one inbound is required")
  136. }
  137. if client.SubID == "" {
  138. client.SubID = uuid.NewString()
  139. }
  140. if !client.Enable {
  141. client.Enable = true
  142. }
  143. now := time.Now().UnixMilli()
  144. if client.CreatedAt == 0 {
  145. client.CreatedAt = now
  146. }
  147. client.UpdatedAt = now
  148. existing := &model.ClientRecord{}
  149. err := database.GetDB().Where("email = ?", client.Email).First(existing).Error
  150. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  151. return false, err
  152. }
  153. emailTaken := !errors.Is(err, gorm.ErrRecordNotFound)
  154. if emailTaken {
  155. if existing.SubID == "" || existing.SubID != client.SubID {
  156. return false, common.NewError("email already in use:", client.Email)
  157. }
  158. // Reuse stored credentials when re-adding an existing identity, or
  159. // fillProtocolDefaults mints a fresh UUID that desyncs other inbounds.
  160. if client.ID == "" {
  161. client.ID = existing.UUID
  162. }
  163. if client.Password == "" {
  164. client.Password = existing.Password
  165. }
  166. if client.Auth == "" {
  167. client.Auth = existing.Auth
  168. }
  169. if client.Secret == "" {
  170. client.Secret = existing.Secret
  171. }
  172. }
  173. if client.SubID != "" {
  174. var subTaken int64
  175. if err := database.GetDB().Model(&model.ClientRecord{}).
  176. Where("sub_id = ? AND email <> ?", client.SubID, client.Email).
  177. Count(&subTaken).Error; err != nil {
  178. return false, err
  179. }
  180. if subTaken > 0 {
  181. return false, common.NewError("subId already in use:", client.SubID)
  182. }
  183. }
  184. // Prepared before any inbound is written: fillProtocolDefaults mints the
  185. // shared credentials on the first inbound and every later one reuses them.
  186. adds := make([]*model.Inbound, 0, len(payload.InboundIds))
  187. for _, ibId := range payload.InboundIds {
  188. inbound, getErr := inboundSvc.GetInbound(ibId)
  189. if getErr != nil {
  190. return false, fmt.Errorf("inbound %d: %w", ibId, getErr)
  191. }
  192. if err := s.fillProtocolDefaults(&client, inbound); err != nil {
  193. return false, fmt.Errorf("inbound %d: %w", ibId, err)
  194. }
  195. clientForInbound := client
  196. if ips, ok := client.AllowedIPsByInbound[ibId]; ok {
  197. clientForInbound.AllowedIPs = ips
  198. } else if !addressesFitAmneziaWGInbound(clientForInbound.AllowedIPs, inbound) {
  199. // The shared AllowedIPs value (e.g. from a single-field legacy
  200. // caller) came from a different subnet than this inbound's own --
  201. // clear it so defaultAmneziaWGClients allocates a fresh, correct
  202. // address for THIS inbound instead of persisting an unroutable
  203. // peer. Same reasoning as addressesFitAmneziaWGInbound's own doc
  204. // comment on the Attach path.
  205. clientForInbound.AllowedIPs = nil
  206. }
  207. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(clientForInbound, inbound)}})
  208. if mErr != nil {
  209. return false, fmt.Errorf("inbound %d: %w", ibId, mErr)
  210. }
  211. adds = append(adds, &model.Inbound{Id: ibId, Settings: string(settingsPayload)})
  212. }
  213. needRestart, fanoutErr := s.fanoutInboundClientAdds(inboundSvc, adds)
  214. if fanoutErr != nil {
  215. // Never on a failed create: this retrims the devices of an email that
  216. // already existed, and a create the panel reported as failed must not.
  217. return needRestart, fanoutErr
  218. }
  219. return needRestart, s.setClientLimitHwidByEmail(nil, client.Email, payload.LimitHwid)
  220. }
  221. // inboundFanoutConcurrency caps how many inbounds one client op applies at
  222. // once, so a client spanning many of them can't start an unbounded RPC burst.
  223. const inboundFanoutConcurrency = 4
  224. // inboundApply is one inbound's share of a client op, ready to run.
  225. type inboundApply struct {
  226. id int
  227. run func() (bool, error)
  228. }
  229. // fanoutInboundApplies runs the applies with the node pushes overlapping, so a
  230. // client spanning several nodes no longer costs one RPC round-trip per node.
  231. func fanoutInboundApplies(applies []inboundApply) (bool, error) {
  232. var needRestart atomic.Bool
  233. errs := make([]error, len(applies))
  234. sem := make(chan struct{}, inboundFanoutConcurrency)
  235. var wg sync.WaitGroup
  236. for i := range applies {
  237. wg.Add(1)
  238. sem <- struct{}{}
  239. go func() {
  240. defer wg.Done()
  241. defer func() { <-sem }()
  242. // Off the request goroutine gin's Recovery no longer covers this,
  243. // so an unrecovered panic here would take the whole panel down.
  244. defer func() {
  245. if r := recover(); r != nil {
  246. // The apply may already have committed, so ask for the
  247. // restart the lost return value can no longer report.
  248. needRestart.Store(true)
  249. errs[i] = fmt.Errorf("inbound %d: panic: %v", applies[i].id, r)
  250. logger.Errorf("panic applying client change to inbound %d: %v\n%s", applies[i].id, r, debug.Stack())
  251. }
  252. }()
  253. nr, err := applies[i].run()
  254. if nr {
  255. needRestart.Store(true)
  256. }
  257. if err != nil {
  258. errs[i] = fmt.Errorf("inbound %d: %w", applies[i].id, err)
  259. }
  260. }()
  261. }
  262. wg.Wait()
  263. return needRestart.Load(), errors.Join(errs...)
  264. }
  265. // fanoutInboundClientAdds applies one payload per inbound.
  266. func (s *ClientService) fanoutInboundClientAdds(inboundSvc *InboundService, adds []*model.Inbound) (bool, error) {
  267. applies := make([]inboundApply, 0, len(adds))
  268. for _, add := range adds {
  269. applies = append(applies, inboundApply{id: add.Id, run: func() (bool, error) {
  270. return s.AddInboundClient(inboundSvc, add)
  271. }})
  272. }
  273. return fanoutInboundApplies(applies)
  274. }
  275. func (s *ClientService) fillProtocolDefaults(c *model.Client, ib *model.Inbound) error {
  276. switch ib.Protocol {
  277. case model.VMESS, model.VLESS:
  278. if c.ID == "" {
  279. c.ID = uuid.NewString()
  280. }
  281. case model.Trojan:
  282. if c.Password == "" {
  283. c.Password = strings.ReplaceAll(uuid.NewString(), "-", "")
  284. }
  285. case model.Shadowsocks:
  286. method := shadowsocksMethodFromSettings(ib.Settings)
  287. if c.Password == "" || !validShadowsocksClientKey(method, c.Password) {
  288. c.Password = randomShadowsocksClientKey(method)
  289. }
  290. case model.Hysteria:
  291. if c.Auth == "" {
  292. c.Auth = strings.ReplaceAll(uuid.NewString(), "-", "")
  293. }
  294. case model.MTProto:
  295. if c.Secret == "" {
  296. c.Secret = model.GenerateFakeTLSSecret(mtprotoDomainFromSettings(ib.Settings))
  297. }
  298. }
  299. return nil
  300. }
  301. // defaultMtprotoDomain is the FakeTLS fronting domain used when an mtproto
  302. // inbound carries no fakeTlsDomain of its own; it mirrors the frontend default.
  303. const defaultMtprotoDomain = "www.cloudflare.com"
  304. // mtprotoDomainFromSettings returns the inbound-level FakeTLS domain, falling
  305. // back to the default when unset, so a generated client secret always fronts a
  306. // real hostname.
  307. func mtprotoDomainFromSettings(settings string) string {
  308. domain := ""
  309. if settings != "" {
  310. var m map[string]any
  311. if err := json.Unmarshal([]byte(settings), &m); err == nil {
  312. domain, _ = m["fakeTlsDomain"].(string)
  313. }
  314. }
  315. domain = strings.TrimSpace(domain)
  316. if domain == "" {
  317. return defaultMtprotoDomain
  318. }
  319. return domain
  320. }
  321. func clientWithInboundFlow(c model.Client, ib *model.Inbound) model.Client {
  322. if ib.DisableFlow || !inboundCanEnableTlsFlow(string(ib.Protocol), ib.StreamSettings, ib.Settings) {
  323. c.Flow = ""
  324. }
  325. return c
  326. }
  327. func shadowsocksMethodFromSettings(settings string) string {
  328. if settings == "" {
  329. return ""
  330. }
  331. var m map[string]any
  332. if err := json.Unmarshal([]byte(settings), &m); err != nil {
  333. return ""
  334. }
  335. method, _ := m["method"].(string)
  336. return method
  337. }
  338. func randomShadowsocksClientKey(method string) string {
  339. if n := shadowsocksKeyBytes(method); n > 0 {
  340. return random.Base64Bytes(n)
  341. }
  342. return strings.ReplaceAll(uuid.NewString(), "-", "")
  343. }
  344. func validShadowsocksClientKey(method, key string) bool {
  345. n := shadowsocksKeyBytes(method)
  346. if n == 0 {
  347. return key != ""
  348. }
  349. decoded, err := base64.StdEncoding.DecodeString(key)
  350. if err != nil {
  351. return false
  352. }
  353. return len(decoded) == n
  354. }
  355. func shadowsocksKeyBytes(method string) int {
  356. switch method {
  357. case "2022-blake3-aes-128-gcm":
  358. return 16
  359. case "2022-blake3-aes-256-gcm", "2022-blake3-chacha20-poly1305":
  360. return 32
  361. }
  362. return 0
  363. }
  364. // normalizeShadowsocksClientKeys rewrites any Shadowsocks-2022 client password
  365. // whose decoded length no longer matches settings.method, which happens after the
  366. // inbound method is switched between ciphers of different key sizes (e.g.
  367. // aes-256↔aes-128). A wrong-length uPSK makes xray reject the user, so the link
  368. // fails to connect; regenerating restores a valid key (clients must re-fetch).
  369. // Non-Shadowsocks / legacy-SS settings pass through unchanged.
  370. func normalizeShadowsocksClientKeys(settings string) (string, bool) {
  371. method := shadowsocksMethodFromSettings(settings)
  372. if shadowsocksKeyBytes(method) == 0 {
  373. return settings, false
  374. }
  375. var m map[string]any
  376. if err := json.Unmarshal([]byte(settings), &m); err != nil {
  377. return settings, false
  378. }
  379. clients, ok := m["clients"].([]any)
  380. if !ok {
  381. return settings, false
  382. }
  383. changed := false
  384. for i := range clients {
  385. c, ok := clients[i].(map[string]any)
  386. if !ok {
  387. continue
  388. }
  389. if pw, _ := c["password"].(string); validShadowsocksClientKey(method, pw) {
  390. continue
  391. }
  392. c["password"] = randomShadowsocksClientKey(method)
  393. clients[i] = c
  394. changed = true
  395. }
  396. if !changed {
  397. return settings, false
  398. }
  399. m["clients"] = clients
  400. bs, err := json.MarshalIndent(m, "", " ")
  401. if err != nil {
  402. return settings, false
  403. }
  404. return string(bs), true
  405. }
  406. func applyShadowsocksClientMethod(clients []any, settings map[string]any) {
  407. method, _ := settings["method"].(string)
  408. is2022 := strings.HasPrefix(method, "2022-blake3-")
  409. for i := range clients {
  410. cm, ok := clients[i].(map[string]any)
  411. if !ok {
  412. continue
  413. }
  414. if is2022 {
  415. if _, hasKey := cm["method"]; hasKey {
  416. delete(cm, "method")
  417. clients[i] = cm
  418. }
  419. continue
  420. }
  421. if method == "" {
  422. continue
  423. }
  424. if existing, _ := cm["method"].(string); existing != "" {
  425. continue
  426. }
  427. cm["method"] = method
  428. clients[i] = cm
  429. }
  430. }
  431. func (s *ClientService) Update(inboundSvc *InboundService, id int, updated model.Client, limitHwid int, inboundFilter ...int) (bool, error) {
  432. existing, err := s.GetByID(id)
  433. if err != nil {
  434. return false, err
  435. }
  436. inboundIds, err := s.GetInboundIdsForRecord(id)
  437. if err != nil {
  438. return false, err
  439. }
  440. if len(inboundFilter) > 0 {
  441. allow := make(map[int]struct{}, len(inboundFilter))
  442. for _, fid := range inboundFilter {
  443. allow[fid] = struct{}{}
  444. }
  445. filtered := inboundIds[:0:0]
  446. for _, ibId := range inboundIds {
  447. if _, ok := allow[ibId]; ok {
  448. filtered = append(filtered, ibId)
  449. }
  450. }
  451. inboundIds = filtered
  452. }
  453. if strings.TrimSpace(updated.Email) == "" {
  454. return false, common.NewError("client email is required")
  455. }
  456. if err := validateClientEmail(updated.Email); err != nil {
  457. return false, err
  458. }
  459. if err := validateClientSubID(updated.SubID); err != nil {
  460. return false, err
  461. }
  462. if err := validateClientResetDay(updated.ResetDay); err != nil {
  463. return false, err
  464. }
  465. if err := validateClientResetMax(updated.ResetMax); err != nil {
  466. return false, err
  467. }
  468. if err := validateClientTrafficReset(updated.TrafficReset, updated.TrafficResetDay); err != nil {
  469. return false, err
  470. }
  471. normalizeClientTrafficReset(&updated)
  472. if updated.SubID == "" {
  473. updated.SubID = existing.SubID
  474. }
  475. if updated.SubID == "" {
  476. updated.SubID = uuid.NewString()
  477. }
  478. updated.UpdatedAt = time.Now().UnixMilli()
  479. if updated.CreatedAt == 0 {
  480. updated.CreatedAt = existing.CreatedAt
  481. }
  482. // Preserve existing credentials when the caller omits them, so a partial
  483. // update (e.g. only changing traffic/expiry) doesn't silently rotate the
  484. // client's UUID/password/auth via fillProtocolDefaults. Supplying a new
  485. // value still rotates it intentionally.
  486. if updated.ID == "" {
  487. updated.ID = existing.UUID
  488. }
  489. if updated.Password == "" {
  490. updated.Password = existing.Password
  491. }
  492. if updated.Auth == "" {
  493. updated.Auth = existing.Auth
  494. }
  495. if updated.Secret == "" {
  496. updated.Secret = existing.Secret
  497. }
  498. if updated.Email != existing.Email {
  499. var collisionCount int64
  500. if err := database.GetDB().Model(&model.ClientRecord{}).
  501. Where("email = ? AND id <> ?", updated.Email, id).
  502. Count(&collisionCount).Error; err != nil {
  503. return false, err
  504. }
  505. if collisionCount > 0 {
  506. return false, common.NewError("Duplicate email:", updated.Email)
  507. }
  508. }
  509. if updated.SubID != existing.SubID {
  510. var subCollision int64
  511. if err := database.GetDB().Model(&model.ClientRecord{}).
  512. Where("sub_id = ? AND id <> ?", updated.SubID, id).
  513. Count(&subCollision).Error; err != nil {
  514. return false, err
  515. }
  516. if subCollision > 0 {
  517. return false, common.NewError("Duplicate subId:", updated.SubID)
  518. }
  519. }
  520. // Built before any inbound is written, as in Create: fillProtocolDefaults
  521. // mints the shared credentials on the first inbound, later ones reuse them.
  522. applies := make([]inboundApply, 0, len(inboundIds))
  523. for _, ibId := range inboundIds {
  524. inbound, getErr := inboundSvc.GetInbound(ibId)
  525. if getErr != nil {
  526. if errors.Is(getErr, gorm.ErrRecordNotFound) {
  527. if err := database.GetDB().
  528. Where("client_id = ? AND inbound_id = ?", id, ibId).
  529. Delete(&model.ClientInbound{}).Error; err != nil {
  530. return false, err
  531. }
  532. continue
  533. }
  534. return false, getErr
  535. }
  536. if existing.Email == "" {
  537. continue
  538. }
  539. if err := s.fillProtocolDefaults(&updated, inbound); err != nil {
  540. return false, err
  541. }
  542. clientForInbound := updated
  543. if ips, ok := updated.AllowedIPsByInbound[ibId]; ok {
  544. clientForInbound.AllowedIPs = ips
  545. } else if !addressesFitAmneziaWGInbound(clientForInbound.AllowedIPs, inbound) {
  546. // A single shared AllowedIPs field (the common case for a caller
  547. // that never sends AllowedIPsByInbound) must never overwrite an
  548. // inbound it doesn't belong to -- e.g. a client attached to both
  549. // wg and awg saving its wg-labeled address would otherwise get
  550. // that same address silently written into the awg peer config
  551. // too. Clearing it here makes UpdateInboundClient's own
  552. // empty-AllowedIPs carry-forward (see its WireGuard/AmneziaWG
  553. // branch) preserve THIS inbound's existing, correct value
  554. // instead.
  555. clientForInbound.AllowedIPs = nil
  556. }
  557. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(clientForInbound, inbound)}})
  558. if mErr != nil {
  559. return false, mErr
  560. }
  561. data := &model.Inbound{Id: ibId, Settings: string(settingsPayload)}
  562. applies = append(applies, inboundApply{id: ibId, run: func() (bool, error) {
  563. return s.UpdateInboundClient(inboundSvc, data, existing.Email)
  564. }})
  565. }
  566. needRestart, applyErr := fanoutInboundApplies(applies)
  567. if applyErr != nil {
  568. return needRestart, applyErr
  569. }
  570. // UpdateInboundClient renames the record atomically with each inbound's
  571. // settings JSON; this direct write only covers records with no inbound left.
  572. if updated.Email != existing.Email {
  573. if err := database.GetDB().Model(&model.ClientRecord{}).
  574. Where("id = ? AND email = ?", id, existing.Email).
  575. Update("email", updated.Email).Error; err != nil {
  576. return needRestart, err
  577. }
  578. }
  579. if len(inboundIds) == 0 {
  580. merged := *existing
  581. applyClientRecordMerge(&merged, updated.ToRecord())
  582. if err := database.GetDB().Model(&model.ClientRecord{}).
  583. Where("id = ?", id).
  584. Updates(map[string]any{
  585. "sub_id": merged.SubID,
  586. "uuid": merged.UUID,
  587. "password": merged.Password,
  588. "auth": merged.Auth,
  589. "secret": merged.Secret,
  590. "flow": merged.Flow,
  591. "security": merged.Security,
  592. "wg_private_key": merged.PrivateKey,
  593. "wg_public_key": merged.PublicKey,
  594. "wg_allowed_ips": merged.AllowedIPs,
  595. "wg_pre_shared_key": merged.PreSharedKey,
  596. "wg_keep_alive": merged.KeepAlive,
  597. "limit_ip": merged.LimitIP,
  598. "total_gb": merged.TotalGB,
  599. "expiry_time": merged.ExpiryTime,
  600. "tg_id": merged.TgID,
  601. "comment": merged.Comment,
  602. "reset": merged.Reset,
  603. "reset_day": merged.ResetDay,
  604. "reset_max": merged.ResetMax,
  605. "traffic_reset": merged.TrafficReset,
  606. "traffic_reset_day": merged.TrafficResetDay,
  607. }).Error; err != nil {
  608. return needRestart, err
  609. }
  610. }
  611. reverseStr := ""
  612. if updated.Reverse != nil && strings.TrimSpace(updated.Reverse.Tag) != "" {
  613. if b, mErr := json.Marshal(updated.Reverse); mErr == nil {
  614. reverseStr = string(b)
  615. }
  616. }
  617. if err := database.GetDB().Model(&model.ClientRecord{}).
  618. Where("id = ?", id).
  619. Update("reverse", reverseStr).Error; err != nil {
  620. return needRestart, err
  621. }
  622. // Persist the group explicitly. SyncInbound deliberately preserves the
  623. // stored group when the inbound settings carry none — so a node snapshot or a
  624. // group-less settings rebuild can't wipe it (see SyncInbound + its tests).
  625. // That guard also meant clearing the group in the client editor never took
  626. // effect. The editor always round-trips the field, so apply it here,
  627. // including the empty string that removes the client from its group.
  628. if err := database.GetDB().Model(&model.ClientRecord{}).
  629. Where("id = ?", id).
  630. UpdateColumn("group_name", updated.Group).Error; err != nil {
  631. return needRestart, err
  632. }
  633. // Same shape as the group write above: SyncInbound keeps a stored ad-tag
  634. // when the incoming settings carry none, so clearing the override must be
  635. // applied here, where the editor always round-trips the field.
  636. if err := database.GetDB().Model(&model.ClientRecord{}).
  637. Where("id = ?", id).
  638. UpdateColumn("ad_tag", updated.AdTag).Error; err != nil {
  639. return needRestart, err
  640. }
  641. if err := database.GetDB().Model(&model.ClientRecord{}).
  642. Where("id = ?", id).
  643. UpdateColumn("enable", updated.Enable).Error; err != nil {
  644. return needRestart, err
  645. }
  646. if err := s.setClientLimitHwidByEmail(nil, updated.Email, limitHwid); err != nil {
  647. return needRestart, err
  648. }
  649. if err := database.GetDB().Model(&model.ClientRecord{}).
  650. Where("id = ?", id).
  651. UpdateColumn("updated_at", time.Now().UnixMilli()).Error; err != nil {
  652. return needRestart, err
  653. }
  654. return needRestart, nil
  655. }
  656. func (s *ClientService) Delete(inboundSvc *InboundService, id int, keepTraffic bool) (bool, error) {
  657. existing, err := s.GetByID(id)
  658. if err != nil {
  659. return false, err
  660. }
  661. tombstoneClientEmail(existing.Email)
  662. inboundIds, err := s.GetInboundIdsForRecord(id)
  663. if err != nil {
  664. withdrawClientTombstones(existing.Email)
  665. return false, err
  666. }
  667. applies := make([]inboundApply, 0, len(inboundIds))
  668. var delErrs []error
  669. for _, ibId := range inboundIds {
  670. if _, getErr := inboundSvc.GetInbound(ibId); getErr != nil {
  671. if errors.Is(getErr, gorm.ErrRecordNotFound) {
  672. continue
  673. }
  674. delErrs = append(delErrs, fmt.Errorf("inbound %d: %w", ibId, getErr))
  675. continue
  676. }
  677. // Always delete by email — the client's stable identity. This removes
  678. // every matching entry from the inbound's settings even when the stored
  679. // credential (UUID/password/auth) drifted from the inbound JSON, or a
  680. // duplicate entry with the same email exists.
  681. if existing.Email == "" {
  682. continue
  683. }
  684. applies = append(applies, inboundApply{id: ibId, run: func() (bool, error) {
  685. nr, delErr := s.DelInboundClientByEmail(inboundSvc, ibId, existing.Email, keepTraffic, true)
  686. // The client is already absent from this inbound (data drift or a
  687. // retried delete). Skip it — deletion stays idempotent.
  688. if errors.Is(delErr, ErrClientNotInInbound) {
  689. return nr, nil
  690. }
  691. return nr, delErr
  692. }})
  693. }
  694. needRestart, applyErr := fanoutInboundApplies(applies)
  695. if applyErr != nil {
  696. delErrs = append(delErrs, applyErr)
  697. }
  698. // A failed inbound still holds the client in its settings JSON: keep the
  699. // record so the next delete retries exactly the leftovers, and report it.
  700. // The tombstone lifts with it, or the next node merge finishes the deletion.
  701. if len(delErrs) > 0 {
  702. withdrawClientTombstones(existing.Email)
  703. return needRestart, errors.Join(delErrs...)
  704. }
  705. db := database.GetDB()
  706. if err := db.Transaction(func(tx *gorm.DB) error {
  707. if existing.Email != "" {
  708. if err := adjustGroupBaselinesForRemovedTraffic(tx, []string{existing.Email}); err != nil {
  709. return err
  710. }
  711. }
  712. if err := tx.Where("client_id = ?", id).Delete(&model.ClientInbound{}).Error; err != nil {
  713. return err
  714. }
  715. if err := tx.Where("client_id = ?", id).Delete(&model.ClientExternalLink{}).Error; err != nil {
  716. return err
  717. }
  718. if err := clearClientHwidsBySubIDTx(tx, existing.SubID); err != nil {
  719. return err
  720. }
  721. if !keepTraffic && existing.Email != "" {
  722. if err := tx.Where("email = ?", existing.Email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  723. return err
  724. }
  725. if err := clearGlobalTraffic(tx, existing.Email); err != nil {
  726. return err
  727. }
  728. if err := tx.Where("client_email = ?", existing.Email).Delete(&model.InboundClientIps{}).Error; err != nil {
  729. return err
  730. }
  731. if err := tx.Where("email = ?", existing.Email).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  732. return err
  733. }
  734. }
  735. return tx.Delete(&model.ClientRecord{}, id).Error
  736. }); err != nil {
  737. withdrawClientTombstones(existing.Email)
  738. return needRestart, err
  739. }
  740. return needRestart, nil
  741. }
  742. // hasTunnelAttachment reports whether any of inboundIds is a currently
  743. // existing WireGuard or AmneziaWG inbound. Inbounds that fail to load are
  744. // skipped rather than treated as an error -- Attach's own loop already
  745. // surfaces a real error for any inbound it can't load when it gets there.
  746. func (s *ClientService) hasTunnelAttachment(inboundSvc *InboundService, inboundIds []int) bool {
  747. for _, ibId := range inboundIds {
  748. inbound, err := inboundSvc.GetInbound(ibId)
  749. if err != nil {
  750. continue
  751. }
  752. if inbound.Protocol == model.WireGuard || inbound.Protocol == model.AmneziaWG {
  753. return true
  754. }
  755. }
  756. return false
  757. }
  758. // addressesFitAmneziaWGInbound reports whether every entry in addrs falls
  759. // inside ib's own configured subnet(s). AmneziaWG only: its kernel interface
  760. // Address is exactly that subnet, so an address inherited from elsewhere (an
  761. // identity attached to a WireGuard inbound first, say) produces a peer that
  762. // can never connect -- Attach allocates fresh instead.
  763. func addressesFitAmneziaWGInbound(addrs []string, ib *model.Inbound) bool {
  764. if ib.Protocol != model.AmneziaWG || len(addrs) == 0 {
  765. return true
  766. }
  767. v4Base, v6Base, err := defaultAmneziaWGSubnetBases(ib.Settings)
  768. if err != nil {
  769. return false
  770. }
  771. bases := make([]netip.Prefix, 0, 2)
  772. for _, base := range []string{v4Base, v6Base} {
  773. if base == "" {
  774. continue
  775. }
  776. prefix, pErr := netip.ParsePrefix(base)
  777. if pErr != nil {
  778. return false
  779. }
  780. bases = append(bases, prefix)
  781. }
  782. for _, a := range addrs {
  783. host := wireguardHostAddr(a)
  784. if !host.IsValid() {
  785. return false
  786. }
  787. fits := false
  788. for _, prefix := range bases {
  789. if prefix.Contains(host) {
  790. fits = true
  791. break
  792. }
  793. }
  794. if !fits {
  795. return false
  796. }
  797. }
  798. return true
  799. }
  800. // Attach applies the client to every requested inbound: one failing inbound no
  801. // longer aborts the others, so the error can name several and needRestart holds.
  802. func (s *ClientService) Attach(inboundSvc *InboundService, id int, inboundIds []int) (bool, error) {
  803. existing, err := s.GetByID(id)
  804. if err != nil {
  805. return false, err
  806. }
  807. currentIds, err := s.GetInboundIdsForRecord(id)
  808. if err != nil {
  809. return false, err
  810. }
  811. have := make(map[int]struct{}, len(currentIds))
  812. for _, x := range currentIds {
  813. have[x] = struct{}{}
  814. }
  815. clientWire := existing.ToClient()
  816. flow, ffErr := s.EffectiveFlow(nil, id)
  817. if ffErr != nil {
  818. return false, ffErr
  819. }
  820. clientWire.Flow = flow
  821. clientWire.UpdatedAt = time.Now().UnixMilli()
  822. // If this identity has no CURRENT WireGuard/AmneziaWG attachment,
  823. // clientWire.AllowedIPs (from the ClientRecord) is a leftover from
  824. // whenever it last had one -- nothing reserves it anymore. Clear it so
  825. // attaching to a tunnel inbound now allocates a fresh address instead
  826. // of resurrecting the old one, which may no longer even be the lowest
  827. // free slot. Left untouched when the identity already has an active
  828. // tunnel elsewhere, so extending it to a second protocol still keeps
  829. // the same address on both.
  830. if !s.hasTunnelAttachment(inboundSvc, currentIds) {
  831. clientWire.AllowedIPs = nil
  832. }
  833. adds := make([]*model.Inbound, 0, len(inboundIds))
  834. for _, ibId := range inboundIds {
  835. if _, attached := have[ibId]; attached {
  836. continue
  837. }
  838. inbound, getErr := inboundSvc.GetInbound(ibId)
  839. if getErr != nil {
  840. return false, fmt.Errorf("inbound %d: %w", ibId, getErr)
  841. }
  842. copyClient := *clientWire
  843. if !addressesFitAmneziaWGInbound(copyClient.AllowedIPs, inbound) {
  844. copyClient.AllowedIPs = nil
  845. }
  846. if err := s.fillProtocolDefaults(&copyClient, inbound); err != nil {
  847. return false, fmt.Errorf("inbound %d: %w", ibId, err)
  848. }
  849. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(copyClient, inbound)}})
  850. if mErr != nil {
  851. return false, fmt.Errorf("inbound %d: %w", ibId, mErr)
  852. }
  853. adds = append(adds, &model.Inbound{Id: ibId, Settings: string(settingsPayload)})
  854. }
  855. return s.fanoutInboundClientAdds(inboundSvc, adds)
  856. }
  857. func (s *ClientService) CreateOne(inboundSvc *InboundService, inboundId int, client model.Client) (bool, error) {
  858. return s.Create(inboundSvc, &ClientCreatePayload{
  859. Client: client,
  860. InboundIds: []int{inboundId},
  861. })
  862. }
  863. func (s *ClientService) DetachByEmail(inboundSvc *InboundService, inboundId int, email string) (bool, error) {
  864. if email == "" {
  865. return false, common.NewError("client email is required")
  866. }
  867. rec, err := s.GetRecordByEmail(nil, email)
  868. if err != nil {
  869. return false, err
  870. }
  871. return s.Detach(inboundSvc, rec.Id, []int{inboundId})
  872. }
  873. func (s *ClientService) AttachByEmail(inboundSvc *InboundService, email string, inboundIds []int) (bool, error) {
  874. if email == "" {
  875. return false, common.NewError("client email is required")
  876. }
  877. rec, err := s.GetRecordByEmail(nil, email)
  878. if err != nil {
  879. return false, err
  880. }
  881. return s.Attach(inboundSvc, rec.Id, inboundIds)
  882. }
  883. func (s *ClientService) DetachByEmailMany(inboundSvc *InboundService, email string, inboundIds []int) (bool, error) {
  884. if email == "" {
  885. return false, common.NewError("client email is required")
  886. }
  887. rec, err := s.GetRecordByEmail(nil, email)
  888. if err != nil {
  889. return false, err
  890. }
  891. return s.Detach(inboundSvc, rec.Id, inboundIds)
  892. }
  893. func (s *ClientService) DeleteByEmail(inboundSvc *InboundService, email string, keepTraffic bool) (bool, error) {
  894. if email == "" {
  895. return false, common.NewError("client email is required")
  896. }
  897. rec, err := s.GetRecordByEmail(nil, email)
  898. if err == nil {
  899. return s.Delete(inboundSvc, rec.Id, keepTraffic)
  900. }
  901. if !errors.Is(err, gorm.ErrRecordNotFound) {
  902. return false, err
  903. }
  904. inboundIds, idsErr := s.findInboundIdsByClientEmail(email)
  905. if idsErr != nil {
  906. return false, idsErr
  907. }
  908. if len(inboundIds) == 0 {
  909. return false, common.NewError(fmt.Sprintf("client %q not found in any inbound or client record", email))
  910. }
  911. applies := make([]inboundApply, 0, len(inboundIds))
  912. for _, ibId := range inboundIds {
  913. applies = append(applies, inboundApply{id: ibId, run: func() (bool, error) {
  914. nr, delErr := s.DelInboundClientByEmail(inboundSvc, ibId, email, keepTraffic, true)
  915. if errors.Is(delErr, ErrClientNotInInbound) {
  916. return nr, nil
  917. }
  918. return nr, delErr
  919. }})
  920. }
  921. needRestart, delErr := fanoutInboundApplies(applies)
  922. if delErr != nil {
  923. return needRestart, delErr
  924. }
  925. if !keepTraffic {
  926. db := database.GetDB()
  927. if err := db.Where("email = ?", email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  928. return needRestart, err
  929. }
  930. if err := clearGlobalTraffic(db, email); err != nil {
  931. return needRestart, err
  932. }
  933. if err := db.Where("client_email = ?", email).Delete(&model.InboundClientIps{}).Error; err != nil {
  934. return needRestart, err
  935. }
  936. if err := db.Where("email = ?", email).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  937. return needRestart, err
  938. }
  939. }
  940. return needRestart, nil
  941. }
  942. func (s *ClientService) UpdateByEmail(inboundSvc *InboundService, email string, updated model.Client, limitHwid int, inboundFilter ...int) (bool, error) {
  943. if email == "" {
  944. return false, common.NewError("client email is required")
  945. }
  946. rec, err := s.GetRecordByEmail(nil, email)
  947. if err != nil {
  948. return false, err
  949. }
  950. return s.Update(inboundSvc, rec.Id, updated, limitHwid, inboundFilter...)
  951. }
  952. func (s *ClientService) Detach(inboundSvc *InboundService, id int, inboundIds []int) (bool, error) {
  953. existing, err := s.GetByID(id)
  954. if err != nil {
  955. return false, err
  956. }
  957. currentIds, err := s.GetInboundIdsForRecord(id)
  958. if err != nil {
  959. return false, err
  960. }
  961. have := make(map[int]struct{}, len(currentIds))
  962. for _, x := range currentIds {
  963. have[x] = struct{}{}
  964. }
  965. applies := make([]inboundApply, 0, len(inboundIds))
  966. for _, ibId := range inboundIds {
  967. if _, attached := have[ibId]; !attached {
  968. continue
  969. }
  970. if _, getErr := inboundSvc.GetInbound(ibId); getErr != nil {
  971. return false, getErr
  972. }
  973. // Detach by email — the client's stable identity (see Delete).
  974. if existing.Email == "" {
  975. continue
  976. }
  977. applies = append(applies, inboundApply{id: ibId, run: func() (bool, error) {
  978. nr, delErr := s.DelInboundClientByEmail(inboundSvc, ibId, existing.Email, true, false)
  979. if errors.Is(delErr, ErrClientNotInInbound) {
  980. return nr, nil
  981. }
  982. return nr, delErr
  983. }})
  984. }
  985. return fanoutInboundApplies(applies)
  986. }