inbound_clients.go 15 KB

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