1
0

inbound_clients.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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. db := database.GetDB()
  123. var count int64
  124. query := fmt.Sprintf(
  125. "SELECT COUNT(*) %s WHERE inbounds.id != ? AND LOWER(%s) = LOWER(?)",
  126. database.JSONClientsFromInbound(),
  127. database.JSONFieldText("client.value", "email"),
  128. )
  129. if err := db.Raw(query, exceptInboundId, email).Scan(&count).Error; err != nil {
  130. return false, err
  131. }
  132. return count > 0, nil
  133. }
  134. func (s *InboundService) emailsUsedByOtherInbounds(emails []string, exceptInboundId int) (map[string]bool, error) {
  135. shared := make(map[string]bool, len(emails))
  136. want := make(map[string]struct{}, len(emails))
  137. for _, e := range emails {
  138. e = strings.ToLower(strings.TrimSpace(e))
  139. if e != "" {
  140. want[e] = struct{}{}
  141. }
  142. }
  143. if len(want) == 0 {
  144. return shared, nil
  145. }
  146. db := database.GetDB()
  147. var rows []string
  148. query := fmt.Sprintf(
  149. "SELECT DISTINCT LOWER(%s) %s WHERE inbounds.id != ?",
  150. database.JSONFieldText("client.value", "email"),
  151. database.JSONClientsFromInbound(),
  152. )
  153. if err := db.Raw(query, exceptInboundId).Scan(&rows).Error; err != nil {
  154. return nil, err
  155. }
  156. for _, e := range rows {
  157. e = strings.ToLower(strings.TrimSpace(e))
  158. if _, ok := want[e]; ok {
  159. shared[e] = true
  160. }
  161. }
  162. return shared, nil
  163. }
  164. func (s *InboundService) writeBackClientSubID(sourceInboundID int, client model.Client, subID string) (bool, error) {
  165. client.SubID = subID
  166. client.UpdatedAt = time.Now().UnixMilli()
  167. if client.Email == "" {
  168. return false, common.NewError("empty client email")
  169. }
  170. settingsBytes, err := json.Marshal(map[string][]model.Client{
  171. "clients": {client},
  172. })
  173. if err != nil {
  174. return false, err
  175. }
  176. updatePayload := &model.Inbound{
  177. Id: sourceInboundID,
  178. Settings: string(settingsBytes),
  179. }
  180. return s.clientService.UpdateInboundClient(s, updatePayload, client.Email)
  181. }
  182. func (s *InboundService) generateRandomCredential(targetProtocol model.Protocol) string {
  183. switch targetProtocol {
  184. case model.VMESS, model.VLESS:
  185. return uuid.NewString()
  186. default:
  187. return strings.ReplaceAll(uuid.NewString(), "-", "")
  188. }
  189. }
  190. func (s *InboundService) buildTargetClientFromSource(source model.Client, targetInbound *model.Inbound, email string, flow string) (model.Client, error) {
  191. nowTs := time.Now().UnixMilli()
  192. target := source
  193. target.Email = email
  194. target.CreatedAt = nowTs
  195. target.UpdatedAt = nowTs
  196. target.ID = ""
  197. target.Password = ""
  198. target.Auth = ""
  199. target.Flow = ""
  200. target.Secret = ""
  201. targetProtocol := targetInbound.Protocol
  202. switch targetProtocol {
  203. case model.VMESS:
  204. target.ID = s.generateRandomCredential(targetProtocol)
  205. case model.VLESS:
  206. target.ID = s.generateRandomCredential(targetProtocol)
  207. if (flow == "xtls-rprx-vision" || flow == "xtls-rprx-vision-udp443") &&
  208. inboundCanEnableTlsFlow(string(targetProtocol), targetInbound.StreamSettings, targetInbound.Settings) {
  209. target.Flow = flow
  210. }
  211. case model.Trojan, model.Shadowsocks:
  212. target.Password = s.generateRandomCredential(targetProtocol)
  213. case model.Hysteria:
  214. target.Auth = s.generateRandomCredential(targetProtocol)
  215. case model.MTProto:
  216. target.Secret = model.GenerateFakeTLSSecret(mtprotoDomainFromSettings(targetInbound.Settings))
  217. default:
  218. target.ID = s.generateRandomCredential(targetProtocol)
  219. }
  220. return target, nil
  221. }
  222. func (s *InboundService) nextAvailableCopiedEmail(originalEmail string, targetID int, occupied map[string]struct{}) string {
  223. base := fmt.Sprintf("%s_%d", originalEmail, targetID)
  224. candidate := base
  225. suffix := 0
  226. for {
  227. if _, exists := occupied[strings.ToLower(candidate)]; !exists {
  228. occupied[strings.ToLower(candidate)] = struct{}{}
  229. return candidate
  230. }
  231. suffix++
  232. candidate = fmt.Sprintf("%s_%d", base, suffix)
  233. }
  234. }
  235. func (s *InboundService) CopyInboundClients(targetInboundID int, sourceInboundID int, clientEmails []string, flow string) (*CopyClientsResult, bool, error) {
  236. result := &CopyClientsResult{
  237. Added: []string{},
  238. Skipped: []string{},
  239. Errors: []string{},
  240. }
  241. if targetInboundID == sourceInboundID {
  242. return result, false, common.NewError("source and target inbounds must be different")
  243. }
  244. targetInbound, err := s.GetInbound(targetInboundID)
  245. if err != nil {
  246. return result, false, err
  247. }
  248. sourceInbound, err := s.GetInbound(sourceInboundID)
  249. if err != nil {
  250. return result, false, err
  251. }
  252. sourceClients, err := s.GetClients(sourceInbound)
  253. if err != nil {
  254. return result, false, err
  255. }
  256. if len(sourceClients) == 0 {
  257. return result, false, nil
  258. }
  259. allowedEmails := map[string]struct{}{}
  260. if len(clientEmails) > 0 {
  261. for _, email := range clientEmails {
  262. allowedEmails[strings.ToLower(strings.TrimSpace(email))] = struct{}{}
  263. }
  264. }
  265. occupiedEmails := map[string]struct{}{}
  266. allEmails, err := s.GetAllEmails()
  267. if err != nil {
  268. return result, false, err
  269. }
  270. for _, email := range allEmails {
  271. clean := strings.Trim(email, "\"")
  272. if clean != "" {
  273. occupiedEmails[strings.ToLower(clean)] = struct{}{}
  274. }
  275. }
  276. newClients := make([]model.Client, 0)
  277. needRestart := false
  278. for _, sourceClient := range sourceClients {
  279. originalEmail := strings.TrimSpace(sourceClient.Email)
  280. if originalEmail == "" {
  281. continue
  282. }
  283. if len(allowedEmails) > 0 {
  284. if _, ok := allowedEmails[strings.ToLower(originalEmail)]; !ok {
  285. continue
  286. }
  287. }
  288. if sourceClient.SubID == "" {
  289. newSubID := uuid.NewString()
  290. subNeedRestart, subErr := s.writeBackClientSubID(sourceInbound.Id, sourceClient, newSubID)
  291. if subErr != nil {
  292. result.Errors = append(result.Errors, fmt.Sprintf("%s: failed to write source subId: %v", originalEmail, subErr))
  293. continue
  294. }
  295. if subNeedRestart {
  296. needRestart = true
  297. }
  298. sourceClient.SubID = newSubID
  299. }
  300. targetEmail := s.nextAvailableCopiedEmail(originalEmail, targetInboundID, occupiedEmails)
  301. targetClient, buildErr := s.buildTargetClientFromSource(sourceClient, targetInbound, targetEmail, flow)
  302. if buildErr != nil {
  303. result.Errors = append(result.Errors, fmt.Sprintf("%s: %v", originalEmail, buildErr))
  304. continue
  305. }
  306. newClients = append(newClients, targetClient)
  307. result.Added = append(result.Added, targetEmail)
  308. }
  309. if len(newClients) == 0 {
  310. return result, needRestart, nil
  311. }
  312. settingsPayload, err := json.Marshal(map[string][]model.Client{
  313. "clients": newClients,
  314. })
  315. if err != nil {
  316. return result, needRestart, err
  317. }
  318. addNeedRestart, err := s.clientService.AddInboundClient(s, &model.Inbound{
  319. Id: targetInboundID,
  320. Settings: string(settingsPayload),
  321. })
  322. if err != nil {
  323. return result, needRestart, err
  324. }
  325. if addNeedRestart {
  326. needRestart = true
  327. }
  328. return result, needRestart, nil
  329. }
  330. func (s *InboundService) GetClientInboundByTrafficID(trafficId int) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  331. db := database.GetDB()
  332. var traffics []*xray.ClientTraffic
  333. err = db.Model(xray.ClientTraffic{}).Where("id = ?", trafficId).Find(&traffics).Error
  334. if err != nil {
  335. logger.Warningf("Error retrieving ClientTraffic with trafficId %d: %v", trafficId, err)
  336. return nil, nil, err
  337. }
  338. if len(traffics) == 0 {
  339. return nil, nil, nil
  340. }
  341. traffic = traffics[0]
  342. inbound, err = s.GetInbound(traffic.InboundId)
  343. if errors.Is(err, gorm.ErrRecordNotFound) {
  344. // client_traffics.inbound_id goes stale when an inbound is deleted and
  345. // recreated; fall back to the authoritative client_inbounds link by email.
  346. ids, idErr := s.clientService.GetInboundIdsForEmail(db, traffic.Email)
  347. if idErr != nil {
  348. return traffic, nil, idErr
  349. }
  350. if len(ids) > 0 {
  351. inbound, err = s.GetInbound(ids[0])
  352. }
  353. }
  354. return traffic, inbound, err
  355. }
  356. func (s *InboundService) GetClientInboundByEmail(email string) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  357. db := database.GetDB()
  358. var traffics []*xray.ClientTraffic
  359. err = db.Model(xray.ClientTraffic{}).Where("email = ?", email).Find(&traffics).Error
  360. if err != nil {
  361. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  362. return nil, nil, err
  363. }
  364. if len(traffics) == 0 {
  365. return nil, nil, nil
  366. }
  367. traffic = traffics[0]
  368. inbound, err = s.GetInbound(traffic.InboundId)
  369. if errors.Is(err, gorm.ErrRecordNotFound) {
  370. // client_traffics.inbound_id is a legacy single-inbound pointer that goes
  371. // stale when an inbound is deleted and recreated: the email-keyed traffic
  372. // row survives but still references the missing inbound. Fall back to the
  373. // authoritative client_inbounds link so email lookups (reset, info, …) work.
  374. ids, idErr := s.clientService.GetInboundIdsForEmail(db, email)
  375. if idErr != nil {
  376. return traffic, nil, idErr
  377. }
  378. if len(ids) > 0 {
  379. inbound, err = s.GetInbound(ids[0])
  380. }
  381. }
  382. return traffic, inbound, err
  383. }
  384. func (s *InboundService) GetClientByEmail(clientEmail string) (*xray.ClientTraffic, *model.Client, error) {
  385. traffic, inbound, err := s.GetClientInboundByEmail(clientEmail)
  386. if err != nil {
  387. return nil, nil, err
  388. }
  389. if inbound == nil {
  390. return nil, nil, common.NewError("Inbound Not Found For Email:", clientEmail)
  391. }
  392. clients, err := s.GetClients(inbound)
  393. if err != nil {
  394. return nil, nil, err
  395. }
  396. for _, client := range clients {
  397. if client.Email == clientEmail {
  398. return traffic, &client, nil
  399. }
  400. }
  401. return nil, nil, common.NewError("Client Not Found In Inbound For Email:", clientEmail)
  402. }
  403. // EmailsByInbound returns the list of client emails currently configured on
  404. // an inbound's settings.clients[]. Used by the "delete all clients" flow on
  405. // the inbounds page, which then feeds the list into ClientService.BulkDelete.
  406. func (s *InboundService) EmailsByInbound(inboundId int) ([]string, error) {
  407. inbound, err := s.GetInbound(inboundId)
  408. if err != nil {
  409. return nil, err
  410. }
  411. clients, err := s.GetClients(inbound)
  412. if err != nil {
  413. return nil, err
  414. }
  415. emails := make([]string, 0, len(clients))
  416. for _, c := range clients {
  417. if e := strings.TrimSpace(c.Email); e != "" {
  418. emails = append(emails, e)
  419. }
  420. }
  421. return emails, nil
  422. }