inbound_clients.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. package service
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "strings"
  7. "time"
  8. "github.com/google/uuid"
  9. "github.com/mhsanaei/3x-ui/v3/internal/database"
  10. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  11. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  12. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  13. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  14. "gorm.io/gorm"
  15. )
  16. type CopyClientsResult struct {
  17. Added []string `json:"added"`
  18. Skipped []string `json:"skipped"`
  19. Errors []string `json:"errors"`
  20. }
  21. // enrichClientStats resolves each inbound's clients from the clients table
  22. // once, fills in the UUID/SubId fields on the preloaded ClientStats, and tops
  23. // up rows owned by a sibling inbound (shared-email mode — the row is keyed on
  24. // email so it only preloads on its owning inbound). Reading identity from the
  25. // clients table keeps /inbounds/list in sync with the running Xray config
  26. // when the embedded settings JSON is stale (#6436).
  27. func (s *InboundService) enrichClientStats(db *gorm.DB, inbounds []*model.Inbound) {
  28. if len(inbounds) == 0 {
  29. return
  30. }
  31. clientsByInbound := s.backfillClientStats(db, inbounds)
  32. for i, inbound := range inbounds {
  33. clients := clientsByInbound[i]
  34. if len(clients) == 0 || len(inbound.ClientStats) == 0 {
  35. continue
  36. }
  37. cMap := make(map[string]model.Client, len(clients))
  38. for _, c := range clients {
  39. cMap[strings.ToLower(c.Email)] = c
  40. }
  41. for j := range inbound.ClientStats {
  42. email := strings.ToLower(inbound.ClientStats[j].Email)
  43. if c, ok := cMap[email]; ok {
  44. inbound.ClientStats[j].UUID = c.ID
  45. inbound.ClientStats[j].SubId = c.SubID
  46. }
  47. }
  48. }
  49. }
  50. // backfillClientStats tops up each inbound's preloaded ClientStats with rows
  51. // owned by a sibling inbound: client_traffics is keyed on email, so a client
  52. // attached to several inbounds has one row that only preloads on the inbound
  53. // it was created on. Returns the clients-table clients per inbound for reuse
  54. // (not the embedded settings JSON, which can lag the live UUID — #6436).
  55. func (s *InboundService) backfillClientStats(db *gorm.DB, inbounds []*model.Inbound) [][]model.Client {
  56. clientsByInbound := make([][]model.Client, len(inbounds))
  57. seenByInbound := make([]map[string]struct{}, len(inbounds))
  58. missing := make(map[string]struct{})
  59. for i, inbound := range inbounds {
  60. clients, _ := s.clientService.ListForInbound(db, inbound.Id)
  61. clientsByInbound[i] = clients
  62. seen := make(map[string]struct{}, len(inbound.ClientStats))
  63. for _, st := range inbound.ClientStats {
  64. if st.Email != "" {
  65. seen[strings.ToLower(st.Email)] = struct{}{}
  66. }
  67. }
  68. seenByInbound[i] = seen
  69. for _, c := range clients {
  70. if c.Email == "" {
  71. continue
  72. }
  73. if _, ok := seen[strings.ToLower(c.Email)]; !ok {
  74. missing[c.Email] = struct{}{}
  75. }
  76. }
  77. }
  78. if len(missing) > 0 {
  79. emails := make([]string, 0, len(missing))
  80. for e := range missing {
  81. emails = append(emails, e)
  82. }
  83. var extra []xray.ClientTraffic
  84. var loadErr error
  85. for _, batch := range chunkStrings(emails, sqlInChunk) {
  86. var page []xray.ClientTraffic
  87. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  88. loadErr = err
  89. break
  90. }
  91. extra = append(extra, page...)
  92. }
  93. if loadErr != nil {
  94. logger.Warning("backfillClientStats:", loadErr)
  95. } else {
  96. byEmail := make(map[string]xray.ClientTraffic, len(extra))
  97. for _, st := range extra {
  98. byEmail[strings.ToLower(st.Email)] = st
  99. }
  100. for i, inbound := range inbounds {
  101. for _, c := range clientsByInbound[i] {
  102. if c.Email == "" {
  103. continue
  104. }
  105. key := strings.ToLower(c.Email)
  106. if _, ok := seenByInbound[i][key]; ok {
  107. continue
  108. }
  109. if st, ok := byEmail[key]; ok {
  110. inbound.ClientStats = append(inbound.ClientStats, st)
  111. seenByInbound[i][key] = struct{}{}
  112. }
  113. }
  114. }
  115. }
  116. }
  117. return clientsByInbound
  118. }
  119. // emailUsedByOtherInbounds reports whether email lives in any inbound other
  120. // than exceptInboundId. Empty email returns false.
  121. func (s *InboundService) emailUsedByOtherInbounds(email string, exceptInboundId int) (bool, error) {
  122. if email == "" {
  123. return false, nil
  124. }
  125. var count int64
  126. err := database.GetDB().Table("client_inbounds").
  127. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  128. Where("client_inbounds.inbound_id != ? AND LOWER(clients.email) = ?",
  129. exceptInboundId, strings.ToLower(strings.TrimSpace(email))).
  130. Count(&count).Error
  131. if err != nil {
  132. return false, err
  133. }
  134. return count > 0, nil
  135. }
  136. func (s *InboundService) emailsUsedByOtherInbounds(emails []string, exceptInboundId int) (map[string]bool, error) {
  137. shared := make(map[string]bool, len(emails))
  138. want := make(map[string]struct{}, len(emails))
  139. for _, e := range emails {
  140. e = strings.ToLower(strings.TrimSpace(e))
  141. if e != "" {
  142. want[e] = struct{}{}
  143. }
  144. }
  145. if len(want) == 0 {
  146. return shared, nil
  147. }
  148. lowered := make([]string, 0, len(want))
  149. for e := range want {
  150. lowered = append(lowered, e)
  151. }
  152. db := database.GetDB()
  153. for _, batch := range chunkStrings(lowered, sqlInChunk) {
  154. var rows []struct{ Email string }
  155. err := db.Table("client_inbounds").
  156. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  157. Select("DISTINCT LOWER(clients.email) AS email").
  158. Where("client_inbounds.inbound_id != ? AND LOWER(clients.email) IN ?", exceptInboundId, batch).
  159. Scan(&rows).Error
  160. if err != nil {
  161. return nil, err
  162. }
  163. for _, r := range rows {
  164. shared[r.Email] = true
  165. }
  166. }
  167. return shared, nil
  168. }
  169. func (s *InboundService) writeBackClientSubID(sourceInboundID int, client model.Client, subID string) (bool, error) {
  170. client.SubID = subID
  171. client.UpdatedAt = time.Now().UnixMilli()
  172. if client.Email == "" {
  173. return false, common.NewError("empty client email")
  174. }
  175. settingsBytes, err := json.Marshal(map[string][]model.Client{
  176. "clients": {client},
  177. })
  178. if err != nil {
  179. return false, err
  180. }
  181. updatePayload := &model.Inbound{
  182. Id: sourceInboundID,
  183. Settings: string(settingsBytes),
  184. }
  185. return s.clientService.UpdateInboundClient(s, updatePayload, client.Email)
  186. }
  187. func (s *InboundService) generateRandomCredential(targetProtocol model.Protocol) string {
  188. switch targetProtocol {
  189. case model.VMESS, model.VLESS:
  190. return uuid.NewString()
  191. default:
  192. return strings.ReplaceAll(uuid.NewString(), "-", "")
  193. }
  194. }
  195. func (s *InboundService) buildTargetClientFromSource(source model.Client, targetInbound *model.Inbound, email string, flow string) (model.Client, error) {
  196. nowTs := time.Now().UnixMilli()
  197. target := source
  198. target.Email = email
  199. target.CreatedAt = nowTs
  200. target.UpdatedAt = nowTs
  201. target.ID = ""
  202. target.Password = ""
  203. target.Auth = ""
  204. target.Flow = ""
  205. target.Secret = ""
  206. targetProtocol := targetInbound.Protocol
  207. switch targetProtocol {
  208. case model.VMESS:
  209. target.ID = s.generateRandomCredential(targetProtocol)
  210. case model.VLESS:
  211. target.ID = s.generateRandomCredential(targetProtocol)
  212. if (flow == "xtls-rprx-vision" || flow == "xtls-rprx-vision-udp443") &&
  213. !targetInbound.DisableFlow &&
  214. inboundCanEnableTlsFlow(string(targetProtocol), targetInbound.StreamSettings, targetInbound.Settings) {
  215. target.Flow = flow
  216. }
  217. case model.Trojan, model.Shadowsocks:
  218. target.Password = s.generateRandomCredential(targetProtocol)
  219. case model.Hysteria:
  220. target.Auth = s.generateRandomCredential(targetProtocol)
  221. case model.MTProto:
  222. target.Secret = model.GenerateFakeTLSSecret(mtprotoDomainFromSettings(targetInbound.Settings))
  223. case model.TUIC:
  224. target.ID = uuid.NewString()
  225. target.Password = s.generateRandomCredential(targetProtocol)
  226. default:
  227. target.ID = s.generateRandomCredential(targetProtocol)
  228. }
  229. return target, nil
  230. }
  231. func (s *InboundService) nextAvailableCopiedEmail(originalEmail string, targetID int, occupied map[string]struct{}) string {
  232. base := fmt.Sprintf("%s_%d", originalEmail, targetID)
  233. candidate := base
  234. suffix := 0
  235. for {
  236. if _, exists := occupied[strings.ToLower(candidate)]; !exists {
  237. occupied[strings.ToLower(candidate)] = struct{}{}
  238. return candidate
  239. }
  240. suffix++
  241. candidate = fmt.Sprintf("%s_%d", base, suffix)
  242. }
  243. }
  244. func (s *InboundService) CopyInboundClients(targetInboundID int, sourceInboundID int, clientEmails []string, flow string) (*CopyClientsResult, bool, error) {
  245. result := &CopyClientsResult{
  246. Added: []string{},
  247. Skipped: []string{},
  248. Errors: []string{},
  249. }
  250. if targetInboundID == sourceInboundID {
  251. return result, false, common.NewError("source and target inbounds must be different")
  252. }
  253. targetInbound, err := s.GetInbound(targetInboundID)
  254. if err != nil {
  255. return result, false, err
  256. }
  257. sourceInbound, err := s.GetInbound(sourceInboundID)
  258. if err != nil {
  259. return result, false, err
  260. }
  261. sourceClients, err := s.GetClients(sourceInbound)
  262. if err != nil {
  263. return result, false, err
  264. }
  265. if len(sourceClients) == 0 {
  266. return result, false, nil
  267. }
  268. allowedEmails := map[string]struct{}{}
  269. if len(clientEmails) > 0 {
  270. for _, email := range clientEmails {
  271. allowedEmails[strings.ToLower(strings.TrimSpace(email))] = struct{}{}
  272. }
  273. }
  274. occupiedEmails := map[string]struct{}{}
  275. allEmails, err := s.GetAllEmails()
  276. if err != nil {
  277. return result, false, err
  278. }
  279. for _, email := range allEmails {
  280. clean := strings.Trim(email, "\"")
  281. if clean != "" {
  282. occupiedEmails[strings.ToLower(clean)] = struct{}{}
  283. }
  284. }
  285. newClients := make([]model.Client, 0)
  286. needRestart := false
  287. for _, sourceClient := range sourceClients {
  288. originalEmail := strings.TrimSpace(sourceClient.Email)
  289. if originalEmail == "" {
  290. continue
  291. }
  292. if len(allowedEmails) > 0 {
  293. if _, ok := allowedEmails[strings.ToLower(originalEmail)]; !ok {
  294. continue
  295. }
  296. }
  297. if sourceClient.SubID == "" {
  298. newSubID := uuid.NewString()
  299. subNeedRestart, subErr := s.writeBackClientSubID(sourceInbound.Id, sourceClient, newSubID)
  300. if subErr != nil {
  301. result.Errors = append(result.Errors, fmt.Sprintf("%s: failed to write source subId: %v", originalEmail, subErr))
  302. continue
  303. }
  304. if subNeedRestart {
  305. needRestart = true
  306. }
  307. sourceClient.SubID = newSubID
  308. }
  309. targetEmail := s.nextAvailableCopiedEmail(originalEmail, targetInboundID, occupiedEmails)
  310. targetClient, buildErr := s.buildTargetClientFromSource(sourceClient, targetInbound, targetEmail, flow)
  311. if buildErr != nil {
  312. result.Errors = append(result.Errors, fmt.Sprintf("%s: %v", originalEmail, buildErr))
  313. continue
  314. }
  315. newClients = append(newClients, targetClient)
  316. result.Added = append(result.Added, targetEmail)
  317. }
  318. if len(newClients) == 0 {
  319. return result, needRestart, nil
  320. }
  321. settingsPayload, err := json.Marshal(map[string][]model.Client{
  322. "clients": newClients,
  323. })
  324. if err != nil {
  325. return result, needRestart, err
  326. }
  327. addNeedRestart, err := s.clientService.AddInboundClient(s, &model.Inbound{
  328. Id: targetInboundID,
  329. Settings: string(settingsPayload),
  330. })
  331. if err != nil {
  332. return result, needRestart, err
  333. }
  334. if addNeedRestart {
  335. needRestart = true
  336. }
  337. return result, needRestart, nil
  338. }
  339. func (s *InboundService) GetClientInboundByTrafficID(trafficId int) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  340. db := database.GetDB()
  341. var traffics []*xray.ClientTraffic
  342. err = db.Model(xray.ClientTraffic{}).Where("id = ?", trafficId).Find(&traffics).Error
  343. if err != nil {
  344. logger.Warningf("Error retrieving ClientTraffic with trafficId %d: %v", trafficId, err)
  345. return nil, nil, err
  346. }
  347. if len(traffics) == 0 {
  348. return nil, nil, nil
  349. }
  350. traffic = traffics[0]
  351. inbound, err = s.GetInbound(traffic.InboundId)
  352. if errors.Is(err, gorm.ErrRecordNotFound) {
  353. // client_traffics.inbound_id goes stale when an inbound is deleted and
  354. // recreated; fall back to the authoritative client_inbounds link by email.
  355. ids, idErr := s.clientService.GetInboundIdsForEmail(db, traffic.Email)
  356. if idErr != nil {
  357. return traffic, nil, idErr
  358. }
  359. if len(ids) > 0 {
  360. inbound, err = s.GetInbound(ids[0])
  361. }
  362. }
  363. return traffic, inbound, err
  364. }
  365. func (s *InboundService) GetClientInboundByEmail(email string) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  366. db := database.GetDB()
  367. var traffics []*xray.ClientTraffic
  368. err = db.Model(xray.ClientTraffic{}).Where("email = ?", email).Find(&traffics).Error
  369. if err != nil {
  370. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  371. return nil, nil, err
  372. }
  373. if len(traffics) == 0 {
  374. return nil, nil, nil
  375. }
  376. traffic = traffics[0]
  377. inbound, err = s.GetInbound(traffic.InboundId)
  378. if errors.Is(err, gorm.ErrRecordNotFound) {
  379. // client_traffics.inbound_id is a legacy single-inbound pointer that goes
  380. // stale when an inbound is deleted and recreated: the email-keyed traffic
  381. // row survives but still references the missing inbound. Fall back to the
  382. // authoritative client_inbounds link so email lookups (reset, info, …) work.
  383. ids, idErr := s.clientService.GetInboundIdsForEmail(db, email)
  384. if idErr != nil {
  385. return traffic, nil, idErr
  386. }
  387. if len(ids) > 0 {
  388. inbound, err = s.GetInbound(ids[0])
  389. }
  390. }
  391. if err == nil && inbound != nil && !s.inboundHasClientEmail(inbound, email) {
  392. // The pointed-at inbound still exists but no longer carries the client —
  393. // the client was moved to another inbound (#6059). Resolve through the
  394. // client_inbounds link to the inbound that actually hosts it now.
  395. ids, idErr := s.clientService.GetInboundIdsForEmail(db, email)
  396. if idErr == nil {
  397. for _, id := range ids {
  398. if id == inbound.Id {
  399. continue
  400. }
  401. if other, oErr := s.GetInbound(id); oErr == nil && s.inboundHasClientEmail(other, email) {
  402. inbound = other
  403. break
  404. }
  405. }
  406. }
  407. }
  408. return traffic, inbound, err
  409. }
  410. func (s *InboundService) inboundHasClientEmail(inbound *model.Inbound, email string) bool {
  411. clients, err := s.GetClients(inbound)
  412. if err != nil {
  413. return false
  414. }
  415. for _, client := range clients {
  416. if client.Email == email {
  417. return true
  418. }
  419. }
  420. return false
  421. }
  422. func (s *InboundService) GetClientByEmail(clientEmail string) (*xray.ClientTraffic, *model.Client, error) {
  423. traffic, inbound, err := s.GetClientInboundByEmail(clientEmail)
  424. if err != nil {
  425. return nil, nil, err
  426. }
  427. if inbound == nil {
  428. return nil, nil, common.NewError("Inbound Not Found For Email:", clientEmail)
  429. }
  430. clients, err := s.GetClients(inbound)
  431. if err != nil {
  432. return nil, nil, err
  433. }
  434. for _, client := range clients {
  435. if client.Email == clientEmail {
  436. return traffic, &client, nil
  437. }
  438. }
  439. return nil, nil, common.NewError("Client Not Found In Inbound For Email:", clientEmail)
  440. }
  441. // EmailsByInbound returns the list of client emails currently configured on
  442. // an inbound's settings.clients[]. Used by the "delete all clients" flow on
  443. // the inbounds page, which then feeds the list into ClientService.BulkDelete.
  444. func (s *InboundService) EmailsByInbound(inboundId int) ([]string, error) {
  445. inbound, err := s.GetInbound(inboundId)
  446. if err != nil {
  447. return nil, err
  448. }
  449. clients, err := s.GetClients(inbound)
  450. if err != nil {
  451. return nil, err
  452. }
  453. emails := make([]string, 0, len(clients))
  454. for _, c := range clients {
  455. if e := strings.TrimSpace(c.Email); e != "" {
  456. emails = append(emails, e)
  457. }
  458. }
  459. return emails, nil
  460. }