1
0

client_crud.go 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043
  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 create/attach applies at
  222. // once, so a client spanning many of them can't start an unbounded RPC burst.
  223. const inboundFanoutConcurrency = 4
  224. // fanoutInboundClientAdds applies one payload per inbound with the node pushes
  225. // overlapping; unlike the sequential loop, one failure no longer stops the rest.
  226. func (s *ClientService) fanoutInboundClientAdds(inboundSvc *InboundService, adds []*model.Inbound) (bool, error) {
  227. var needRestart atomic.Bool
  228. errs := make([]error, len(adds))
  229. sem := make(chan struct{}, inboundFanoutConcurrency)
  230. var wg sync.WaitGroup
  231. for i := range adds {
  232. wg.Add(1)
  233. sem <- struct{}{}
  234. go func() {
  235. defer wg.Done()
  236. defer func() { <-sem }()
  237. // Off the request goroutine gin's Recovery no longer covers this,
  238. // so an unrecovered panic here would take the whole panel down.
  239. defer func() {
  240. if r := recover(); r != nil {
  241. // The apply may already have committed, so ask for the
  242. // restart the lost return value can no longer report.
  243. needRestart.Store(true)
  244. errs[i] = fmt.Errorf("inbound %d: panic: %v", adds[i].Id, r)
  245. logger.Errorf("panic adding client to inbound %d: %v\n%s", adds[i].Id, r, debug.Stack())
  246. }
  247. }()
  248. nr, err := s.AddInboundClient(inboundSvc, adds[i])
  249. if nr {
  250. needRestart.Store(true)
  251. }
  252. if err != nil {
  253. errs[i] = fmt.Errorf("inbound %d: %w", adds[i].Id, err)
  254. }
  255. }()
  256. }
  257. wg.Wait()
  258. return needRestart.Load(), errors.Join(errs...)
  259. }
  260. func (s *ClientService) fillProtocolDefaults(c *model.Client, ib *model.Inbound) error {
  261. switch ib.Protocol {
  262. case model.VMESS, model.VLESS:
  263. if c.ID == "" {
  264. c.ID = uuid.NewString()
  265. }
  266. case model.Trojan:
  267. if c.Password == "" {
  268. c.Password = strings.ReplaceAll(uuid.NewString(), "-", "")
  269. }
  270. case model.Shadowsocks:
  271. method := shadowsocksMethodFromSettings(ib.Settings)
  272. if c.Password == "" || !validShadowsocksClientKey(method, c.Password) {
  273. c.Password = randomShadowsocksClientKey(method)
  274. }
  275. case model.Hysteria:
  276. if c.Auth == "" {
  277. c.Auth = strings.ReplaceAll(uuid.NewString(), "-", "")
  278. }
  279. case model.MTProto:
  280. if c.Secret == "" {
  281. c.Secret = model.GenerateFakeTLSSecret(mtprotoDomainFromSettings(ib.Settings))
  282. }
  283. }
  284. return nil
  285. }
  286. // defaultMtprotoDomain is the FakeTLS fronting domain used when an mtproto
  287. // inbound carries no fakeTlsDomain of its own; it mirrors the frontend default.
  288. const defaultMtprotoDomain = "www.cloudflare.com"
  289. // mtprotoDomainFromSettings returns the inbound-level FakeTLS domain, falling
  290. // back to the default when unset, so a generated client secret always fronts a
  291. // real hostname.
  292. func mtprotoDomainFromSettings(settings string) string {
  293. domain := ""
  294. if settings != "" {
  295. var m map[string]any
  296. if err := json.Unmarshal([]byte(settings), &m); err == nil {
  297. domain, _ = m["fakeTlsDomain"].(string)
  298. }
  299. }
  300. domain = strings.TrimSpace(domain)
  301. if domain == "" {
  302. return defaultMtprotoDomain
  303. }
  304. return domain
  305. }
  306. func clientWithInboundFlow(c model.Client, ib *model.Inbound) model.Client {
  307. if ib.DisableFlow || !inboundCanEnableTlsFlow(string(ib.Protocol), ib.StreamSettings, ib.Settings) {
  308. c.Flow = ""
  309. }
  310. return c
  311. }
  312. func shadowsocksMethodFromSettings(settings string) string {
  313. if settings == "" {
  314. return ""
  315. }
  316. var m map[string]any
  317. if err := json.Unmarshal([]byte(settings), &m); err != nil {
  318. return ""
  319. }
  320. method, _ := m["method"].(string)
  321. return method
  322. }
  323. func randomShadowsocksClientKey(method string) string {
  324. if n := shadowsocksKeyBytes(method); n > 0 {
  325. return random.Base64Bytes(n)
  326. }
  327. return strings.ReplaceAll(uuid.NewString(), "-", "")
  328. }
  329. func validShadowsocksClientKey(method, key string) bool {
  330. n := shadowsocksKeyBytes(method)
  331. if n == 0 {
  332. return key != ""
  333. }
  334. decoded, err := base64.StdEncoding.DecodeString(key)
  335. if err != nil {
  336. return false
  337. }
  338. return len(decoded) == n
  339. }
  340. func shadowsocksKeyBytes(method string) int {
  341. switch method {
  342. case "2022-blake3-aes-128-gcm":
  343. return 16
  344. case "2022-blake3-aes-256-gcm", "2022-blake3-chacha20-poly1305":
  345. return 32
  346. }
  347. return 0
  348. }
  349. // normalizeShadowsocksClientKeys rewrites any Shadowsocks-2022 client password
  350. // whose decoded length no longer matches settings.method, which happens after the
  351. // inbound method is switched between ciphers of different key sizes (e.g.
  352. // aes-256↔aes-128). A wrong-length uPSK makes xray reject the user, so the link
  353. // fails to connect; regenerating restores a valid key (clients must re-fetch).
  354. // Non-Shadowsocks / legacy-SS settings pass through unchanged.
  355. func normalizeShadowsocksClientKeys(settings string) (string, bool) {
  356. method := shadowsocksMethodFromSettings(settings)
  357. if shadowsocksKeyBytes(method) == 0 {
  358. return settings, false
  359. }
  360. var m map[string]any
  361. if err := json.Unmarshal([]byte(settings), &m); err != nil {
  362. return settings, false
  363. }
  364. clients, ok := m["clients"].([]any)
  365. if !ok {
  366. return settings, false
  367. }
  368. changed := false
  369. for i := range clients {
  370. c, ok := clients[i].(map[string]any)
  371. if !ok {
  372. continue
  373. }
  374. if pw, _ := c["password"].(string); validShadowsocksClientKey(method, pw) {
  375. continue
  376. }
  377. c["password"] = randomShadowsocksClientKey(method)
  378. clients[i] = c
  379. changed = true
  380. }
  381. if !changed {
  382. return settings, false
  383. }
  384. m["clients"] = clients
  385. bs, err := json.MarshalIndent(m, "", " ")
  386. if err != nil {
  387. return settings, false
  388. }
  389. return string(bs), true
  390. }
  391. func applyShadowsocksClientMethod(clients []any, settings map[string]any) {
  392. method, _ := settings["method"].(string)
  393. is2022 := strings.HasPrefix(method, "2022-blake3-")
  394. for i := range clients {
  395. cm, ok := clients[i].(map[string]any)
  396. if !ok {
  397. continue
  398. }
  399. if is2022 {
  400. if _, hasKey := cm["method"]; hasKey {
  401. delete(cm, "method")
  402. clients[i] = cm
  403. }
  404. continue
  405. }
  406. if method == "" {
  407. continue
  408. }
  409. if existing, _ := cm["method"].(string); existing != "" {
  410. continue
  411. }
  412. cm["method"] = method
  413. clients[i] = cm
  414. }
  415. }
  416. func (s *ClientService) Update(inboundSvc *InboundService, id int, updated model.Client, limitHwid int, inboundFilter ...int) (bool, error) {
  417. existing, err := s.GetByID(id)
  418. if err != nil {
  419. return false, err
  420. }
  421. inboundIds, err := s.GetInboundIdsForRecord(id)
  422. if err != nil {
  423. return false, err
  424. }
  425. if len(inboundFilter) > 0 {
  426. allow := make(map[int]struct{}, len(inboundFilter))
  427. for _, fid := range inboundFilter {
  428. allow[fid] = struct{}{}
  429. }
  430. filtered := inboundIds[:0:0]
  431. for _, ibId := range inboundIds {
  432. if _, ok := allow[ibId]; ok {
  433. filtered = append(filtered, ibId)
  434. }
  435. }
  436. inboundIds = filtered
  437. }
  438. if strings.TrimSpace(updated.Email) == "" {
  439. return false, common.NewError("client email is required")
  440. }
  441. if err := validateClientEmail(updated.Email); err != nil {
  442. return false, err
  443. }
  444. if err := validateClientSubID(updated.SubID); err != nil {
  445. return false, err
  446. }
  447. if err := validateClientResetDay(updated.ResetDay); err != nil {
  448. return false, err
  449. }
  450. if err := validateClientResetMax(updated.ResetMax); err != nil {
  451. return false, err
  452. }
  453. if err := validateClientTrafficReset(updated.TrafficReset, updated.TrafficResetDay); err != nil {
  454. return false, err
  455. }
  456. normalizeClientTrafficReset(&updated)
  457. if updated.SubID == "" {
  458. updated.SubID = existing.SubID
  459. }
  460. if updated.SubID == "" {
  461. updated.SubID = uuid.NewString()
  462. }
  463. updated.UpdatedAt = time.Now().UnixMilli()
  464. if updated.CreatedAt == 0 {
  465. updated.CreatedAt = existing.CreatedAt
  466. }
  467. // Preserve existing credentials when the caller omits them, so a partial
  468. // update (e.g. only changing traffic/expiry) doesn't silently rotate the
  469. // client's UUID/password/auth via fillProtocolDefaults. Supplying a new
  470. // value still rotates it intentionally.
  471. if updated.ID == "" {
  472. updated.ID = existing.UUID
  473. }
  474. if updated.Password == "" {
  475. updated.Password = existing.Password
  476. }
  477. if updated.Auth == "" {
  478. updated.Auth = existing.Auth
  479. }
  480. if updated.Secret == "" {
  481. updated.Secret = existing.Secret
  482. }
  483. if updated.Email != existing.Email {
  484. var collisionCount int64
  485. if err := database.GetDB().Model(&model.ClientRecord{}).
  486. Where("email = ? AND id <> ?", updated.Email, id).
  487. Count(&collisionCount).Error; err != nil {
  488. return false, err
  489. }
  490. if collisionCount > 0 {
  491. return false, common.NewError("Duplicate email:", updated.Email)
  492. }
  493. }
  494. if updated.SubID != existing.SubID {
  495. var subCollision int64
  496. if err := database.GetDB().Model(&model.ClientRecord{}).
  497. Where("sub_id = ? AND id <> ?", updated.SubID, id).
  498. Count(&subCollision).Error; err != nil {
  499. return false, err
  500. }
  501. if subCollision > 0 {
  502. return false, common.NewError("Duplicate subId:", updated.SubID)
  503. }
  504. }
  505. needRestart := false
  506. for _, ibId := range inboundIds {
  507. inbound, getErr := inboundSvc.GetInbound(ibId)
  508. if getErr != nil {
  509. if errors.Is(getErr, gorm.ErrRecordNotFound) {
  510. if err := database.GetDB().
  511. Where("client_id = ? AND inbound_id = ?", id, ibId).
  512. Delete(&model.ClientInbound{}).Error; err != nil {
  513. return needRestart, err
  514. }
  515. continue
  516. }
  517. return needRestart, getErr
  518. }
  519. if existing.Email == "" {
  520. continue
  521. }
  522. if err := s.fillProtocolDefaults(&updated, inbound); err != nil {
  523. return needRestart, err
  524. }
  525. clientForInbound := updated
  526. if ips, ok := updated.AllowedIPsByInbound[ibId]; ok {
  527. clientForInbound.AllowedIPs = ips
  528. } else if !addressesFitAmneziaWGInbound(clientForInbound.AllowedIPs, inbound) {
  529. // A single shared AllowedIPs field (the common case for a caller
  530. // that never sends AllowedIPsByInbound) must never overwrite an
  531. // inbound it doesn't belong to -- e.g. a client attached to both
  532. // wg and awg saving its wg-labeled address would otherwise get
  533. // that same address silently written into the awg peer config
  534. // too. Clearing it here makes UpdateInboundClient's own
  535. // empty-AllowedIPs carry-forward (see its WireGuard/AmneziaWG
  536. // branch) preserve THIS inbound's existing, correct value
  537. // instead.
  538. clientForInbound.AllowedIPs = nil
  539. }
  540. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(clientForInbound, inbound)}})
  541. if mErr != nil {
  542. return needRestart, mErr
  543. }
  544. nr, upErr := s.UpdateInboundClient(inboundSvc, &model.Inbound{
  545. Id: ibId,
  546. Settings: string(settingsPayload),
  547. }, existing.Email)
  548. if upErr != nil {
  549. return needRestart, upErr
  550. }
  551. if nr {
  552. needRestart = true
  553. }
  554. }
  555. // UpdateInboundClient renames the record atomically with each inbound's
  556. // settings JSON; this direct write only covers records with no inbound left.
  557. if updated.Email != existing.Email {
  558. if err := database.GetDB().Model(&model.ClientRecord{}).
  559. Where("id = ? AND email = ?", id, existing.Email).
  560. Update("email", updated.Email).Error; err != nil {
  561. return needRestart, err
  562. }
  563. }
  564. if len(inboundIds) == 0 {
  565. merged := *existing
  566. applyClientRecordMerge(&merged, updated.ToRecord())
  567. if err := database.GetDB().Model(&model.ClientRecord{}).
  568. Where("id = ?", id).
  569. Updates(map[string]any{
  570. "sub_id": merged.SubID,
  571. "uuid": merged.UUID,
  572. "password": merged.Password,
  573. "auth": merged.Auth,
  574. "secret": merged.Secret,
  575. "flow": merged.Flow,
  576. "security": merged.Security,
  577. "wg_private_key": merged.PrivateKey,
  578. "wg_public_key": merged.PublicKey,
  579. "wg_allowed_ips": merged.AllowedIPs,
  580. "wg_pre_shared_key": merged.PreSharedKey,
  581. "wg_keep_alive": merged.KeepAlive,
  582. "limit_ip": merged.LimitIP,
  583. "total_gb": merged.TotalGB,
  584. "expiry_time": merged.ExpiryTime,
  585. "tg_id": merged.TgID,
  586. "comment": merged.Comment,
  587. "reset": merged.Reset,
  588. "reset_day": merged.ResetDay,
  589. "reset_max": merged.ResetMax,
  590. "traffic_reset": merged.TrafficReset,
  591. "traffic_reset_day": merged.TrafficResetDay,
  592. }).Error; err != nil {
  593. return needRestart, err
  594. }
  595. }
  596. reverseStr := ""
  597. if updated.Reverse != nil && strings.TrimSpace(updated.Reverse.Tag) != "" {
  598. if b, mErr := json.Marshal(updated.Reverse); mErr == nil {
  599. reverseStr = string(b)
  600. }
  601. }
  602. if err := database.GetDB().Model(&model.ClientRecord{}).
  603. Where("id = ?", id).
  604. Update("reverse", reverseStr).Error; err != nil {
  605. return needRestart, err
  606. }
  607. // Persist the group explicitly. SyncInbound deliberately preserves the
  608. // stored group when the inbound settings carry none — so a node snapshot or a
  609. // group-less settings rebuild can't wipe it (see SyncInbound + its tests).
  610. // That guard also meant clearing the group in the client editor never took
  611. // effect. The editor always round-trips the field, so apply it here,
  612. // including the empty string that removes the client from its group.
  613. if err := database.GetDB().Model(&model.ClientRecord{}).
  614. Where("id = ?", id).
  615. UpdateColumn("group_name", updated.Group).Error; err != nil {
  616. return needRestart, err
  617. }
  618. // Same shape as the group write above: SyncInbound keeps a stored ad-tag
  619. // when the incoming settings carry none, so clearing the override must be
  620. // applied here, where the editor always round-trips the field.
  621. if err := database.GetDB().Model(&model.ClientRecord{}).
  622. Where("id = ?", id).
  623. UpdateColumn("ad_tag", updated.AdTag).Error; err != nil {
  624. return needRestart, err
  625. }
  626. if err := database.GetDB().Model(&model.ClientRecord{}).
  627. Where("id = ?", id).
  628. UpdateColumn("enable", updated.Enable).Error; err != nil {
  629. return needRestart, err
  630. }
  631. if err := s.setClientLimitHwidByEmail(nil, updated.Email, limitHwid); err != nil {
  632. return needRestart, err
  633. }
  634. if err := database.GetDB().Model(&model.ClientRecord{}).
  635. Where("id = ?", id).
  636. UpdateColumn("updated_at", time.Now().UnixMilli()).Error; err != nil {
  637. return needRestart, err
  638. }
  639. return needRestart, nil
  640. }
  641. func (s *ClientService) Delete(inboundSvc *InboundService, id int, keepTraffic bool) (bool, error) {
  642. existing, err := s.GetByID(id)
  643. if err != nil {
  644. return false, err
  645. }
  646. tombstoneClientEmail(existing.Email)
  647. inboundIds, err := s.GetInboundIdsForRecord(id)
  648. if err != nil {
  649. withdrawClientTombstones(existing.Email)
  650. return false, err
  651. }
  652. needRestart := false
  653. var delErrs []error
  654. for _, ibId := range inboundIds {
  655. if _, getErr := inboundSvc.GetInbound(ibId); getErr != nil {
  656. if errors.Is(getErr, gorm.ErrRecordNotFound) {
  657. continue
  658. }
  659. delErrs = append(delErrs, fmt.Errorf("inbound %d: %w", ibId, getErr))
  660. continue
  661. }
  662. // Always delete by email — the client's stable identity. This removes
  663. // every matching entry from the inbound's settings even when the stored
  664. // credential (UUID/password/auth) drifted from the inbound JSON, or a
  665. // duplicate entry with the same email exists.
  666. if existing.Email == "" {
  667. continue
  668. }
  669. nr, delErr := s.DelInboundClientByEmail(inboundSvc, ibId, existing.Email, keepTraffic, true)
  670. if delErr != nil {
  671. // The client is already absent from this inbound (data drift or a
  672. // retried delete). Skip it — deletion stays idempotent.
  673. if errors.Is(delErr, ErrClientNotInInbound) {
  674. continue
  675. }
  676. delErrs = append(delErrs, fmt.Errorf("inbound %d: %w", ibId, delErr))
  677. continue
  678. }
  679. if nr {
  680. needRestart = true
  681. }
  682. }
  683. // A failed inbound still holds the client in its settings JSON: keep the
  684. // record so the next delete retries exactly the leftovers, and report it.
  685. // The tombstone lifts with it, or the next node merge finishes the deletion.
  686. if len(delErrs) > 0 {
  687. withdrawClientTombstones(existing.Email)
  688. return needRestart, errors.Join(delErrs...)
  689. }
  690. db := database.GetDB()
  691. if err := db.Transaction(func(tx *gorm.DB) error {
  692. if existing.Email != "" {
  693. if err := adjustGroupBaselinesForRemovedTraffic(tx, []string{existing.Email}); err != nil {
  694. return err
  695. }
  696. }
  697. if err := tx.Where("client_id = ?", id).Delete(&model.ClientInbound{}).Error; err != nil {
  698. return err
  699. }
  700. if err := tx.Where("client_id = ?", id).Delete(&model.ClientExternalLink{}).Error; err != nil {
  701. return err
  702. }
  703. if err := clearClientHwidsBySubIDTx(tx, existing.SubID); err != nil {
  704. return err
  705. }
  706. if !keepTraffic && existing.Email != "" {
  707. if err := tx.Where("email = ?", existing.Email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  708. return err
  709. }
  710. if err := clearGlobalTraffic(tx, existing.Email); err != nil {
  711. return err
  712. }
  713. if err := tx.Where("client_email = ?", existing.Email).Delete(&model.InboundClientIps{}).Error; err != nil {
  714. return err
  715. }
  716. if err := tx.Where("email = ?", existing.Email).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  717. return err
  718. }
  719. }
  720. return tx.Delete(&model.ClientRecord{}, id).Error
  721. }); err != nil {
  722. withdrawClientTombstones(existing.Email)
  723. return needRestart, err
  724. }
  725. return needRestart, nil
  726. }
  727. // hasTunnelAttachment reports whether any of inboundIds is a currently
  728. // existing WireGuard or AmneziaWG inbound. Inbounds that fail to load are
  729. // skipped rather than treated as an error -- Attach's own loop already
  730. // surfaces a real error for any inbound it can't load when it gets there.
  731. func (s *ClientService) hasTunnelAttachment(inboundSvc *InboundService, inboundIds []int) bool {
  732. for _, ibId := range inboundIds {
  733. inbound, err := inboundSvc.GetInbound(ibId)
  734. if err != nil {
  735. continue
  736. }
  737. if inbound.Protocol == model.WireGuard || inbound.Protocol == model.AmneziaWG {
  738. return true
  739. }
  740. }
  741. return false
  742. }
  743. // addressesFitAmneziaWGInbound reports whether every entry in addrs falls
  744. // inside ib's own configured subnet(s). AmneziaWG only: its kernel interface
  745. // Address is exactly that subnet, so an address inherited from elsewhere (an
  746. // identity attached to a WireGuard inbound first, say) produces a peer that
  747. // can never connect -- Attach allocates fresh instead.
  748. func addressesFitAmneziaWGInbound(addrs []string, ib *model.Inbound) bool {
  749. if ib.Protocol != model.AmneziaWG || len(addrs) == 0 {
  750. return true
  751. }
  752. v4Base, v6Base, err := defaultAmneziaWGSubnetBases(ib.Settings)
  753. if err != nil {
  754. return false
  755. }
  756. bases := make([]netip.Prefix, 0, 2)
  757. for _, base := range []string{v4Base, v6Base} {
  758. if base == "" {
  759. continue
  760. }
  761. prefix, pErr := netip.ParsePrefix(base)
  762. if pErr != nil {
  763. return false
  764. }
  765. bases = append(bases, prefix)
  766. }
  767. for _, a := range addrs {
  768. host := wireguardHostAddr(a)
  769. if !host.IsValid() {
  770. return false
  771. }
  772. fits := false
  773. for _, prefix := range bases {
  774. if prefix.Contains(host) {
  775. fits = true
  776. break
  777. }
  778. }
  779. if !fits {
  780. return false
  781. }
  782. }
  783. return true
  784. }
  785. // Attach applies the client to every requested inbound: one failing inbound no
  786. // longer aborts the others, so the error can name several and needRestart holds.
  787. func (s *ClientService) Attach(inboundSvc *InboundService, id int, inboundIds []int) (bool, error) {
  788. existing, err := s.GetByID(id)
  789. if err != nil {
  790. return false, err
  791. }
  792. currentIds, err := s.GetInboundIdsForRecord(id)
  793. if err != nil {
  794. return false, err
  795. }
  796. have := make(map[int]struct{}, len(currentIds))
  797. for _, x := range currentIds {
  798. have[x] = struct{}{}
  799. }
  800. clientWire := existing.ToClient()
  801. flow, ffErr := s.EffectiveFlow(nil, id)
  802. if ffErr != nil {
  803. return false, ffErr
  804. }
  805. clientWire.Flow = flow
  806. clientWire.UpdatedAt = time.Now().UnixMilli()
  807. // If this identity has no CURRENT WireGuard/AmneziaWG attachment,
  808. // clientWire.AllowedIPs (from the ClientRecord) is a leftover from
  809. // whenever it last had one -- nothing reserves it anymore. Clear it so
  810. // attaching to a tunnel inbound now allocates a fresh address instead
  811. // of resurrecting the old one, which may no longer even be the lowest
  812. // free slot. Left untouched when the identity already has an active
  813. // tunnel elsewhere, so extending it to a second protocol still keeps
  814. // the same address on both.
  815. if !s.hasTunnelAttachment(inboundSvc, currentIds) {
  816. clientWire.AllowedIPs = nil
  817. }
  818. adds := make([]*model.Inbound, 0, len(inboundIds))
  819. for _, ibId := range inboundIds {
  820. if _, attached := have[ibId]; attached {
  821. continue
  822. }
  823. inbound, getErr := inboundSvc.GetInbound(ibId)
  824. if getErr != nil {
  825. return false, fmt.Errorf("inbound %d: %w", ibId, getErr)
  826. }
  827. copyClient := *clientWire
  828. if !addressesFitAmneziaWGInbound(copyClient.AllowedIPs, inbound) {
  829. copyClient.AllowedIPs = nil
  830. }
  831. if err := s.fillProtocolDefaults(&copyClient, inbound); err != nil {
  832. return false, fmt.Errorf("inbound %d: %w", ibId, err)
  833. }
  834. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(copyClient, inbound)}})
  835. if mErr != nil {
  836. return false, fmt.Errorf("inbound %d: %w", ibId, mErr)
  837. }
  838. adds = append(adds, &model.Inbound{Id: ibId, Settings: string(settingsPayload)})
  839. }
  840. return s.fanoutInboundClientAdds(inboundSvc, adds)
  841. }
  842. func (s *ClientService) CreateOne(inboundSvc *InboundService, inboundId int, client model.Client) (bool, error) {
  843. return s.Create(inboundSvc, &ClientCreatePayload{
  844. Client: client,
  845. InboundIds: []int{inboundId},
  846. })
  847. }
  848. func (s *ClientService) DetachByEmail(inboundSvc *InboundService, inboundId int, email string) (bool, error) {
  849. if email == "" {
  850. return false, common.NewError("client email is required")
  851. }
  852. rec, err := s.GetRecordByEmail(nil, email)
  853. if err != nil {
  854. return false, err
  855. }
  856. return s.Detach(inboundSvc, rec.Id, []int{inboundId})
  857. }
  858. func (s *ClientService) AttachByEmail(inboundSvc *InboundService, email string, inboundIds []int) (bool, error) {
  859. if email == "" {
  860. return false, common.NewError("client email is required")
  861. }
  862. rec, err := s.GetRecordByEmail(nil, email)
  863. if err != nil {
  864. return false, err
  865. }
  866. return s.Attach(inboundSvc, rec.Id, inboundIds)
  867. }
  868. func (s *ClientService) DetachByEmailMany(inboundSvc *InboundService, email string, inboundIds []int) (bool, error) {
  869. if email == "" {
  870. return false, common.NewError("client email is required")
  871. }
  872. rec, err := s.GetRecordByEmail(nil, email)
  873. if err != nil {
  874. return false, err
  875. }
  876. return s.Detach(inboundSvc, rec.Id, inboundIds)
  877. }
  878. func (s *ClientService) DeleteByEmail(inboundSvc *InboundService, email string, keepTraffic bool) (bool, error) {
  879. if email == "" {
  880. return false, common.NewError("client email is required")
  881. }
  882. rec, err := s.GetRecordByEmail(nil, email)
  883. if err == nil {
  884. return s.Delete(inboundSvc, rec.Id, keepTraffic)
  885. }
  886. if !errors.Is(err, gorm.ErrRecordNotFound) {
  887. return false, err
  888. }
  889. inboundIds, idsErr := s.findInboundIdsByClientEmail(email)
  890. if idsErr != nil {
  891. return false, idsErr
  892. }
  893. if len(inboundIds) == 0 {
  894. return false, common.NewError(fmt.Sprintf("client %q not found in any inbound or client record", email))
  895. }
  896. needRestart := false
  897. var delErrs []error
  898. for _, ibId := range inboundIds {
  899. nr, delErr := s.DelInboundClientByEmail(inboundSvc, ibId, email, keepTraffic, true)
  900. if delErr != nil {
  901. if errors.Is(delErr, ErrClientNotInInbound) {
  902. continue
  903. }
  904. delErrs = append(delErrs, fmt.Errorf("inbound %d: %w", ibId, delErr))
  905. continue
  906. }
  907. if nr {
  908. needRestart = true
  909. }
  910. }
  911. if len(delErrs) > 0 {
  912. return needRestart, errors.Join(delErrs...)
  913. }
  914. if !keepTraffic {
  915. db := database.GetDB()
  916. if err := db.Where("email = ?", email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  917. return needRestart, err
  918. }
  919. if err := clearGlobalTraffic(db, email); err != nil {
  920. return needRestart, err
  921. }
  922. if err := db.Where("client_email = ?", email).Delete(&model.InboundClientIps{}).Error; err != nil {
  923. return needRestart, err
  924. }
  925. if err := db.Where("email = ?", email).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  926. return needRestart, err
  927. }
  928. }
  929. return needRestart, nil
  930. }
  931. func (s *ClientService) UpdateByEmail(inboundSvc *InboundService, email string, updated model.Client, limitHwid int, inboundFilter ...int) (bool, error) {
  932. if email == "" {
  933. return false, common.NewError("client email is required")
  934. }
  935. rec, err := s.GetRecordByEmail(nil, email)
  936. if err != nil {
  937. return false, err
  938. }
  939. return s.Update(inboundSvc, rec.Id, updated, limitHwid, inboundFilter...)
  940. }
  941. func (s *ClientService) Detach(inboundSvc *InboundService, id int, inboundIds []int) (bool, error) {
  942. existing, err := s.GetByID(id)
  943. if err != nil {
  944. return false, err
  945. }
  946. currentIds, err := s.GetInboundIdsForRecord(id)
  947. if err != nil {
  948. return false, err
  949. }
  950. have := make(map[int]struct{}, len(currentIds))
  951. for _, x := range currentIds {
  952. have[x] = struct{}{}
  953. }
  954. needRestart := false
  955. for _, ibId := range inboundIds {
  956. if _, attached := have[ibId]; !attached {
  957. continue
  958. }
  959. if _, getErr := inboundSvc.GetInbound(ibId); getErr != nil {
  960. return needRestart, getErr
  961. }
  962. // Detach by email — the client's stable identity (see Delete).
  963. if existing.Email == "" {
  964. continue
  965. }
  966. nr, delErr := s.DelInboundClientByEmail(inboundSvc, ibId, existing.Email, true, false)
  967. if delErr != nil {
  968. if errors.Is(delErr, ErrClientNotInInbound) {
  969. continue
  970. }
  971. return needRestart, delErr
  972. }
  973. if nr {
  974. needRestart = true
  975. }
  976. }
  977. return needRestart, nil
  978. }