inbound.go 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348
  1. // Package service provides business logic services for the 3x-ui web panel,
  2. // including inbound/outbound management, user administration, settings, and Xray integration.
  3. package service
  4. import (
  5. "context"
  6. "encoding/json"
  7. "fmt"
  8. "net"
  9. "sort"
  10. "strings"
  11. "time"
  12. "github.com/mhsanaei/3x-ui/v3/internal/database"
  13. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  14. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  15. "github.com/mhsanaei/3x-ui/v3/internal/mtproto"
  16. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  17. "github.com/mhsanaei/3x-ui/v3/internal/util/netsafe"
  18. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  19. "gorm.io/gorm"
  20. "gorm.io/gorm/clause"
  21. )
  22. type InboundService struct {
  23. xrayApi xray.XrayAPI
  24. clientService ClientService
  25. fallbackService FallbackService
  26. }
  27. func normalizeInboundShareAddrStrategy(strategy string) string {
  28. strategy = strings.TrimSpace(strategy)
  29. switch strategy {
  30. case "listen", "custom":
  31. return strategy
  32. default:
  33. return "node"
  34. }
  35. }
  36. func normalizeInboundShareAddress(inbound *model.Inbound) {
  37. if inbound == nil {
  38. return
  39. }
  40. inbound.ShareAddrStrategy = normalizeInboundShareAddrStrategy(inbound.ShareAddrStrategy)
  41. if addr, err := normalizeInboundShareHost(inbound.ShareAddr); err == nil {
  42. inbound.ShareAddr = addr
  43. } else {
  44. inbound.ShareAddr = strings.TrimSpace(inbound.ShareAddr)
  45. }
  46. }
  47. func normalizeInboundShareAddressStrict(inbound *model.Inbound) error {
  48. if inbound == nil {
  49. return nil
  50. }
  51. inbound.ShareAddrStrategy = normalizeInboundShareAddrStrategy(inbound.ShareAddrStrategy)
  52. addr, err := normalizeInboundShareHost(inbound.ShareAddr)
  53. if err != nil {
  54. return common.NewError("shareAddr must be a host or IP without scheme or port")
  55. }
  56. inbound.ShareAddr = addr
  57. return nil
  58. }
  59. func normalizeInboundShareHost(raw string) (string, error) {
  60. addr := strings.TrimSpace(raw)
  61. if addr == "" {
  62. return "", nil
  63. }
  64. if strings.Contains(addr, "://") || strings.HasPrefix(addr, "//") || strings.ContainsAny(addr, "/?#@") {
  65. return "", fmt.Errorf("invalid share address %q", raw)
  66. }
  67. if strings.HasPrefix(addr, "[") {
  68. if !strings.HasSuffix(addr, "]") {
  69. return "", fmt.Errorf("invalid IPv6 host %q", raw)
  70. }
  71. ip := net.ParseIP(addr[1 : len(addr)-1])
  72. if ip == nil || ip.To4() != nil {
  73. return "", fmt.Errorf("invalid IPv6 host %q", raw)
  74. }
  75. return "[" + ip.String() + "]", nil
  76. }
  77. if strings.Contains(addr, ":") {
  78. if _, _, err := net.SplitHostPort(addr); err == nil {
  79. return "", fmt.Errorf("share address must not include port")
  80. }
  81. ip := net.ParseIP(addr)
  82. if ip == nil || ip.To4() != nil {
  83. return "", fmt.Errorf("invalid IPv6 host %q", raw)
  84. }
  85. return "[" + ip.String() + "]", nil
  86. }
  87. host, err := netsafe.NormalizeHost(addr)
  88. if err != nil {
  89. return "", err
  90. }
  91. return host, nil
  92. }
  93. func normalizeInboundShareAddressColumns(tx *gorm.DB) error {
  94. if tx == nil || !tx.Migrator().HasColumn(&model.Inbound{}, "share_addr_strategy") {
  95. return nil
  96. }
  97. strategyExpr := `CASE TRIM(COALESCE(share_addr_strategy, '')) WHEN 'listen' THEN 'listen' WHEN 'custom' THEN 'custom' ELSE 'node' END`
  98. if err := tx.Exec(`UPDATE inbounds SET share_addr_strategy = ` + strategyExpr + ` WHERE share_addr_strategy IS NULL OR share_addr_strategy <> ` + strategyExpr).Error; err != nil {
  99. return err
  100. }
  101. hasShareAddr := tx.Migrator().HasColumn(&model.Inbound{}, "share_addr")
  102. if hasShareAddr {
  103. if err := tx.Exec(`UPDATE inbounds SET share_addr = TRIM(share_addr) WHERE share_addr IS NOT NULL AND share_addr <> TRIM(share_addr)`).Error; err != nil {
  104. return err
  105. }
  106. }
  107. if !hasShareAddr {
  108. return nil
  109. }
  110. var rows []struct {
  111. Id int
  112. ShareAddrStrategy string
  113. ShareAddr string
  114. }
  115. if err := tx.Model(&model.Inbound{}).Select("id", "share_addr_strategy", "share_addr").Find(&rows).Error; err != nil {
  116. return err
  117. }
  118. for _, row := range rows {
  119. strategy := normalizeInboundShareAddrStrategy(row.ShareAddrStrategy)
  120. addr, addrErr := normalizeInboundShareHost(row.ShareAddr)
  121. if addrErr != nil {
  122. strategy = "node"
  123. addr = ""
  124. }
  125. updates := map[string]any{}
  126. if strategy != row.ShareAddrStrategy {
  127. updates["share_addr_strategy"] = strategy
  128. }
  129. if addr != row.ShareAddr {
  130. updates["share_addr"] = addr
  131. }
  132. if len(updates) > 0 {
  133. if err := tx.Model(&model.Inbound{}).Where("id = ?", row.Id).Updates(updates).Error; err != nil {
  134. return err
  135. }
  136. }
  137. }
  138. return nil
  139. }
  140. // GetInbounds retrieves all inbounds for a specific user with client stats.
  141. func (s *InboundService) GetInbounds(userId int) ([]*model.Inbound, error) {
  142. db := database.GetDB()
  143. var inbounds []*model.Inbound
  144. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("user_id = ?", userId).Order("id ASC").Find(&inbounds).Error
  145. if err != nil && err != gorm.ErrRecordNotFound {
  146. return nil, err
  147. }
  148. s.enrichClientStats(db, inbounds)
  149. s.annotateFallbackParents(db, inbounds)
  150. s.annotateLocalOriginGuid(inbounds)
  151. return inbounds, nil
  152. }
  153. // annotateLocalOriginGuid fills OriginNodeGuid for this panel's OWN inbounds
  154. // (NodeID == nil) with the panel's stable GUID; inbounds synced from a node
  155. // already carry the originating node's GUID. Read-time only (not persisted) so
  156. // the per-inbound online view can scope by GUID uniformly across a chain of
  157. // nodes (#4983).
  158. func (s *InboundService) annotateLocalOriginGuid(inbounds []*model.Inbound) {
  159. if len(inbounds) == 0 {
  160. return
  161. }
  162. guid := s.panelGuid()
  163. if guid == "" {
  164. return
  165. }
  166. for _, ib := range inbounds {
  167. if ib.OriginNodeGuid == "" && ib.NodeID == nil {
  168. ib.OriginNodeGuid = guid
  169. }
  170. }
  171. }
  172. // GetInboundsSlim returns the same list of inbounds as GetInbounds but
  173. // strips every per-client field other than email / enable / comment from
  174. // settings.clients and skips UUID/SubId enrichment on ClientStats. The
  175. // inbounds page only needs those three to roll up client counts and
  176. // render badges, so this trims tens of bytes per client (UUID, password,
  177. // flow, security, totalGB, expiryTime, limitIp, tgId, ...) which adds
  178. // up fast on installs with thousands of clients.
  179. //
  180. // Full client data is still available through GET /panel/api/inbounds/get/:id
  181. // for the edit/info/qr/export/clone flows that need it.
  182. func (s *InboundService) GetInboundsSlim(userId int) ([]*model.Inbound, error) {
  183. db := database.GetDB()
  184. var inbounds []*model.Inbound
  185. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("user_id = ?", userId).Order("id ASC").Find(&inbounds).Error
  186. if err != nil && err != gorm.ErrRecordNotFound {
  187. return nil, err
  188. }
  189. s.annotateFallbackParents(db, inbounds)
  190. s.annotateLocalOriginGuid(inbounds)
  191. // Top up stats rows owned by sibling inbounds (multi-attached clients)
  192. // so the list's depleted/expiring badges see every client; the UUID/SubId
  193. // enrichment stays skipped. Must run before slimming strips the settings.
  194. s.backfillClientStats(db, inbounds)
  195. // Slim feeds the panel UI only (masters poll the full list), so the badge
  196. // math may see the cross-panel totals a master pushed.
  197. s.overlayInboundsClientStats(db, inbounds)
  198. for _, ib := range inbounds {
  199. ib.Settings = slimSettingsClients(ib.Settings)
  200. }
  201. return inbounds, nil
  202. }
  203. // slimSettingsClients rewrites the inbound settings JSON so settings.clients[]
  204. // keeps only the fields the list view actually reads. Returns the input
  205. // unchanged when the JSON can't be parsed or has no clients array.
  206. func slimSettingsClients(settings string) string {
  207. if settings == "" {
  208. return settings
  209. }
  210. var raw map[string]any
  211. if err := json.Unmarshal([]byte(settings), &raw); err != nil {
  212. return settings
  213. }
  214. clients, ok := raw["clients"].([]any)
  215. if !ok || len(clients) == 0 {
  216. return settings
  217. }
  218. slim := make([]any, 0, len(clients))
  219. for _, entry := range clients {
  220. c, ok := entry.(map[string]any)
  221. if !ok {
  222. continue
  223. }
  224. row := make(map[string]any, 3)
  225. if v, ok := c["email"]; ok {
  226. row["email"] = v
  227. }
  228. if v, ok := c["enable"]; ok {
  229. row["enable"] = v
  230. }
  231. if v, ok := c["comment"]; ok && v != "" {
  232. row["comment"] = v
  233. }
  234. slim = append(slim, row)
  235. }
  236. raw["clients"] = slim
  237. out, err := json.Marshal(raw)
  238. if err != nil {
  239. return settings
  240. }
  241. return string(out)
  242. }
  243. // annotateFallbackParents fills FallbackParent on each inbound that is
  244. // the child side of a fallback rule. One DB round-trip serves the full
  245. // list — the frontend needs this to rewrite the child's client-share
  246. // link so it points at the master's reachable endpoint.
  247. func (s *InboundService) annotateFallbackParents(db *gorm.DB, inbounds []*model.Inbound) {
  248. if len(inbounds) == 0 {
  249. return
  250. }
  251. childIds := make([]int, 0, len(inbounds))
  252. for _, ib := range inbounds {
  253. childIds = append(childIds, ib.Id)
  254. }
  255. var rows []model.InboundFallback
  256. if err := db.Where("child_id IN ?", childIds).
  257. Order("sort_order ASC, id ASC").
  258. Find(&rows).Error; err != nil {
  259. return
  260. }
  261. first := make(map[int]model.InboundFallback, len(rows))
  262. for _, r := range rows {
  263. if _, ok := first[r.ChildId]; !ok {
  264. first[r.ChildId] = r
  265. }
  266. }
  267. for _, ib := range inbounds {
  268. if r, ok := first[ib.Id]; ok {
  269. ib.FallbackParent = &model.FallbackParentInfo{
  270. MasterId: r.MasterId,
  271. Path: r.Path,
  272. }
  273. }
  274. }
  275. }
  276. type InboundOption struct {
  277. Id int `json:"id" example:"1"`
  278. Remark string `json:"remark" example:"VLESS-443"`
  279. Tag string `json:"tag" example:"in-443-tcp"`
  280. Protocol string `json:"protocol" example:"vless"`
  281. Port int `json:"port" example:"443"`
  282. TlsFlowCapable bool `json:"tlsFlowCapable" example:"true"`
  283. SsMethod string `json:"ssMethod"`
  284. // Hosting node; nil for this panel's own inbounds. Lets the clients
  285. // page map a node filter onto inbound IDs (#4997).
  286. NodeId *int `json:"nodeId,omitempty"`
  287. }
  288. func (s *InboundService) GetInboundOptions(userId int) ([]InboundOption, error) {
  289. db := database.GetDB()
  290. var rows []struct {
  291. Id int `gorm:"column:id"`
  292. Remark string `gorm:"column:remark"`
  293. Tag string `gorm:"column:tag"`
  294. Protocol string `gorm:"column:protocol"`
  295. Port int `gorm:"column:port"`
  296. StreamSettings string `gorm:"column:stream_settings"`
  297. Settings string `gorm:"column:settings"`
  298. NodeId *int `gorm:"column:node_id"`
  299. }
  300. err := db.Table("inbounds").
  301. Select("id, remark, tag, protocol, port, stream_settings, settings, node_id").
  302. Where("user_id = ?", userId).
  303. Order("id ASC").
  304. Scan(&rows).Error
  305. if err != nil && err != gorm.ErrRecordNotFound {
  306. return nil, err
  307. }
  308. out := make([]InboundOption, 0, len(rows))
  309. for _, r := range rows {
  310. out = append(out, InboundOption{
  311. Id: r.Id,
  312. Remark: r.Remark,
  313. Tag: r.Tag,
  314. Protocol: r.Protocol,
  315. Port: r.Port,
  316. TlsFlowCapable: inboundCanEnableTlsFlow(r.Protocol, r.StreamSettings, r.Settings),
  317. SsMethod: inboundShadowsocksMethod(r.Protocol, r.Settings),
  318. NodeId: r.NodeId,
  319. })
  320. }
  321. return out, nil
  322. }
  323. // GetAllInbounds retrieves all inbounds with client stats.
  324. func (s *InboundService) GetAllInbounds() ([]*model.Inbound, error) {
  325. db := database.GetDB()
  326. var inbounds []*model.Inbound
  327. err := db.Model(model.Inbound{}).Preload("ClientStats").Find(&inbounds).Error
  328. if err != nil && err != gorm.ErrRecordNotFound {
  329. return nil, err
  330. }
  331. s.enrichClientStats(db, inbounds)
  332. return inbounds, nil
  333. }
  334. func (s *InboundService) GetInboundsByTrafficReset(period string) ([]*model.Inbound, error) {
  335. db := database.GetDB()
  336. var inbounds []*model.Inbound
  337. err := db.Model(model.Inbound{}).Where("traffic_reset = ?", period).Find(&inbounds).Error
  338. if err != nil && err != gorm.ErrRecordNotFound {
  339. return nil, err
  340. }
  341. return inbounds, nil
  342. }
  343. func (s *InboundService) GetClients(inbound *model.Inbound) ([]model.Client, error) {
  344. settings := map[string][]model.Client{}
  345. json.Unmarshal([]byte(inbound.Settings), &settings)
  346. if settings == nil {
  347. return nil, fmt.Errorf("setting is null")
  348. }
  349. clients := settings["clients"]
  350. if clients == nil {
  351. return nil, nil
  352. }
  353. return clients, nil
  354. }
  355. func (s *InboundService) GetAllEmails() ([]string, error) {
  356. db := database.GetDB()
  357. var emails []string
  358. query := fmt.Sprintf(
  359. "SELECT DISTINCT %s %s",
  360. database.JSONFieldText("client.value", "email"),
  361. database.JSONClientsFromInbound(),
  362. )
  363. if err := db.Raw(query).Scan(&emails).Error; err != nil {
  364. return nil, err
  365. }
  366. return emails, nil
  367. }
  368. // getAllEmailSubIDs returns email→subId. An email seen with two different
  369. // non-empty subIds is locked (mapped to "") so neither identity can claim it.
  370. func (s *InboundService) getAllEmailSubIDs() (map[string]string, error) {
  371. db := database.GetDB()
  372. var rows []struct {
  373. Email string
  374. SubID string
  375. }
  376. query := fmt.Sprintf(
  377. "SELECT %s AS email, %s AS sub_id %s",
  378. database.JSONFieldText("client.value", "email"),
  379. database.JSONFieldText("client.value", "subId"),
  380. database.JSONClientsFromInbound(),
  381. )
  382. if err := db.Raw(query).Scan(&rows).Error; err != nil {
  383. return nil, err
  384. }
  385. result := make(map[string]string, len(rows))
  386. for _, r := range rows {
  387. email := strings.ToLower(r.Email)
  388. if email == "" {
  389. continue
  390. }
  391. subID := r.SubID
  392. if existing, ok := result[email]; ok {
  393. if existing != subID {
  394. result[email] = ""
  395. }
  396. continue
  397. }
  398. result[email] = subID
  399. }
  400. return result, nil
  401. }
  402. // normalizeStreamSettings clears StreamSettings for protocols that don't use it.
  403. // Only vmess, vless, trojan, shadowsocks, hysteria, and wireguard protocols use
  404. // streamSettings (wireguard for finalmask UDP masks and sockopt on its listener).
  405. func (s *InboundService) normalizeStreamSettings(inbound *model.Inbound) {
  406. protocolsWithStream := map[model.Protocol]bool{
  407. model.VMESS: true,
  408. model.VLESS: true,
  409. model.Trojan: true,
  410. model.Shadowsocks: true,
  411. model.Hysteria: true,
  412. model.WireGuard: true,
  413. }
  414. if !protocolsWithStream[inbound.Protocol] {
  415. inbound.StreamSettings = ""
  416. }
  417. }
  418. // normalizeMtprotoSecret rebuilds an mtproto inbound's FakeTLS secret so it is
  419. // always valid and matches the configured domain before the row is persisted.
  420. func (s *InboundService) normalizeMtprotoSecret(inbound *model.Inbound) {
  421. if inbound.Protocol != model.MTProto {
  422. return
  423. }
  424. if healed, ok := model.HealMtprotoSecret(inbound.Settings); ok {
  425. inbound.Settings = healed
  426. }
  427. }
  428. // mtprotoRoutesThroughXray reports whether an mtproto inbound is configured to
  429. // egress through the core's router (the loopback SOCKS bridge in §xray.go).
  430. func mtprotoRoutesThroughXray(inbound *model.Inbound) bool {
  431. if inbound == nil || inbound.Protocol != model.MTProto {
  432. return false
  433. }
  434. var parsed struct {
  435. RouteThroughXray bool `json:"routeThroughXray"`
  436. }
  437. if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil {
  438. return false
  439. }
  440. return parsed.RouteThroughXray
  441. }
  442. func settingsRouteXrayPort(parsed map[string]any) int {
  443. switch v := parsed["routeXrayPort"].(type) {
  444. case float64:
  445. return int(v)
  446. case int:
  447. return v
  448. case json.Number:
  449. if n, err := v.Int64(); err == nil {
  450. return int(n)
  451. }
  452. }
  453. return 0
  454. }
  455. func parseRouteXrayPort(settings string) int {
  456. if settings == "" {
  457. return 0
  458. }
  459. var parsed map[string]any
  460. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  461. return 0
  462. }
  463. return settingsRouteXrayPort(parsed)
  464. }
  465. // normalizeMtprotoXrayPort guarantees a routed mtproto inbound carries a stable
  466. // loopback egress port in its settings, so the generated Xray SOCKS bridge and
  467. // the mtg sidecar agree on where mtg dials out. The port is backend-owned: it is
  468. // allocated once when routing is first enabled and preserved across edits
  469. // (carried over from oldSettings, which wins over any value the client echoed
  470. // back). When routing is off it — together with the now-inert outbound
  471. // selection — is stripped so a disabled bridge leaves nothing stale behind.
  472. //
  473. // It returns an error when an egress port cannot be allocated or persisted, so
  474. // the caller refuses the save rather than storing a routed-but-portless inbound,
  475. // which would otherwise route no traffic and have its mtg metrics skipped (see
  476. // mtproto_job) — silently losing its accounting.
  477. func (s *InboundService) normalizeMtprotoXrayPort(inbound *model.Inbound, oldSettings string) error {
  478. if inbound.Protocol != model.MTProto {
  479. return nil
  480. }
  481. var parsed map[string]any
  482. if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil || parsed == nil {
  483. return nil
  484. }
  485. routed, _ := parsed["routeThroughXray"].(bool)
  486. if !routed {
  487. _, hadPort := parsed["routeXrayPort"]
  488. _, hadTag := parsed["outboundTag"]
  489. if !hadPort && !hadTag {
  490. return nil
  491. }
  492. delete(parsed, "routeXrayPort")
  493. delete(parsed, "outboundTag")
  494. if bs, err := json.MarshalIndent(parsed, "", " "); err == nil {
  495. inbound.Settings = string(bs)
  496. } else {
  497. logger.Warning("mtproto: failed to marshal settings after disabling routing:", err)
  498. }
  499. return nil
  500. }
  501. // Prefer the already-stored port (carried across edits), then any value the
  502. // client sent, then allocate a fresh one.
  503. port := parseRouteXrayPort(oldSettings)
  504. if port <= 0 {
  505. port = settingsRouteXrayPort(parsed)
  506. }
  507. if port <= 0 {
  508. allocated, err := mtproto.FreeLocalPort()
  509. if err != nil {
  510. return common.NewError("mtproto: could not allocate an Xray egress port:", err)
  511. }
  512. port = allocated
  513. }
  514. if settingsRouteXrayPort(parsed) == port {
  515. return nil
  516. }
  517. parsed["routeXrayPort"] = port
  518. bs, err := json.MarshalIndent(parsed, "", " ")
  519. if err != nil {
  520. return common.NewError("mtproto: could not persist the Xray egress port:", err)
  521. }
  522. inbound.Settings = string(bs)
  523. return nil
  524. }
  525. // AddInbound creates a new inbound configuration.
  526. // It validates port uniqueness, client email uniqueness, and required fields,
  527. // then saves the inbound to the database and optionally adds it to the running Xray instance.
  528. // Returns the created inbound, whether Xray needs restart, and any error.
  529. func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  530. // Normalize streamSettings based on protocol
  531. s.normalizeStreamSettings(inbound)
  532. s.normalizeMtprotoSecret(inbound)
  533. if err := s.normalizeMtprotoXrayPort(inbound, ""); err != nil {
  534. return inbound, false, err
  535. }
  536. inbound.SubSortIndex = normalizeSubSortIndex(inbound.SubSortIndex)
  537. if err := normalizeInboundShareAddressStrict(inbound); err != nil {
  538. return inbound, false, err
  539. }
  540. conflict, err := s.checkPortConflict(inbound, 0)
  541. if err != nil {
  542. return inbound, false, err
  543. }
  544. if conflict != nil {
  545. return inbound, false, common.NewError(conflict.String())
  546. }
  547. inbound.Tag, err = s.resolveInboundTag(inbound, 0)
  548. if err != nil {
  549. return inbound, false, err
  550. }
  551. clients, err := s.GetClients(inbound)
  552. if err != nil {
  553. return inbound, false, err
  554. }
  555. existEmail, err := s.clientService.checkEmailsExistForClients(s, clients, nil)
  556. if err != nil {
  557. return inbound, false, err
  558. }
  559. if existEmail != "" {
  560. return inbound, false, common.NewError("Duplicate email:", existEmail)
  561. }
  562. // Ensure created_at and updated_at on clients in settings
  563. if len(clients) > 0 {
  564. var settings map[string]any
  565. if err2 := json.Unmarshal([]byte(inbound.Settings), &settings); err2 == nil && settings != nil {
  566. now := time.Now().Unix() * 1000
  567. updatedClients := make([]model.Client, 0, len(clients))
  568. for _, c := range clients {
  569. if c.CreatedAt == 0 {
  570. c.CreatedAt = now
  571. }
  572. c.UpdatedAt = now
  573. updatedClients = append(updatedClients, c)
  574. }
  575. settings["clients"] = updatedClients
  576. if bs, err3 := json.MarshalIndent(settings, "", " "); err3 == nil {
  577. inbound.Settings = string(bs)
  578. } else {
  579. logger.Debug("Unable to marshal inbound settings with timestamps:", err3)
  580. }
  581. } else if err2 != nil {
  582. logger.Debug("Unable to parse inbound settings for timestamps:", err2)
  583. }
  584. }
  585. // Secure client ID
  586. for _, client := range clients {
  587. switch inbound.Protocol {
  588. case "trojan":
  589. if client.Password == "" {
  590. return inbound, false, common.NewError("empty client ID")
  591. }
  592. case "shadowsocks":
  593. if client.Email == "" {
  594. return inbound, false, common.NewError("empty client ID")
  595. }
  596. case "hysteria":
  597. if client.Auth == "" {
  598. return inbound, false, common.NewError("empty client ID")
  599. }
  600. default:
  601. if client.ID == "" {
  602. return inbound, false, common.NewError("empty client ID")
  603. }
  604. }
  605. }
  606. db := database.GetDB()
  607. tx := db.Begin()
  608. markDirty := false
  609. defer func() {
  610. if err != nil {
  611. tx.Rollback()
  612. return
  613. }
  614. tx.Commit()
  615. if markDirty && inbound.NodeID != nil {
  616. if dErr := (&NodeService{}).MarkNodeDirty(*inbound.NodeID); dErr != nil {
  617. logger.Warning("mark node dirty failed:", dErr)
  618. }
  619. }
  620. }()
  621. // Omit the ClientStats has-many association: GORM's cascade would INSERT
  622. // those rows with an ON CONFLICT target on the primary key only, which
  623. // collides with the globally-unique client_traffics.email when an imported
  624. // inbound carries clients that another inbound already created (e.g.
  625. // importing two inbounds that share the same clients). We insert the stats
  626. // ourselves below with the same email-conflict guard AddClientStat uses.
  627. err = tx.Omit("ClientStats").Save(inbound).Error
  628. if err != nil {
  629. return inbound, false, err
  630. }
  631. // Imported stats first, so their traffic counters survive; emails that
  632. // already own a (shared) row are skipped instead of tripping the unique
  633. // constraint.
  634. for i := range inbound.ClientStats {
  635. if inbound.ClientStats[i].Email == "" {
  636. continue
  637. }
  638. inbound.ClientStats[i].Id = 0
  639. inbound.ClientStats[i].InboundId = inbound.Id
  640. if err = tx.Clauses(clause.OnConflict{
  641. Columns: []clause.Column{{Name: "email"}},
  642. DoNothing: true,
  643. }).Create(&inbound.ClientStats[i]).Error; err != nil {
  644. return inbound, false, err
  645. }
  646. }
  647. // Then make sure every client has a stats row. AddClientStat is a no-op
  648. // where one exists (including the rows just inserted), and fills the gap
  649. // for clients an import payload didn't carry stats for.
  650. for _, client := range clients {
  651. if err = s.AddClientStat(tx, inbound.Id, &client); err != nil {
  652. return inbound, false, err
  653. }
  654. }
  655. if err = s.clientService.SyncInbound(tx, inbound.Id, clients); err != nil {
  656. return inbound, false, err
  657. }
  658. // Before the deferred commit, so a node in "selected" sync mode cannot
  659. // sweep the new central row in the gap before its tag is allowed.
  660. if inbound.NodeID != nil {
  661. if aErr := (&NodeService{}).EnsureInboundTagAllowed(*inbound.NodeID, inbound.Tag); aErr != nil {
  662. logger.Warning("allow inbound tag on node failed:", aErr)
  663. }
  664. }
  665. needRestart := false
  666. if inbound.Enable {
  667. rt, push, dirty, perr := s.nodePushPlan(inbound)
  668. if perr != nil {
  669. err = perr
  670. return inbound, false, err
  671. }
  672. if dirty {
  673. markDirty = true
  674. }
  675. if push {
  676. if err1 := rt.AddInbound(context.Background(), inbound); err1 == nil {
  677. logger.Debug("New inbound added on", rt.Name(), ":", inbound.Tag)
  678. } else {
  679. logger.Debug("Unable to add inbound on", rt.Name(), ":", err1)
  680. if inbound.NodeID != nil {
  681. markDirty = true
  682. } else {
  683. needRestart = true
  684. }
  685. }
  686. }
  687. }
  688. // A routed mtproto inbound is not an Xray inbound itself, so the runtime
  689. // push above only (re)starts the mtg sidecar. The egress SOCKS bridge lives
  690. // in the generated config, so force a regen to wire it in.
  691. if mtprotoRoutesThroughXray(inbound) {
  692. needRestart = true
  693. }
  694. return inbound, needRestart, err
  695. }
  696. func (s *InboundService) DelInbound(id int) (bool, error) {
  697. db := database.GetDB()
  698. needRestart := false
  699. markDirty := false
  700. var ib model.Inbound
  701. loadErr := db.Model(model.Inbound{}).Where("id = ?", id).First(&ib).Error
  702. if loadErr == nil {
  703. shouldPushToRuntime := ib.NodeID != nil || ib.Enable
  704. if shouldPushToRuntime {
  705. rt, push, dirty, perr := s.nodePushPlan(&ib)
  706. if perr != nil {
  707. logger.Warning("DelInbound: node lookup failed, deleting central row anyway:", perr)
  708. markDirty = true
  709. } else if push {
  710. if err1 := rt.DelInbound(context.Background(), &ib); err1 == nil {
  711. logger.Debug("Inbound deleted on", rt.Name(), ":", ib.Tag)
  712. } else {
  713. logger.Warning("DelInbound on", rt.Name(), "failed, deleting central row anyway:", err1)
  714. if ib.NodeID == nil {
  715. needRestart = true
  716. } else {
  717. markDirty = true
  718. }
  719. }
  720. } else if ib.NodeID == nil {
  721. needRestart = true
  722. } else if dirty {
  723. markDirty = true
  724. }
  725. } else {
  726. logger.Debug("DelInbound: skipping runtime push for disabled local inbound id:", id)
  727. }
  728. } else {
  729. logger.Debug("DelInbound: inbound not found, id:", id)
  730. }
  731. if err := s.clientService.DetachInbound(db, id); err != nil {
  732. return false, err
  733. }
  734. if err := db.Delete(model.Inbound{}, id).Error; err != nil {
  735. return needRestart, err
  736. }
  737. // Hosts have no hard FK; drop the inbound's hosts alongside it.
  738. if err := db.Where("inbound_id = ?", id).Delete(&model.Host{}).Error; err != nil {
  739. return needRestart, err
  740. }
  741. if markDirty && ib.NodeID != nil {
  742. if dErr := (&NodeService{}).MarkNodeDirty(*ib.NodeID); dErr != nil {
  743. logger.Warning("mark node dirty failed:", dErr)
  744. }
  745. }
  746. if !database.IsPostgres() {
  747. var count int64
  748. if err := db.Model(&model.Inbound{}).Count(&count).Error; err != nil {
  749. return needRestart, err
  750. }
  751. if count == 0 {
  752. if err := db.Exec("DELETE FROM sqlite_sequence WHERE name = ?", "inbounds").Error; err != nil {
  753. return needRestart, err
  754. }
  755. }
  756. }
  757. // Drop the egress SOCKS bridge a routed mtproto inbound left in the config.
  758. if mtprotoRoutesThroughXray(&ib) {
  759. needRestart = true
  760. }
  761. return needRestart, nil
  762. }
  763. type BulkDelInboundResult struct {
  764. Deleted int `json:"deleted"`
  765. Skipped []BulkDelInboundReport `json:"skipped,omitempty"`
  766. }
  767. type BulkDelInboundReport struct {
  768. Id int `json:"id"`
  769. Reason string `json:"reason"`
  770. }
  771. // DelInbounds removes every inbound in the list, reusing the single-delete
  772. // path per id. Failures are recorded in Skipped and processing continues for
  773. // the rest; the aggregated needRestart is returned so the caller restarts
  774. // xray at most once.
  775. func (s *InboundService) DelInbounds(ids []int) (BulkDelInboundResult, bool, error) {
  776. result := BulkDelInboundResult{}
  777. needRestart := false
  778. for _, id := range ids {
  779. r, err := s.DelInbound(id)
  780. if err != nil {
  781. result.Skipped = append(result.Skipped, BulkDelInboundReport{Id: id, Reason: err.Error()})
  782. continue
  783. }
  784. result.Deleted++
  785. if r {
  786. needRestart = true
  787. }
  788. }
  789. return result, needRestart, nil
  790. }
  791. func (s *InboundService) GetInbound(id int) (*model.Inbound, error) {
  792. db := database.GetDB()
  793. inbound := &model.Inbound{}
  794. err := db.Model(model.Inbound{}).First(inbound, id).Error
  795. if err != nil {
  796. return nil, err
  797. }
  798. return inbound, nil
  799. }
  800. func (s *InboundService) GetInboundDetail(id int) (*model.Inbound, error) {
  801. db := database.GetDB()
  802. inbound := &model.Inbound{}
  803. err := db.Model(model.Inbound{}).Preload("ClientStats").First(inbound, id).Error
  804. if err != nil {
  805. return nil, err
  806. }
  807. s.enrichClientStats(db, []*model.Inbound{inbound})
  808. s.overlayInboundsClientStats(db, []*model.Inbound{inbound})
  809. return inbound, nil
  810. }
  811. func (s *InboundService) SetInboundEnable(id int, enable bool) (bool, error) {
  812. inbound, err := s.GetInbound(id)
  813. if err != nil {
  814. return false, err
  815. }
  816. if inbound.Enable == enable {
  817. return false, nil
  818. }
  819. db := database.GetDB()
  820. if err := db.Model(model.Inbound{}).Where("id = ?", id).
  821. Update("enable", enable).Error; err != nil {
  822. return false, err
  823. }
  824. inbound.Enable = enable
  825. needRestart := false
  826. rt, push, dirty, perr := s.nodePushPlan(inbound)
  827. if perr != nil {
  828. return false, perr
  829. }
  830. // Remote nodes interpret DelInbound as a real row delete (it hits
  831. // panel/api/inbounds/del/:id on the remote), so toggling the enable
  832. // switch on a remote inbound used to wipe the row entirely (#4402).
  833. // PATCH the remote row via UpdateInbound instead — preserves the
  834. // settings/client history and just flips the enable flag.
  835. if inbound.NodeID != nil {
  836. if push {
  837. if err := rt.UpdateInbound(context.Background(), inbound, inbound); err != nil {
  838. logger.Warning("SetInboundEnable: remote UpdateInbound on", rt.Name(), "failed:", err)
  839. dirty = true
  840. }
  841. }
  842. if dirty {
  843. if dErr := (&NodeService{}).MarkNodeDirty(*inbound.NodeID); dErr != nil {
  844. logger.Warning("mark node dirty failed:", dErr)
  845. }
  846. }
  847. return false, nil
  848. }
  849. if !push {
  850. return true, nil
  851. }
  852. if err := rt.DelInbound(context.Background(), inbound); err != nil &&
  853. !strings.Contains(err.Error(), "not found") {
  854. logger.Debug("SetInboundEnable: DelInbound on", rt.Name(), "failed:", err)
  855. needRestart = true
  856. }
  857. if !enable {
  858. return needRestart, nil
  859. }
  860. runtimeInbound, err := s.buildRuntimeInboundForAPI(db, inbound)
  861. if err != nil {
  862. logger.Debug("SetInboundEnable: build runtime config failed:", err)
  863. return true, nil
  864. }
  865. if err := rt.AddInbound(context.Background(), runtimeInbound); err != nil {
  866. logger.Debug("SetInboundEnable: AddInbound on", rt.Name(), "failed:", err)
  867. needRestart = true
  868. }
  869. return needRestart, nil
  870. }
  871. func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  872. // Normalize streamSettings based on protocol
  873. s.normalizeStreamSettings(inbound)
  874. s.normalizeMtprotoSecret(inbound)
  875. inbound.SubSortIndex = normalizeSubSortIndex(inbound.SubSortIndex)
  876. conflict, err := s.checkPortConflict(inbound, inbound.Id)
  877. if err != nil {
  878. return inbound, false, err
  879. }
  880. if conflict != nil {
  881. return inbound, false, common.NewError(conflict.String())
  882. }
  883. oldInbound, err := s.GetInbound(inbound.Id)
  884. if err != nil {
  885. return inbound, false, err
  886. }
  887. inbound.NodeID = oldInbound.NodeID
  888. // Capture the pre-edit routing state before oldInbound.Settings is replaced
  889. // with the new settings further down, then ensure a routed inbound keeps a
  890. // stable egress port (reusing the one already stored).
  891. oldRoutedMtproto := mtprotoRoutesThroughXray(oldInbound)
  892. if err := s.normalizeMtprotoXrayPort(inbound, oldInbound.Settings); err != nil {
  893. return inbound, false, err
  894. }
  895. tag := oldInbound.Tag
  896. oldBits := inboundTransports(oldInbound.Protocol, oldInbound.StreamSettings, oldInbound.Settings)
  897. oldTagWasAuto := isAutoGeneratedTag(tag, oldInbound.Port, oldInbound.NodeID, oldBits)
  898. db := database.GetDB()
  899. tx := db.Begin()
  900. markDirty := false
  901. defer func() {
  902. if err != nil {
  903. tx.Rollback()
  904. return
  905. }
  906. tx.Commit()
  907. if markDirty && oldInbound.NodeID != nil {
  908. if dErr := (&NodeService{}).MarkNodeDirty(*oldInbound.NodeID); dErr != nil {
  909. logger.Warning("mark node dirty failed:", dErr)
  910. }
  911. }
  912. }()
  913. err = s.updateClientTraffics(tx, oldInbound, inbound)
  914. if err != nil {
  915. return inbound, false, err
  916. }
  917. // Ensure created_at and updated_at exist in inbound.Settings clients
  918. {
  919. var oldSettings map[string]any
  920. _ = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  921. emailToCreated := map[string]int64{}
  922. emailToUpdated := map[string]int64{}
  923. if oldSettings != nil {
  924. if oc, ok := oldSettings["clients"].([]any); ok {
  925. for _, it := range oc {
  926. if m, ok2 := it.(map[string]any); ok2 {
  927. if email, ok3 := m["email"].(string); ok3 {
  928. switch v := m["created_at"].(type) {
  929. case float64:
  930. emailToCreated[email] = int64(v)
  931. case int64:
  932. emailToCreated[email] = v
  933. }
  934. switch v := m["updated_at"].(type) {
  935. case float64:
  936. emailToUpdated[email] = int64(v)
  937. case int64:
  938. emailToUpdated[email] = v
  939. }
  940. }
  941. }
  942. }
  943. }
  944. }
  945. var newSettings map[string]any
  946. if err2 := json.Unmarshal([]byte(inbound.Settings), &newSettings); err2 == nil && newSettings != nil {
  947. now := time.Now().Unix() * 1000
  948. if nSlice, ok := newSettings["clients"].([]any); ok {
  949. for i := range nSlice {
  950. if m, ok2 := nSlice[i].(map[string]any); ok2 {
  951. email, _ := m["email"].(string)
  952. if _, ok3 := m["created_at"]; !ok3 {
  953. if v, ok4 := emailToCreated[email]; ok4 && v > 0 {
  954. m["created_at"] = v
  955. } else {
  956. m["created_at"] = now
  957. }
  958. }
  959. // Preserve client's updated_at if present; do not bump on parent inbound update
  960. if _, hasUpdated := m["updated_at"]; !hasUpdated {
  961. if v, ok4 := emailToUpdated[email]; ok4 && v > 0 {
  962. m["updated_at"] = v
  963. }
  964. }
  965. nSlice[i] = m
  966. }
  967. }
  968. newSettings["clients"] = nSlice
  969. if bs, err3 := json.MarshalIndent(newSettings, "", " "); err3 == nil {
  970. inbound.Settings = string(bs)
  971. }
  972. }
  973. }
  974. }
  975. oldInbound.Total = inbound.Total
  976. oldInbound.Remark = inbound.Remark
  977. oldInbound.SubSortIndex = inbound.SubSortIndex
  978. oldInbound.Enable = inbound.Enable
  979. oldInbound.ExpiryTime = inbound.ExpiryTime
  980. oldInbound.TrafficReset = inbound.TrafficReset
  981. oldInbound.Listen = inbound.Listen
  982. oldInbound.Port = inbound.Port
  983. oldInbound.Protocol = inbound.Protocol
  984. oldInbound.Settings = inbound.Settings
  985. oldInbound.StreamSettings = inbound.StreamSettings
  986. oldInbound.Sniffing = inbound.Sniffing
  987. if strings.TrimSpace(inbound.ShareAddrStrategy) == "" {
  988. normalizeInboundShareAddress(oldInbound)
  989. inbound.ShareAddrStrategy = oldInbound.ShareAddrStrategy
  990. inbound.ShareAddr = oldInbound.ShareAddr
  991. } else {
  992. if err := normalizeInboundShareAddressStrict(inbound); err != nil {
  993. return inbound, false, err
  994. }
  995. oldInbound.ShareAddrStrategy = inbound.ShareAddrStrategy
  996. oldInbound.ShareAddr = inbound.ShareAddr
  997. }
  998. if oldTagWasAuto && inbound.Tag == tag {
  999. inbound.Tag = ""
  1000. }
  1001. oldInbound.Tag, err = s.resolveInboundTag(inbound, inbound.Id)
  1002. if err != nil {
  1003. return inbound, false, err
  1004. }
  1005. inbound.Tag = oldInbound.Tag
  1006. needRestart := false
  1007. rt, push, dirty, perr := s.nodePushPlan(oldInbound)
  1008. if perr != nil {
  1009. err = perr
  1010. return inbound, false, err
  1011. }
  1012. if dirty {
  1013. markDirty = true
  1014. }
  1015. if oldInbound.NodeID == nil {
  1016. if !push {
  1017. needRestart = true
  1018. } else {
  1019. oldSnapshot := *oldInbound
  1020. oldSnapshot.Tag = tag
  1021. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 == nil {
  1022. logger.Debug("Old inbound deleted on", rt.Name(), ":", tag)
  1023. }
  1024. if inbound.Enable {
  1025. runtimeInbound, err2 := s.buildRuntimeInboundForAPI(tx, oldInbound)
  1026. if err2 != nil {
  1027. logger.Debug("Unable to prepare runtime inbound config:", err2)
  1028. needRestart = true
  1029. } else if err2 := rt.AddInbound(context.Background(), runtimeInbound); err2 == nil {
  1030. logger.Debug("Updated inbound added on", rt.Name(), ":", oldInbound.Tag)
  1031. } else {
  1032. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  1033. needRestart = true
  1034. }
  1035. }
  1036. }
  1037. } else if push {
  1038. oldSnapshot := *oldInbound
  1039. oldSnapshot.Tag = tag
  1040. if !inbound.Enable {
  1041. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 != nil {
  1042. logger.Warning("Unable to disable inbound on", rt.Name(), ":", err2)
  1043. markDirty = true
  1044. }
  1045. } else if err2 := rt.UpdateInbound(context.Background(), &oldSnapshot, oldInbound); err2 != nil {
  1046. logger.Warning("Unable to update inbound on", rt.Name(), ":", err2)
  1047. markDirty = true
  1048. }
  1049. }
  1050. // A rename must allow the new tag before the deferred commit, or a node in
  1051. // "selected" sync mode would sweep the renamed central row on the next pull.
  1052. if oldInbound.NodeID != nil {
  1053. if aErr := (&NodeService{}).EnsureInboundTagAllowed(*oldInbound.NodeID, oldInbound.Tag); aErr != nil {
  1054. logger.Warning("allow inbound tag on node failed:", aErr)
  1055. }
  1056. }
  1057. if err = tx.Save(oldInbound).Error; err != nil {
  1058. return inbound, false, err
  1059. }
  1060. newClients, gcErr := s.GetClients(oldInbound)
  1061. if gcErr != nil {
  1062. err = gcErr
  1063. return inbound, false, err
  1064. }
  1065. if err = s.clientService.SyncInbound(tx, oldInbound.Id, newClients); err != nil {
  1066. return inbound, false, err
  1067. }
  1068. // (Re)generate the Xray config whenever routing was or is now enabled, so the
  1069. // egress SOCKS bridge is added, moved, or dropped to match the new settings.
  1070. if mtprotoRoutesThroughXray(inbound) || oldRoutedMtproto {
  1071. needRestart = true
  1072. }
  1073. return inbound, needRestart, nil
  1074. }
  1075. func (s *InboundService) buildRuntimeInboundForAPI(tx *gorm.DB, inbound *model.Inbound) (*model.Inbound, error) {
  1076. if inbound == nil {
  1077. return nil, fmt.Errorf("inbound is nil")
  1078. }
  1079. runtimeInbound := *inbound
  1080. settings := map[string]any{}
  1081. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1082. return nil, err
  1083. }
  1084. clients, ok := settings["clients"].([]any)
  1085. if !ok {
  1086. return &runtimeInbound, nil
  1087. }
  1088. var clientStats []xray.ClientTraffic
  1089. err := tx.Model(xray.ClientTraffic{}).
  1090. Where("inbound_id = ?", inbound.Id).
  1091. Select("email", "enable").
  1092. Find(&clientStats).Error
  1093. if err != nil {
  1094. return nil, err
  1095. }
  1096. enableMap := make(map[string]bool, len(clientStats))
  1097. for _, clientTraffic := range clientStats {
  1098. enableMap[clientTraffic.Email] = clientTraffic.Enable
  1099. }
  1100. finalClients := make([]any, 0, len(clients))
  1101. for _, client := range clients {
  1102. c, ok := client.(map[string]any)
  1103. if !ok {
  1104. continue
  1105. }
  1106. email, _ := c["email"].(string)
  1107. if enable, exists := enableMap[email]; exists && !enable {
  1108. continue
  1109. }
  1110. if manualEnable, ok := c["enable"].(bool); ok && !manualEnable {
  1111. continue
  1112. }
  1113. finalClients = append(finalClients, c)
  1114. }
  1115. settings["clients"] = finalClients
  1116. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1117. if err != nil {
  1118. return nil, err
  1119. }
  1120. runtimeInbound.Settings = string(modifiedSettings)
  1121. return &runtimeInbound, nil
  1122. }
  1123. // updateClientTraffics syncs the ClientTraffic rows with the inbound's clients
  1124. // list: removes rows for emails that disappeared, inserts rows for newly-added
  1125. // emails. Uses sets for O(N) lookup — the previous nested-loop implementation
  1126. // was O(N²) and degraded into multi-second pauses on inbounds with thousands
  1127. // of clients (toggling, saving, or deleting any such inbound felt frozen).
  1128. func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inbound, newInbound *model.Inbound) error {
  1129. oldClients, err := s.GetClients(oldInbound)
  1130. if err != nil {
  1131. return err
  1132. }
  1133. newClients, err := s.GetClients(newInbound)
  1134. if err != nil {
  1135. return err
  1136. }
  1137. // Email is the unique key for ClientTraffic rows. Clients without an
  1138. // email have no stats row to sync — skip them on both sides instead of
  1139. // risking a unique-constraint hit or accidental delete of an unrelated row.
  1140. oldEmails := make(map[string]struct{}, len(oldClients))
  1141. for i := range oldClients {
  1142. if oldClients[i].Email == "" {
  1143. continue
  1144. }
  1145. oldEmails[oldClients[i].Email] = struct{}{}
  1146. }
  1147. newEmails := make(map[string]struct{}, len(newClients))
  1148. for i := range newClients {
  1149. if newClients[i].Email == "" {
  1150. continue
  1151. }
  1152. newEmails[newClients[i].Email] = struct{}{}
  1153. }
  1154. // Drop stats rows for removed emails — but not when a sibling inbound
  1155. // still references the email, since the row is the shared accumulator.
  1156. for i := range oldClients {
  1157. email := oldClients[i].Email
  1158. if email == "" {
  1159. continue
  1160. }
  1161. if _, kept := newEmails[email]; kept {
  1162. continue
  1163. }
  1164. stillUsed, err := s.emailUsedByOtherInbounds(email, oldInbound.Id)
  1165. if err != nil {
  1166. return err
  1167. }
  1168. if stillUsed {
  1169. continue
  1170. }
  1171. if err := s.DelClientStat(tx, email); err != nil {
  1172. return err
  1173. }
  1174. // Keep inbound_client_ips in sync when the inbound edit drops an
  1175. // email, so the IP-limit job doesn't keep a ghost tracking row (#4963).
  1176. if err := s.DelClientIPs(tx, email); err != nil {
  1177. return err
  1178. }
  1179. }
  1180. for i := range newClients {
  1181. email := newClients[i].Email
  1182. if email == "" {
  1183. continue
  1184. }
  1185. if _, existed := oldEmails[email]; existed {
  1186. if err := s.UpdateClientStat(tx, email, &newClients[i]); err != nil {
  1187. return err
  1188. }
  1189. continue
  1190. }
  1191. if err := s.AddClientStat(tx, oldInbound.Id, &newClients[i]); err != nil {
  1192. return err
  1193. }
  1194. }
  1195. return nil
  1196. }
  1197. func (s *InboundService) GetInboundTags() (string, error) {
  1198. db := database.GetDB()
  1199. var inboundTags []string
  1200. err := db.Model(model.Inbound{}).Select("tag").Find(&inboundTags).Error
  1201. if err != nil && err != gorm.ErrRecordNotFound {
  1202. return "", err
  1203. }
  1204. tags, _ := json.Marshal(inboundTags)
  1205. return string(tags), nil
  1206. }
  1207. func (s *InboundService) GetClientReverseTags() (string, error) {
  1208. db := database.GetDB()
  1209. var inbounds []model.Inbound
  1210. err := db.Model(model.Inbound{}).Select("settings").Where("protocol = ?", "vless").Find(&inbounds).Error
  1211. if err != nil && err != gorm.ErrRecordNotFound {
  1212. return "[]", err
  1213. }
  1214. tagSet := make(map[string]struct{})
  1215. for _, inbound := range inbounds {
  1216. var settings map[string]any
  1217. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1218. continue
  1219. }
  1220. clients, ok := settings["clients"].([]any)
  1221. if !ok {
  1222. continue
  1223. }
  1224. for _, client := range clients {
  1225. clientMap, ok := client.(map[string]any)
  1226. if !ok {
  1227. continue
  1228. }
  1229. reverse, ok := clientMap["reverse"].(map[string]any)
  1230. if !ok {
  1231. continue
  1232. }
  1233. tag, _ := reverse["tag"].(string)
  1234. tag = strings.TrimSpace(tag)
  1235. if tag != "" {
  1236. tagSet[tag] = struct{}{}
  1237. }
  1238. }
  1239. }
  1240. rawTags := make([]string, 0, len(tagSet))
  1241. for tag := range tagSet {
  1242. rawTags = append(rawTags, tag)
  1243. }
  1244. sort.Strings(rawTags)
  1245. result, _ := json.Marshal(rawTags)
  1246. return string(result), nil
  1247. }
  1248. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  1249. db := database.GetDB()
  1250. var inbounds []*model.Inbound
  1251. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  1252. if err != nil && err != gorm.ErrRecordNotFound {
  1253. return nil, err
  1254. }
  1255. return inbounds, nil
  1256. }