client_lookup.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. package service
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "strings"
  6. "github.com/mhsanaei/3x-ui/v3/internal/database"
  7. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  8. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  9. "gorm.io/gorm"
  10. )
  11. func (s *ClientService) GetRecordByEmail(tx *gorm.DB, email string) (*model.ClientRecord, error) {
  12. if tx == nil {
  13. tx = database.GetDB()
  14. }
  15. row := &model.ClientRecord{}
  16. err := tx.Where("email = ?", email).First(row).Error
  17. if err != nil {
  18. return nil, err
  19. }
  20. return row, nil
  21. }
  22. // EffectiveFlow returns the client's flow from the first flow-capable inbound
  23. // it is attached to (lowest inbound_id with a non-empty flow_override). The
  24. // canonical clients.Flow column is unreliable for multi-inbound clients: a
  25. // non-flow inbound (Hysteria, WS, gRPC, …) carries an empty flow and, when its
  26. // SyncInbound runs last, overwrites the column to "" even though a VLESS Reality
  27. // inbound stored a real flow. The per-inbound flow_override is always correct,
  28. // so derive the display flow from it (order-independent). See issue #4792.
  29. func (s *ClientService) EffectiveFlow(tx *gorm.DB, recordId int) (string, error) {
  30. if tx == nil {
  31. tx = database.GetDB()
  32. }
  33. var flows []string
  34. err := tx.Model(&model.ClientInbound{}).
  35. Where("client_id = ? AND flow_override <> ?", recordId, "").
  36. Order("inbound_id ASC").
  37. Limit(1).
  38. Pluck("flow_override", &flows).Error
  39. if err != nil {
  40. return "", err
  41. }
  42. if len(flows) == 0 {
  43. return "", nil
  44. }
  45. return flows[0], nil
  46. }
  47. // EffectiveFlowsByEmails resolves the intended flow (non-empty flow_override,
  48. // lowest inbound_id first — same rule as EffectiveFlow) for many clients in one
  49. // query, keyed by email. Emails absent from the result carry no flow anywhere.
  50. // Batched so flow restoration on an inbound with many clients is O(1) queries
  51. // instead of O(clients). Used to restore a stripped flow onto an inbound that
  52. // has just become flow-eligible.
  53. func (s *ClientService) EffectiveFlowsByEmails(tx *gorm.DB, emails []string) (map[string]string, error) {
  54. if tx == nil {
  55. tx = database.GetDB()
  56. }
  57. out := make(map[string]string, len(emails))
  58. if len(emails) == 0 {
  59. return out, nil
  60. }
  61. type row struct {
  62. Email string
  63. Flow string `gorm:"column:flow_override"`
  64. }
  65. for _, batch := range chunkStrings(emails, sqlInChunk) {
  66. var rows []row
  67. err := tx.Table("client_inbounds").
  68. Select("clients.email AS email, client_inbounds.flow_override AS flow_override").
  69. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  70. Where("clients.email IN ? AND client_inbounds.flow_override <> ?", batch, "").
  71. Order("client_inbounds.inbound_id ASC").
  72. Scan(&rows).Error
  73. if err != nil {
  74. return nil, err
  75. }
  76. for _, r := range rows {
  77. if _, seen := out[r.Email]; !seen { // ordered by inbound_id ASC → first = lowest
  78. out[r.Email] = r.Flow
  79. }
  80. }
  81. }
  82. return out, nil
  83. }
  84. func (s *ClientService) GetInboundIdsForEmail(tx *gorm.DB, email string) ([]int, error) {
  85. if tx == nil {
  86. tx = database.GetDB()
  87. }
  88. var ids []int
  89. err := tx.Table("client_inbounds").
  90. Select("client_inbounds.inbound_id").
  91. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  92. Where("clients.email = ?", email).
  93. Scan(&ids).Error
  94. if err != nil {
  95. return nil, err
  96. }
  97. return ids, nil
  98. }
  99. func (s *ClientService) GetRecordsByTgID(tgId int64) ([]*model.ClientRecord, error) {
  100. if tgId <= 0 {
  101. return nil, errors.New("tg_id must be a positive integer")
  102. }
  103. var rows []*model.ClientRecord
  104. err := database.GetDB().Where("tg_id = ?", tgId).Find(&rows).Error
  105. return rows, err
  106. }
  107. func (s *ClientService) GetByID(id int) (*model.ClientRecord, error) {
  108. row := &model.ClientRecord{}
  109. if err := database.GetDB().Where("id = ?", id).First(row).Error; err != nil {
  110. return nil, err
  111. }
  112. return row, nil
  113. }
  114. func (s *ClientService) GetInboundIdsForRecord(id int) ([]int, error) {
  115. var ids []int
  116. err := database.GetDB().Table("client_inbounds").
  117. Where("client_id = ?", id).
  118. Order("inbound_id ASC").
  119. Pluck("inbound_id", &ids).Error
  120. if err != nil {
  121. return nil, err
  122. }
  123. return ids, nil
  124. }
  125. // TunnelAllowedIPsByInbound returns, for each given WireGuard/AmneziaWG
  126. // inbound id, the real AllowedIPs this email currently has on that specific
  127. // inbound's own settings JSON -- joined comma-separated, matching the form
  128. // value shape a single AllowedIPs field already uses. Non-tunnel inbounds
  129. // and ids the email isn't actually attached to are simply absent from the
  130. // result (not an error): callers use this to seed a per-protocol display
  131. // field, and ClientRecord's own single AllowedIPs column can't tell two
  132. // different protocol addresses apart, which is exactly the gap this closes.
  133. func (s *ClientService) TunnelAllowedIPsByInbound(inboundSvc *InboundService, email string, inboundIds []int) (map[int]string, error) {
  134. result := make(map[int]string, len(inboundIds))
  135. for _, ibId := range inboundIds {
  136. inbound, err := inboundSvc.GetInbound(ibId)
  137. if err != nil {
  138. if errors.Is(err, gorm.ErrRecordNotFound) {
  139. continue
  140. }
  141. return nil, err
  142. }
  143. if inbound.Protocol != model.WireGuard && inbound.Protocol != model.AmneziaWG {
  144. continue
  145. }
  146. clients, err := inboundSvc.GetClients(inbound)
  147. if err != nil {
  148. return nil, err
  149. }
  150. for i := range clients {
  151. if strings.EqualFold(clients[i].Email, email) {
  152. result[ibId] = strings.Join(clients[i].AllowedIPs, ",")
  153. break
  154. }
  155. }
  156. }
  157. return result, nil
  158. }
  159. func (s *ClientService) List() ([]ClientWithAttachments, error) {
  160. db := database.GetDB()
  161. var rows []model.ClientRecord
  162. if err := db.Order("id ASC").Find(&rows).Error; err != nil {
  163. return nil, err
  164. }
  165. if len(rows) == 0 {
  166. return []ClientWithAttachments{}, nil
  167. }
  168. clientIds := make([]int, 0, len(rows))
  169. emails := make([]string, 0, len(rows))
  170. for i := range rows {
  171. clientIds = append(clientIds, rows[i].Id)
  172. if rows[i].Email != "" {
  173. emails = append(emails, rows[i].Email)
  174. }
  175. }
  176. attachments := make(map[int][]int, len(rows))
  177. for _, batch := range chunkInts(clientIds, sqlInChunk) {
  178. var links []model.ClientInbound
  179. if err := db.Where("client_id IN ?", batch).Find(&links).Error; err != nil {
  180. return nil, err
  181. }
  182. for _, l := range links {
  183. attachments[l.ClientId] = append(attachments[l.ClientId], l.InboundId)
  184. }
  185. }
  186. trafficByEmail := make(map[string]*xray.ClientTraffic, len(emails))
  187. if len(emails) > 0 {
  188. var stats []xray.ClientTraffic
  189. for _, batch := range chunkStrings(emails, sqlInChunk) {
  190. var batchStats []xray.ClientTraffic
  191. if err := db.Where("email IN ?", batch).Find(&batchStats).Error; err != nil {
  192. return nil, err
  193. }
  194. stats = append(stats, batchStats...)
  195. }
  196. overlayGlobalTrafficValues(db, stats)
  197. for i := range stats {
  198. trafficByEmail[stats[i].Email] = &stats[i]
  199. }
  200. }
  201. out := make([]ClientWithAttachments, 0, len(rows))
  202. for i := range rows {
  203. out = append(out, ClientWithAttachments{
  204. ClientRecord: rows[i],
  205. InboundIds: attachments[rows[i].Id],
  206. Traffic: trafficByEmail[rows[i].Email],
  207. })
  208. }
  209. return out, nil
  210. }
  211. func (s *ClientService) HasPendingNode(inboundSvc *InboundService, email string) bool {
  212. if strings.TrimSpace(email) == "" {
  213. return false
  214. }
  215. ids, err := s.GetInboundIdsForEmail(nil, email)
  216. if err != nil {
  217. return false
  218. }
  219. return inboundSvc.AnyNodePending(ids)
  220. }
  221. // findInboundIdsByClientEmail returns every inbound whose settings.clients[]
  222. // JSON contains an entry with the given email. Driver-portable (no JSON
  223. // operators) by parsing in Go — fine for the rare fallback path.
  224. func (s *ClientService) findInboundIdsByClientEmail(email string) ([]int, error) {
  225. var inbounds []model.Inbound
  226. if err := database.GetDB().
  227. Select("id, settings").
  228. Where("settings LIKE ?", "%"+email+"%").
  229. Find(&inbounds).Error; err != nil {
  230. return nil, err
  231. }
  232. out := make([]int, 0, len(inbounds))
  233. for _, ib := range inbounds {
  234. var settings map[string]any
  235. if err := json.Unmarshal([]byte(ib.Settings), &settings); err != nil {
  236. continue
  237. }
  238. clients, ok := settings["clients"].([]any)
  239. if !ok {
  240. continue
  241. }
  242. for _, c := range clients {
  243. cm, ok := c.(map[string]any)
  244. if !ok {
  245. continue
  246. }
  247. if cEmail, _ := cm["email"].(string); cEmail == email {
  248. out = append(out, ib.Id)
  249. break
  250. }
  251. }
  252. }
  253. return out, nil
  254. }