client_link.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. package service
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/google/uuid"
  6. "github.com/mhsanaei/3x-ui/v3/internal/database"
  7. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  8. "gorm.io/gorm"
  9. "gorm.io/gorm/clause"
  10. )
  11. // applyClientRecordMerge merges incoming client-record fields onto row using the
  12. // same rules everywhere a client record is persisted: scalar quota / lifecycle /
  13. // subscription fields are applied unconditionally (so clearing them takes
  14. // effect), while credentials and identifiers are only overwritten when the
  15. // incoming value is non-empty (so a partial update preserves the stored UUID /
  16. // password / keys). CreatedAt keeps the earliest known value. Email, UpdatedAt,
  17. // and the Id primary key are intentionally not touched here — callers handle
  18. // those separately. Shared by SyncInbound (per-inbound persistence) and Update
  19. // (the no-attached-inbound fallback) so the two paths cannot diverge.
  20. func applyClientRecordMerge(row *model.ClientRecord, incoming *model.ClientRecord) {
  21. if incoming.UUID != "" {
  22. row.UUID = incoming.UUID
  23. }
  24. if incoming.Password != "" {
  25. row.Password = incoming.Password
  26. }
  27. if incoming.Auth != "" {
  28. row.Auth = incoming.Auth
  29. }
  30. if incoming.Secret != "" {
  31. row.Secret = incoming.Secret
  32. }
  33. if incoming.AdTag != "" {
  34. row.AdTag = incoming.AdTag
  35. }
  36. row.Flow = incoming.Flow
  37. if incoming.Security != "" {
  38. row.Security = incoming.Security
  39. }
  40. if incoming.Reverse != "" {
  41. row.Reverse = incoming.Reverse
  42. }
  43. if incoming.PrivateKey != "" {
  44. row.PrivateKey = incoming.PrivateKey
  45. }
  46. if incoming.PublicKey != "" {
  47. row.PublicKey = incoming.PublicKey
  48. }
  49. if incoming.AllowedIPs != "" {
  50. row.AllowedIPs = incoming.AllowedIPs
  51. }
  52. row.PreSharedKey = incoming.PreSharedKey
  53. row.KeepAlive = incoming.KeepAlive
  54. row.SubID = incoming.SubID
  55. row.LimitIP = incoming.LimitIP
  56. row.TotalGB = incoming.TotalGB
  57. row.ExpiryTime = incoming.ExpiryTime
  58. row.Enable = incoming.Enable
  59. row.TgID = incoming.TgID
  60. if incoming.Group != "" {
  61. row.Group = incoming.Group
  62. }
  63. row.Comment = incoming.Comment
  64. row.Reset = incoming.Reset
  65. row.ResetDay = incoming.ResetDay
  66. row.ResetWeekday = incoming.ResetWeekday
  67. row.ResetMax = incoming.ResetMax
  68. // Guarded like Group and AdTag: a node snapshot rebuilt from settings that
  69. // predate the cycle would otherwise silently erase it.
  70. if incoming.TrafficReset != "" {
  71. row.TrafficReset = incoming.TrafficReset
  72. }
  73. if incoming.TrafficResetDay > 0 {
  74. row.TrafficResetDay = incoming.TrafficResetDay
  75. }
  76. if incoming.CreatedAt > 0 && (row.CreatedAt == 0 || incoming.CreatedAt < row.CreatedAt) {
  77. row.CreatedAt = incoming.CreatedAt
  78. }
  79. }
  80. // SyncInbound makes the inbound's client records and links match clients
  81. // exactly: links for clients no longer in the set are removed.
  82. func (s *ClientService) SyncInbound(tx *gorm.DB, inboundId int, clients []model.Client) error {
  83. return s.syncInboundClients(tx, inboundId, clients, nil, true)
  84. }
  85. // ApplyInboundClientDelta persists only the clients an edit actually changed
  86. // plus the emails it detached, leaving every other link on the inbound alone —
  87. // the whole point being that a one-client edit must not rewrite the inbound's
  88. // entire membership set (#6252).
  89. func (s *ClientService) ApplyInboundClientDelta(tx *gorm.DB, inboundId int, changed []model.Client, detachEmails []string) error {
  90. return s.syncInboundClients(tx, inboundId, changed, detachEmails, false)
  91. }
  92. func (s *ClientService) syncInboundClients(tx *gorm.DB, inboundId int, clients []model.Client, detachEmails []string, prune bool) error {
  93. if err := validateClientsRenewal(clients); err != nil {
  94. return err
  95. }
  96. if tx == nil {
  97. tx = database.GetDB()
  98. }
  99. var inbound model.Inbound
  100. if err := tx.Select("protocol").Where("id = ?", inboundId).Take(&inbound).Error; err != nil {
  101. return err
  102. }
  103. if err := s.validateProtocolClients(tx, inbound.Protocol, inboundId, clients, detachEmails, prune); err != nil {
  104. return err
  105. }
  106. emails := make([]string, 0, len(clients))
  107. seen := make(map[string]struct{}, len(clients))
  108. for i := range clients {
  109. email := strings.TrimSpace(clients[i].Email)
  110. if email == "" {
  111. continue
  112. }
  113. if _, ok := seen[email]; ok {
  114. continue
  115. }
  116. seen[email] = struct{}{}
  117. emails = append(emails, email)
  118. }
  119. existing := make(map[string]*model.ClientRecord, len(emails))
  120. const selectChunk = 400
  121. for start := 0; start < len(emails); start += selectChunk {
  122. end := min(start+selectChunk, len(emails))
  123. var rows []model.ClientRecord
  124. if err := tx.Where("email IN ?", emails[start:end]).Find(&rows).Error; err != nil {
  125. return err
  126. }
  127. for i := range rows {
  128. r := rows[i]
  129. existing[r.Email] = &r
  130. }
  131. }
  132. isTunnel := inbound.Protocol == model.WireGuard || inbound.Protocol == model.AmneziaWG
  133. var onLowerTunnel map[int]struct{}
  134. if isTunnel && len(existing) > 0 {
  135. ids := make([]int, 0, len(existing))
  136. for _, row := range existing {
  137. ids = append(ids, row.Id)
  138. }
  139. var err error
  140. if onLowerTunnel, err = clientsOnLowerTunnel(tx, inboundId, ids); err != nil {
  141. return err
  142. }
  143. }
  144. idByEmail := make(map[string]int, len(emails))
  145. pending := make(map[string]*model.ClientRecord, len(emails))
  146. toCreate := make([]*model.ClientRecord, 0, len(emails))
  147. for i := range clients {
  148. email := strings.TrimSpace(clients[i].Email)
  149. if email == "" {
  150. continue
  151. }
  152. incoming := clients[i].ToRecord()
  153. // ToRecord copies the raw email; store the trimmed key this function
  154. // looks up by, or a padded email is inserted and never found again.
  155. incoming.Email = email
  156. row, ok := existing[email]
  157. if !ok {
  158. if _, dup := pending[email]; !dup {
  159. pending[email] = incoming
  160. toCreate = append(toCreate, incoming)
  161. }
  162. continue
  163. }
  164. before := *row
  165. applyClientRecordMerge(row, incoming)
  166. _, outranked := onLowerTunnel[row.Id]
  167. keepLinkOwnedFields(row, &before, isTunnel && !outranked)
  168. preservedUpdatedAt := max(incoming.UpdatedAt, row.UpdatedAt)
  169. row.UpdatedAt = preservedUpdatedAt
  170. idByEmail[email] = row.Id
  171. if *row == before {
  172. continue
  173. }
  174. if err := tx.Save(row).Error; err != nil {
  175. return err
  176. }
  177. if err := tx.Model(&model.ClientRecord{}).
  178. Where("id = ?", row.Id).
  179. UpdateColumn("updated_at", preservedUpdatedAt).Error; err != nil {
  180. return err
  181. }
  182. }
  183. if len(toCreate) > 0 {
  184. // Capture enable before Create: gorm default:true drops explicit false (#6478).
  185. // Restate disabled rows after CreateInBatches.
  186. wantEnable := make([]bool, len(toCreate))
  187. for i, rec := range toCreate {
  188. wantEnable[i] = rec.Enable
  189. }
  190. if err := tx.CreateInBatches(toCreate, 200).Error; err != nil {
  191. return err
  192. }
  193. disabledIDs := make([]int, 0)
  194. for i, rec := range toCreate {
  195. idByEmail[rec.Email] = rec.Id
  196. if !wantEnable[i] {
  197. disabledIDs = append(disabledIDs, rec.Id)
  198. }
  199. }
  200. for _, batch := range chunkInts(disabledIDs, sqlInChunk) {
  201. if err := tx.Model(&model.ClientRecord{}).Where("id IN ?", batch).
  202. UpdateColumn("enable", false).Error; err != nil {
  203. return err
  204. }
  205. }
  206. }
  207. wantedFlow := make(map[int]string, len(clients))
  208. wantedIds := make([]int, 0, len(clients))
  209. for i := range clients {
  210. email := strings.TrimSpace(clients[i].Email)
  211. if email == "" {
  212. continue
  213. }
  214. id, ok := idByEmail[email]
  215. if !ok {
  216. continue
  217. }
  218. if _, dup := wantedFlow[id]; dup {
  219. continue
  220. }
  221. wantedFlow[id] = clients[i].Flow
  222. wantedIds = append(wantedIds, id)
  223. }
  224. relinked, err := s.reconcileInboundLinks(tx, inboundId, wantedFlow, wantedIds, detachEmails, prune)
  225. if err != nil {
  226. return err
  227. }
  228. if err := settleRecordFlows(tx, relinked); err != nil {
  229. return err
  230. }
  231. affected := map[int]struct{}{inboundId: {}}
  232. for _, ids := range chunkInts(wantedIds, sqlInChunk) {
  233. var inboundIDs []int
  234. if err := tx.Model(&model.ClientInbound{}).Distinct("inbound_id").Where("client_id IN ?", ids).Pluck("inbound_id", &inboundIDs).Error; err != nil {
  235. return err
  236. }
  237. for _, id := range inboundIDs {
  238. affected[id] = struct{}{}
  239. }
  240. }
  241. affectedIDs := make([]int, 0, len(affected))
  242. for id := range affected {
  243. affectedIDs = append(affectedIDs, id)
  244. }
  245. for _, ids := range chunkInts(affectedIDs, sqlInChunk) {
  246. var duplicates int64
  247. err := tx.Raw(`SELECT COUNT(*) FROM (
  248. SELECT ci.inbound_id, LOWER(c.uuid) FROM clients c
  249. JOIN client_inbounds ci ON ci.client_id = c.id
  250. JOIN inbounds i ON i.id = ci.inbound_id
  251. WHERE i.protocol = ? AND c.uuid <> '' AND ci.inbound_id IN ?
  252. GROUP BY ci.inbound_id, LOWER(c.uuid) HAVING COUNT(*) > 1
  253. ) AS duplicate_uuids`, model.TUIC, ids).Scan(&duplicates).Error
  254. if err != nil {
  255. return err
  256. }
  257. if duplicates > 0 {
  258. return fmt.Errorf("TUIC: duplicate client UUID within inbound")
  259. }
  260. }
  261. return nil
  262. }
  263. // reconcileInboundLinks writes only the client_inbounds rows that differ and returns
  264. // their clients. prune also removes links absent from wantedFlow, as only a full sync may.
  265. func (s *ClientService) reconcileInboundLinks(tx *gorm.DB, inboundId int, wantedFlow map[int]string, wantedIds []int, detachEmails []string, prune bool) ([]int, error) {
  266. var current []model.ClientInbound
  267. if prune {
  268. if err := tx.Where("inbound_id = ?", inboundId).Find(&current).Error; err != nil {
  269. return nil, err
  270. }
  271. } else {
  272. for _, batch := range chunkInts(wantedIds, sqlInChunk) {
  273. var rows []model.ClientInbound
  274. if err := tx.Where("inbound_id = ? AND client_id IN ?", inboundId, batch).Find(&rows).Error; err != nil {
  275. return nil, err
  276. }
  277. current = append(current, rows...)
  278. }
  279. }
  280. var toDelete []int
  281. toUpdate := make(map[string][]int)
  282. have := make(map[int]struct{}, len(current))
  283. for _, link := range current {
  284. have[link.ClientId] = struct{}{}
  285. flow, keep := wantedFlow[link.ClientId]
  286. if !keep {
  287. if prune {
  288. toDelete = append(toDelete, link.ClientId)
  289. }
  290. continue
  291. }
  292. // Plain compare, not non-empty-wins: clearing a flow must persist "".
  293. if flow != link.FlowOverride {
  294. toUpdate[flow] = append(toUpdate[flow], link.ClientId)
  295. }
  296. }
  297. if len(detachEmails) > 0 {
  298. for _, batch := range chunkStrings(detachEmails, sqlInChunk) {
  299. var ids []int
  300. if err := tx.Model(&model.ClientRecord{}).Where("email IN ?", batch).Pluck("id", &ids).Error; err != nil {
  301. return nil, err
  302. }
  303. for _, id := range ids {
  304. if _, keep := wantedFlow[id]; !keep {
  305. toDelete = append(toDelete, id)
  306. }
  307. }
  308. }
  309. }
  310. toInsert := make([]model.ClientInbound, 0, len(wantedIds))
  311. for _, id := range wantedIds {
  312. if _, exists := have[id]; exists {
  313. continue
  314. }
  315. toInsert = append(toInsert, model.ClientInbound{
  316. ClientId: id,
  317. InboundId: inboundId,
  318. FlowOverride: wantedFlow[id],
  319. })
  320. }
  321. for _, batch := range chunkInts(toDelete, sqlInChunk) {
  322. if err := tx.Where("inbound_id = ? AND client_id IN ?", inboundId, batch).
  323. Delete(&model.ClientInbound{}).Error; err != nil {
  324. return nil, err
  325. }
  326. }
  327. for flow, ids := range toUpdate {
  328. for _, batch := range chunkInts(ids, sqlInChunk) {
  329. if err := tx.Model(&model.ClientInbound{}).
  330. Where("inbound_id = ? AND client_id IN ?", inboundId, batch).
  331. Update("flow_override", flow).Error; err != nil {
  332. return nil, err
  333. }
  334. }
  335. }
  336. if len(toInsert) > 0 {
  337. // The delete this replaced also serialized concurrent syncs of one
  338. // inbound; without the clause a racing node poll aborts its whole tx.
  339. if err := tx.Clauses(clause.OnConflict{
  340. Columns: []clause.Column{{Name: "client_id"}, {Name: "inbound_id"}},
  341. DoUpdates: clause.AssignmentColumns([]string{"flow_override"}),
  342. }).CreateInBatches(toInsert, 200).Error; err != nil {
  343. return nil, err
  344. }
  345. }
  346. relinked := append([]int(nil), toDelete...)
  347. for _, ids := range toUpdate {
  348. relinked = append(relinked, ids...)
  349. }
  350. for _, link := range toInsert {
  351. relinked = append(relinked, link.ClientId)
  352. }
  353. return relinked, nil
  354. }
  355. // keepLinkOwnedFields undoes the merge of the record fields one inbound cannot decide
  356. // alone, or syncing a client's inbounds in turn rewrites the record back and forth.
  357. func keepLinkOwnedFields(row, before *model.ClientRecord, ownsTunnelPeer bool) {
  358. row.Flow = before.Flow
  359. if ownsTunnelPeer {
  360. return
  361. }
  362. row.PrivateKey = before.PrivateKey
  363. row.PublicKey = before.PublicKey
  364. row.AllowedIPs = before.AllowedIPs
  365. row.PreSharedKey = before.PreSharedKey
  366. row.KeepAlive = before.KeepAlive
  367. }
  368. // clientsOnLowerTunnel returns the clients also attached to a WireGuard/AmneziaWG
  369. // inbound with a lower id than inboundId: that tunnel owns their record's peer fields.
  370. func clientsOnLowerTunnel(tx *gorm.DB, inboundId int, clientIds []int) (map[int]struct{}, error) {
  371. out := make(map[int]struct{})
  372. for _, batch := range chunkInts(clientIds, sqlInChunk) {
  373. var ids []int
  374. if err := tx.Table("client_inbounds").
  375. Joins("JOIN inbounds ON inbounds.id = client_inbounds.inbound_id").
  376. Where("client_inbounds.client_id IN ? AND client_inbounds.inbound_id < ? AND inbounds.protocol IN ?",
  377. batch, inboundId, []model.Protocol{model.WireGuard, model.AmneziaWG}).
  378. Distinct().Pluck("client_inbounds.client_id", &ids).Error; err != nil {
  379. return nil, err
  380. }
  381. for _, id := range ids {
  382. out[id] = struct{}{}
  383. }
  384. }
  385. return out, nil
  386. }
  387. // settleRecordFlows sets the record flow of each still-linked client to its
  388. // effective flow (EffectiveFlow's rule); an unlinked record keeps its own.
  389. func settleRecordFlows(tx *gorm.DB, clientIds []int) error {
  390. for _, batch := range chunkInts(clientIds, sqlInChunk) {
  391. var links []model.ClientInbound
  392. if err := tx.Select("client_id", "flow_override").
  393. Where("client_id IN ?", batch).
  394. Order("inbound_id ASC").
  395. Find(&links).Error; err != nil {
  396. return err
  397. }
  398. effective := make(map[int]string, len(batch))
  399. for _, link := range links {
  400. if flow, seen := effective[link.ClientId]; !seen || (flow == "" && link.FlowOverride != "") {
  401. effective[link.ClientId] = link.FlowOverride
  402. }
  403. }
  404. var records []model.ClientRecord
  405. if err := tx.Select("id", "flow").Where("id IN ?", batch).Find(&records).Error; err != nil {
  406. return err
  407. }
  408. idsByFlow := make(map[string][]int)
  409. for _, rec := range records {
  410. if flow, linked := effective[rec.Id]; linked && flow != rec.Flow {
  411. idsByFlow[flow] = append(idsByFlow[flow], rec.Id)
  412. }
  413. }
  414. for flow, ids := range idsByFlow {
  415. if err := tx.Model(&model.ClientRecord{}).Where("id IN ?", ids).
  416. UpdateColumn("flow", flow).Error; err != nil {
  417. return err
  418. }
  419. }
  420. }
  421. return nil
  422. }
  423. func (s *ClientService) DetachInbound(tx *gorm.DB, inboundId int) error {
  424. if tx == nil {
  425. tx = database.GetDB()
  426. }
  427. return tx.Where("inbound_id = ?", inboundId).Delete(&model.ClientInbound{}).Error
  428. }
  429. func (s *ClientService) ListForInbound(tx *gorm.DB, inboundId int) ([]model.Client, error) {
  430. if tx == nil {
  431. tx = database.GetDB()
  432. }
  433. type joinedRow struct {
  434. model.ClientRecord
  435. FlowOverride string
  436. }
  437. var rows []joinedRow
  438. err := tx.Table("clients").
  439. Select("clients.*, client_inbounds.flow_override AS flow_override").
  440. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  441. Where("client_inbounds.inbound_id = ?", inboundId).
  442. Order("clients.id ASC").
  443. Find(&rows).Error
  444. if err != nil {
  445. return nil, err
  446. }
  447. out := make([]model.Client, 0, len(rows))
  448. for i := range rows {
  449. c := rows[i].ToClient()
  450. c.Flow = rows[i].FlowOverride
  451. out = append(out, *c)
  452. }
  453. return out, nil
  454. }
  455. // ListForInboundBySubId is ListForInbound narrowed to one subscription id —
  456. // both filter columns are indexed, so the subscription server resolves a
  457. // subscriber's clients without touching the inbound's settings JSON.
  458. func (s *ClientService) ListForInboundBySubId(tx *gorm.DB, inboundId int, subId string) ([]model.Client, error) {
  459. if tx == nil {
  460. tx = database.GetDB()
  461. }
  462. type joinedRow struct {
  463. model.ClientRecord
  464. FlowOverride string
  465. }
  466. var rows []joinedRow
  467. err := tx.Table("clients").
  468. Select("clients.*, client_inbounds.flow_override AS flow_override").
  469. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  470. Where("client_inbounds.inbound_id = ? AND clients.sub_id = ?", inboundId, subId).
  471. Order("clients.id ASC").
  472. Find(&rows).Error
  473. if err != nil {
  474. return nil, err
  475. }
  476. out := make([]model.Client, 0, len(rows))
  477. for i := range rows {
  478. c := rows[i].ToClient()
  479. c.Flow = rows[i].FlowOverride
  480. out = append(out, *c)
  481. }
  482. return out, nil
  483. }
  484. // validateProtocolClients runs inside the write every path linking clients to an inbound
  485. // shares, so a client the protocol's core config would refuse never reaches it.
  486. func (s *ClientService) validateProtocolClients(tx *gorm.DB, protocol model.Protocol, inboundID int, changed []model.Client, detached []string, prune bool) error {
  487. switch protocol {
  488. case model.TUIC:
  489. return s.validateTuicIdentities(tx, inboundID, changed, detached, prune)
  490. case model.MASQUE:
  491. return validateMasqueEmails(changed)
  492. }
  493. return nil
  494. }
  495. // MASQUE sends the email as the Basic-auth user, so xray-core refuses the whole inbound,
  496. // and with it the Xray start, over one email holding ":".
  497. func validateMasqueEmails(clients []model.Client) error {
  498. for _, client := range clients {
  499. if strings.Contains(client.Email, ":") {
  500. return fmt.Errorf("MASQUE: client email %q cannot contain \":\"", client.Email)
  501. }
  502. }
  503. return nil
  504. }
  505. func (s *ClientService) validateTuicIdentities(tx *gorm.DB, inboundID int, changed []model.Client, detached []string, prune bool) error {
  506. candidates := append([]model.Client(nil), changed...)
  507. if !prune {
  508. current, err := s.ListForInbound(tx, inboundID)
  509. if err != nil {
  510. return err
  511. }
  512. excluded := make(map[string]bool)
  513. for _, client := range changed {
  514. excluded[client.Email] = true
  515. }
  516. for _, email := range detached {
  517. excluded[email] = true
  518. }
  519. for _, client := range current {
  520. if !excluded[client.Email] {
  521. candidates = append(candidates, client)
  522. }
  523. }
  524. }
  525. seen := make(map[uuid.UUID]string)
  526. for _, client := range candidates {
  527. if client.ID == "" {
  528. continue
  529. }
  530. id, err := uuid.Parse(client.ID)
  531. if err != nil {
  532. return fmt.Errorf("TUIC: invalid client UUID")
  533. }
  534. if email, exists := seen[id]; exists && email != client.Email {
  535. return fmt.Errorf("TUIC: duplicate client UUID within inbound")
  536. }
  537. seen[id] = client.Email
  538. }
  539. return nil
  540. }