client_crud.go 36 KB

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