1
0

client_crud.go 34 KB

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