inbound.go 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774
  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. "errors"
  8. "fmt"
  9. "net"
  10. "regexp"
  11. "sort"
  12. "strings"
  13. "time"
  14. "github.com/google/uuid"
  15. "github.com/mhsanaei/3x-ui/v3/internal/database"
  16. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  17. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  18. "github.com/mhsanaei/3x-ui/v3/internal/mtproto"
  19. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  20. "github.com/mhsanaei/3x-ui/v3/internal/util/netsafe"
  21. wgutil "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard"
  22. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  23. "gorm.io/gorm"
  24. "gorm.io/gorm/clause"
  25. )
  26. type InboundService struct {
  27. xrayApi xray.XrayAPI
  28. clientService ClientService
  29. fallbackService FallbackService
  30. }
  31. func normalizeInboundShareAddrStrategy(strategy string) string {
  32. strategy = strings.TrimSpace(strategy)
  33. switch strategy {
  34. case "listen", "custom":
  35. return strategy
  36. default:
  37. return "node"
  38. }
  39. }
  40. func normalizeInboundShareAddress(inbound *model.Inbound) {
  41. if inbound == nil {
  42. return
  43. }
  44. inbound.ShareAddrStrategy = normalizeInboundShareAddrStrategy(inbound.ShareAddrStrategy)
  45. if addr, err := normalizeInboundShareHost(inbound.ShareAddr); err == nil {
  46. inbound.ShareAddr = addr
  47. } else {
  48. inbound.ShareAddr = strings.TrimSpace(inbound.ShareAddr)
  49. }
  50. }
  51. func normalizeInboundShareAddressStrict(inbound *model.Inbound) error {
  52. if inbound == nil {
  53. return nil
  54. }
  55. inbound.ShareAddrStrategy = normalizeInboundShareAddrStrategy(inbound.ShareAddrStrategy)
  56. addr, err := normalizeInboundShareHost(inbound.ShareAddr)
  57. if err != nil {
  58. return common.NewError("shareAddr must be a host or IP without scheme or port")
  59. }
  60. inbound.ShareAddr = addr
  61. return nil
  62. }
  63. func normalizeInboundShareHost(raw string) (string, error) {
  64. addr := strings.TrimSpace(raw)
  65. if addr == "" {
  66. return "", nil
  67. }
  68. if strings.Contains(addr, "://") || strings.HasPrefix(addr, "//") || strings.ContainsAny(addr, "/?#@") {
  69. return "", fmt.Errorf("invalid share address %q", raw)
  70. }
  71. if strings.HasPrefix(addr, "[") {
  72. if !strings.HasSuffix(addr, "]") {
  73. return "", fmt.Errorf("invalid IPv6 host %q", raw)
  74. }
  75. ip := net.ParseIP(addr[1 : len(addr)-1])
  76. if ip == nil || ip.To4() != nil {
  77. return "", fmt.Errorf("invalid IPv6 host %q", raw)
  78. }
  79. return "[" + ip.String() + "]", nil
  80. }
  81. if strings.Contains(addr, ":") {
  82. if _, _, err := net.SplitHostPort(addr); err == nil {
  83. return "", fmt.Errorf("share address must not include port")
  84. }
  85. ip := net.ParseIP(addr)
  86. if ip == nil || ip.To4() != nil {
  87. return "", fmt.Errorf("invalid IPv6 host %q", raw)
  88. }
  89. return "[" + ip.String() + "]", nil
  90. }
  91. host, err := netsafe.NormalizeHost(addr)
  92. if err != nil {
  93. return "", err
  94. }
  95. return host, nil
  96. }
  97. func normalizeInboundShareAddressColumns(tx *gorm.DB) error {
  98. if tx == nil || !tx.Migrator().HasColumn(&model.Inbound{}, "share_addr_strategy") {
  99. return nil
  100. }
  101. strategyExpr := `CASE TRIM(COALESCE(share_addr_strategy, '')) WHEN 'listen' THEN 'listen' WHEN 'custom' THEN 'custom' ELSE 'node' END`
  102. 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 {
  103. return err
  104. }
  105. hasShareAddr := tx.Migrator().HasColumn(&model.Inbound{}, "share_addr")
  106. if hasShareAddr {
  107. 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 {
  108. return err
  109. }
  110. }
  111. if !hasShareAddr {
  112. return nil
  113. }
  114. var rows []struct {
  115. Id int
  116. ShareAddrStrategy string
  117. ShareAddr string
  118. }
  119. if err := tx.Model(&model.Inbound{}).Select("id", "share_addr_strategy", "share_addr").Find(&rows).Error; err != nil {
  120. return err
  121. }
  122. for _, row := range rows {
  123. strategy := normalizeInboundShareAddrStrategy(row.ShareAddrStrategy)
  124. addr, addrErr := normalizeInboundShareHost(row.ShareAddr)
  125. if addrErr != nil {
  126. strategy = "node"
  127. addr = ""
  128. }
  129. updates := map[string]any{}
  130. if strategy != row.ShareAddrStrategy {
  131. updates["share_addr_strategy"] = strategy
  132. }
  133. if addr != row.ShareAddr {
  134. updates["share_addr"] = addr
  135. }
  136. if len(updates) > 0 {
  137. if err := tx.Model(&model.Inbound{}).Where("id = ?", row.Id).Updates(updates).Error; err != nil {
  138. return err
  139. }
  140. }
  141. }
  142. return nil
  143. }
  144. // GetInbounds retrieves all inbounds for a specific user with client stats.
  145. func (s *InboundService) GetInbounds(userId int) ([]*model.Inbound, error) {
  146. db := database.GetDB()
  147. var inbounds []*model.Inbound
  148. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("user_id = ?", userId).Order("id ASC").Find(&inbounds).Error
  149. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  150. return nil, err
  151. }
  152. s.enrichClientStats(db, inbounds)
  153. s.annotateFallbackParents(db, inbounds)
  154. s.annotateLocalOriginGuid(inbounds)
  155. return inbounds, nil
  156. }
  157. // annotateLocalOriginGuid fills OriginNodeGuid for this panel's OWN inbounds
  158. // (NodeID == nil) with the panel's stable GUID; inbounds synced from a node
  159. // already carry the originating node's GUID. Read-time only (not persisted) so
  160. // the per-inbound online view can scope by GUID uniformly across a chain of
  161. // nodes (#4983).
  162. func (s *InboundService) annotateLocalOriginGuid(inbounds []*model.Inbound) {
  163. if len(inbounds) == 0 {
  164. return
  165. }
  166. guid := s.panelGuid()
  167. if guid == "" {
  168. return
  169. }
  170. for _, ib := range inbounds {
  171. if ib.OriginNodeGuid == "" && ib.NodeID == nil {
  172. ib.OriginNodeGuid = guid
  173. }
  174. }
  175. }
  176. // GetInboundsSlim returns the same list of inbounds as GetInbounds but
  177. // strips every per-client field other than email / enable / comment from
  178. // settings.clients and skips UUID/SubId enrichment on ClientStats. The
  179. // inbounds page only needs those three to roll up client counts and
  180. // render badges, so this trims tens of bytes per client (UUID, password,
  181. // flow, security, totalGB, expiryTime, limitIp, tgId, ...) which adds
  182. // up fast on installs with thousands of clients.
  183. //
  184. // Full client data is still available through GET /panel/api/inbounds/get/:id
  185. // for the edit/info/qr/export/clone flows that need it.
  186. func (s *InboundService) GetInboundsSlim(userId int) ([]*model.Inbound, error) {
  187. db := database.GetDB()
  188. var inbounds []*model.Inbound
  189. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("user_id = ?", userId).Order("id ASC").Find(&inbounds).Error
  190. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  191. return nil, err
  192. }
  193. s.annotateFallbackParents(db, inbounds)
  194. s.annotateLocalOriginGuid(inbounds)
  195. // Top up stats rows owned by sibling inbounds (multi-attached clients)
  196. // so the list's depleted/expiring badges see every client; the UUID/SubId
  197. // enrichment stays skipped. Must run before slimming strips the settings.
  198. s.backfillClientStats(db, inbounds)
  199. // Slim feeds the panel UI only (masters poll the full list), so the badge
  200. // math may see the cross-panel totals a master pushed.
  201. s.overlayInboundsClientStats(db, inbounds)
  202. for _, ib := range inbounds {
  203. ib.Settings = slimSettingsClients(ib.Settings)
  204. }
  205. return inbounds, nil
  206. }
  207. // slimSettingsClients rewrites the inbound settings JSON so settings.clients[]
  208. // keeps only the fields the list view actually reads. Returns the input
  209. // unchanged when the JSON can't be parsed or has no clients array.
  210. func slimSettingsClients(settings string) string {
  211. if settings == "" {
  212. return settings
  213. }
  214. var raw map[string]any
  215. if err := json.Unmarshal([]byte(settings), &raw); err != nil {
  216. return settings
  217. }
  218. clients, ok := raw["clients"].([]any)
  219. if !ok || len(clients) == 0 {
  220. return settings
  221. }
  222. slim := make([]any, 0, len(clients))
  223. for _, entry := range clients {
  224. c, ok := entry.(map[string]any)
  225. if !ok {
  226. continue
  227. }
  228. row := make(map[string]any, 3)
  229. if v, ok := c["email"]; ok {
  230. row["email"] = v
  231. }
  232. if v, ok := c["enable"]; ok {
  233. row["enable"] = v
  234. }
  235. if v, ok := c["comment"]; ok && v != "" {
  236. row["comment"] = v
  237. }
  238. slim = append(slim, row)
  239. }
  240. raw["clients"] = slim
  241. out, err := json.Marshal(raw)
  242. if err != nil {
  243. return settings
  244. }
  245. return string(out)
  246. }
  247. // annotateFallbackParents fills FallbackParent on each inbound that is
  248. // the child side of a fallback rule. One DB round-trip serves the full
  249. // list — the frontend needs this to rewrite the child's client-share
  250. // link so it points at the master's reachable endpoint.
  251. func (s *InboundService) annotateFallbackParents(db *gorm.DB, inbounds []*model.Inbound) {
  252. if len(inbounds) == 0 {
  253. return
  254. }
  255. childIds := make([]int, 0, len(inbounds))
  256. for _, ib := range inbounds {
  257. childIds = append(childIds, ib.Id)
  258. }
  259. var rows []model.InboundFallback
  260. if err := db.Where("child_id IN ?", childIds).
  261. Order("sort_order ASC, id ASC").
  262. Find(&rows).Error; err != nil {
  263. return
  264. }
  265. first := make(map[int]model.InboundFallback, len(rows))
  266. for _, r := range rows {
  267. if _, ok := first[r.ChildId]; !ok {
  268. first[r.ChildId] = r
  269. }
  270. }
  271. for _, ib := range inbounds {
  272. if r, ok := first[ib.Id]; ok {
  273. ib.FallbackParent = &model.FallbackParentInfo{
  274. MasterId: r.MasterId,
  275. Path: r.Path,
  276. }
  277. }
  278. }
  279. }
  280. type InboundOption struct {
  281. Id int `json:"id" example:"1"`
  282. Remark string `json:"remark" example:"VLESS-443"`
  283. Tag string `json:"tag" example:"in-443-tcp"`
  284. Protocol string `json:"protocol" example:"vless"`
  285. Port int `json:"port" example:"443"`
  286. Enable bool `json:"enable" example:"true"`
  287. TlsFlowCapable bool `json:"tlsFlowCapable" example:"true"`
  288. SsMethod string `json:"ssMethod"`
  289. WgPublicKey string `json:"wgPublicKey,omitempty"`
  290. WgMtu int `json:"wgMtu,omitempty"`
  291. WgDns string `json:"wgDns,omitempty"`
  292. MtprotoDomain string `json:"mtprotoDomain,omitempty"`
  293. // Hosting node; nil for this panel's own inbounds. Lets the clients
  294. // page map a node filter onto inbound IDs (#4997).
  295. NodeId *int `json:"nodeId,omitempty"`
  296. // Share-host resolution inputs, mirroring the subscription's
  297. // resolveInboundAddress so the clients page renders a node-managed WireGuard
  298. // Endpoint that points at the node, not the master panel. NodeAddress is the
  299. // hosting node's externally reachable address (empty for this panel's own
  300. // inbounds); Listen and ShareAddrStrategy/ShareAddr feed the same
  301. // node→listen→custom fallback the share/QR links already use.
  302. NodeAddress string `json:"nodeAddress,omitempty"`
  303. Listen string `json:"listen,omitempty"`
  304. ShareAddr string `json:"shareAddr,omitempty"`
  305. ShareAddrStrategy string `json:"shareAddrStrategy,omitempty"`
  306. }
  307. func (s *InboundService) GetInboundOptions(userId int) ([]InboundOption, error) {
  308. db := database.GetDB()
  309. var rows []struct {
  310. Id int `gorm:"column:id"`
  311. Remark string `gorm:"column:remark"`
  312. Tag string `gorm:"column:tag"`
  313. Protocol string `gorm:"column:protocol"`
  314. Port int `gorm:"column:port"`
  315. Enable bool `gorm:"column:enable"`
  316. StreamSettings string `gorm:"column:stream_settings"`
  317. Settings string `gorm:"column:settings"`
  318. Listen string `gorm:"column:listen"`
  319. ShareAddr string `gorm:"column:share_addr"`
  320. ShareAddrStrategy string `gorm:"column:share_addr_strategy"`
  321. NodeId *int `gorm:"column:node_id"`
  322. NodeAddress string `gorm:"column:node_address"`
  323. }
  324. err := db.Table("inbounds").
  325. Select("inbounds.id, inbounds.remark, inbounds.tag, inbounds.protocol, inbounds.port, inbounds.enable, inbounds.stream_settings, inbounds.settings, inbounds.listen, inbounds.share_addr, inbounds.share_addr_strategy, inbounds.node_id, COALESCE(nodes.address, '') AS node_address").
  326. Joins("LEFT JOIN nodes ON nodes.id = inbounds.node_id").
  327. Where("inbounds.user_id = ?", userId).
  328. Order("inbounds.id ASC").
  329. Scan(&rows).Error
  330. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  331. return nil, err
  332. }
  333. out := make([]InboundOption, 0, len(rows))
  334. for _, r := range rows {
  335. wgPublicKey, wgMtu, wgDns := inboundWireguardHints(r.Protocol, r.Settings)
  336. shareAddrStrategy := r.ShareAddrStrategy
  337. if shareAddrStrategy == "node" {
  338. shareAddrStrategy = ""
  339. }
  340. out = append(out, InboundOption{
  341. Id: r.Id,
  342. Remark: r.Remark,
  343. Tag: r.Tag,
  344. Protocol: r.Protocol,
  345. Port: r.Port,
  346. Enable: r.Enable,
  347. TlsFlowCapable: inboundCanEnableTlsFlow(r.Protocol, r.StreamSettings, r.Settings),
  348. SsMethod: inboundShadowsocksMethod(r.Protocol, r.Settings),
  349. WgPublicKey: wgPublicKey,
  350. WgMtu: wgMtu,
  351. WgDns: wgDns,
  352. MtprotoDomain: inboundMtprotoDomain(r.Protocol, r.Settings),
  353. NodeId: r.NodeId,
  354. NodeAddress: r.NodeAddress,
  355. Listen: r.Listen,
  356. ShareAddr: r.ShareAddr,
  357. ShareAddrStrategy: shareAddrStrategy,
  358. })
  359. }
  360. return out, nil
  361. }
  362. func inboundWireguardHints(protocol string, settings string) (string, int, string) {
  363. if protocol != string(model.WireGuard) || strings.TrimSpace(settings) == "" {
  364. return "", 0, ""
  365. }
  366. var parsed struct {
  367. PublicKey string `json:"publicKey"`
  368. PubKey string `json:"pubKey"`
  369. SecretKey string `json:"secretKey"`
  370. MTU int `json:"mtu"`
  371. DNS string `json:"dns"`
  372. }
  373. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  374. return "", 0, ""
  375. }
  376. publicKey := parsed.PublicKey
  377. if publicKey == "" {
  378. publicKey = parsed.PubKey
  379. }
  380. if publicKey == "" && parsed.SecretKey != "" {
  381. if derived, err := wgutil.PublicKeyFromPrivate(parsed.SecretKey); err == nil {
  382. publicKey = derived
  383. }
  384. }
  385. return publicKey, parsed.MTU, parsed.DNS
  386. }
  387. // inboundMtprotoDomain returns the inbound-level FakeTLS default domain, used by
  388. // the clients UI to seed a new mtproto client's secret with the right fronting
  389. // hostname.
  390. func inboundMtprotoDomain(protocol string, settings string) string {
  391. if protocol != string(model.MTProto) || strings.TrimSpace(settings) == "" {
  392. return ""
  393. }
  394. var parsed struct {
  395. FakeTLSDomain string `json:"fakeTlsDomain"`
  396. }
  397. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  398. return ""
  399. }
  400. return strings.TrimSpace(parsed.FakeTLSDomain)
  401. }
  402. // GetAllInbounds retrieves all inbounds with client stats.
  403. func (s *InboundService) GetAllInbounds() ([]*model.Inbound, error) {
  404. db := database.GetDB()
  405. var inbounds []*model.Inbound
  406. err := db.Model(model.Inbound{}).Preload("ClientStats").Find(&inbounds).Error
  407. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  408. return nil, err
  409. }
  410. s.enrichClientStats(db, inbounds)
  411. return inbounds, nil
  412. }
  413. func (s *InboundService) GetInboundsByTrafficReset(period string) ([]*model.Inbound, error) {
  414. db := database.GetDB()
  415. var inbounds []*model.Inbound
  416. err := db.Model(model.Inbound{}).Where("traffic_reset = ?", period).Find(&inbounds).Error
  417. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  418. return nil, err
  419. }
  420. return inbounds, nil
  421. }
  422. func (s *InboundService) GetClients(inbound *model.Inbound) ([]model.Client, error) {
  423. return ParseInboundSettingsClients(inbound.Settings)
  424. }
  425. // GetClientsBySubId returns the inbound's clients with the given subscription
  426. // id, resolved from the normalized clients tables (the same source the running
  427. // Xray users are built from) instead of parsing the settings JSON blob.
  428. func (s *InboundService) GetClientsBySubId(inboundId int, subId string) ([]model.Client, error) {
  429. return s.clientService.ListForInboundBySubId(nil, inboundId, subId)
  430. }
  431. func (s *InboundService) GetAllEmails() ([]string, error) {
  432. db := database.GetDB()
  433. var emails []string
  434. query := fmt.Sprintf(
  435. "SELECT DISTINCT %s %s",
  436. database.JSONFieldText("client.value", "email"),
  437. database.JSONClientsFromInbound(),
  438. )
  439. if err := db.Raw(query).Scan(&emails).Error; err != nil {
  440. return nil, err
  441. }
  442. return emails, nil
  443. }
  444. // getAllEmailSubIDs returns email→subId. An email seen with two different
  445. // non-empty subIds is locked (mapped to "") so neither identity can claim it.
  446. func (s *InboundService) getAllEmailSubIDs() (map[string]string, error) {
  447. db := database.GetDB()
  448. var rows []struct {
  449. Email string
  450. SubID string
  451. }
  452. query := fmt.Sprintf(
  453. "SELECT %s AS email, %s AS sub_id %s",
  454. database.JSONFieldText("client.value", "email"),
  455. database.JSONFieldText("client.value", "subId"),
  456. database.JSONClientsFromInbound(),
  457. )
  458. if err := db.Raw(query).Scan(&rows).Error; err != nil {
  459. return nil, err
  460. }
  461. result := make(map[string]string, len(rows))
  462. for _, r := range rows {
  463. email := strings.ToLower(r.Email)
  464. if email == "" {
  465. continue
  466. }
  467. subID := r.SubID
  468. if existing, ok := result[email]; ok {
  469. if existing != subID {
  470. result[email] = ""
  471. }
  472. continue
  473. }
  474. result[email] = subID
  475. }
  476. return result, nil
  477. }
  478. // normalizeStreamSettings clears StreamSettings for protocols that don't use it.
  479. // Only vmess, vless, trojan, shadowsocks, hysteria, wireguard, and tunnel
  480. // protocols use streamSettings (wireguard for finalmask UDP masks and sockopt on
  481. // its listener; tunnel for sockopt, notably sockopt.tproxy for its TProxy/redirect
  482. // mode). Streams keyed on "method" — xray-core v26.7.11's preferred alias for
  483. // "network" — are canonicalized to "network", which every panel reader (link
  484. // generation, port-conflict detection, flow eligibility) keys on.
  485. func (s *InboundService) normalizeStreamSettings(inbound *model.Inbound) {
  486. protocolsWithStream := map[model.Protocol]bool{
  487. model.VMESS: true,
  488. model.VLESS: true,
  489. model.Trojan: true,
  490. model.Shadowsocks: true,
  491. model.Hysteria: true,
  492. model.WireGuard: true,
  493. model.Tunnel: true,
  494. }
  495. if !protocolsWithStream[inbound.Protocol] {
  496. inbound.StreamSettings = ""
  497. return
  498. }
  499. inbound.StreamSettings = canonicalizeStreamNetworkKey(inbound.StreamSettings)
  500. }
  501. // canonicalizeStreamNetworkKey rewrites a streamSettings JSON that names its
  502. // transport under "method" to the panel-canonical "network" key. When both
  503. // keys are present, "method" wins — matching xray-core's own precedence.
  504. func canonicalizeStreamNetworkKey(streamSettings string) string {
  505. if streamSettings == "" {
  506. return streamSettings
  507. }
  508. var stream map[string]any
  509. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  510. return streamSettings
  511. }
  512. method, ok := stream["method"].(string)
  513. if !ok || method == "" {
  514. return streamSettings
  515. }
  516. stream["network"] = method
  517. delete(stream, "method")
  518. out, err := json.MarshalIndent(stream, "", " ")
  519. if err != nil {
  520. return streamSettings
  521. }
  522. return string(out)
  523. }
  524. // finalMaskRealityTcpMasks returns the stream's finalmask.tcp masks when the
  525. // stream uses REALITY security, or nil otherwise. A non-empty result means
  526. // this stream carries the finalmask+REALITY combination that panics
  527. // Xray-core (see https://github.com/XTLS/Xray-core/issues/6453): finalmask
  528. // wraps the connection before REALITY's handshake ever sees it, and
  529. // reality.Server() does an unchecked type assertion assuming a raw
  530. // *net.TCPConn, which panics once finalmask is in front of it.
  531. //
  532. // Only finalmask.tcp matters here — TcpmaskManager (the thing that wraps the
  533. // listener ahead of REALITY's handshake, in xray-core's own
  534. // transport/internet/memory_settings.go) is only constructed when tcp masks
  535. // are present; a finalmask.udp-only config never touches the TCP accept path
  536. // REALITY runs on, so it doesn't reproduce this panic and shouldn't be
  537. // rejected.
  538. func finalMaskRealityTcpMasks(stream map[string]any) []any {
  539. if stream["security"] != "reality" {
  540. return nil
  541. }
  542. finalmask, ok := stream["finalmask"].(map[string]any)
  543. if !ok {
  544. return nil
  545. }
  546. tcp, _ := finalmask["tcp"].([]any)
  547. return tcp
  548. }
  549. // validateFinalMaskRealityCombo rejects finalmask.tcp configured together
  550. // with REALITY security at save time. Upstream has confirmed this
  551. // combination will be documented as unsupported rather than made graceful,
  552. // so the panel must not let it be saved.
  553. func validateFinalMaskRealityCombo(streamSettings string) error {
  554. if streamSettings == "" {
  555. return nil
  556. }
  557. var stream map[string]any
  558. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  559. return nil
  560. }
  561. if len(finalMaskRealityTcpMasks(stream)) == 0 {
  562. return nil
  563. }
  564. return common.NewError("Finalmask is not supported with REALITY security — it crashes Xray-core on the first connection (see XTLS/Xray-core#6453). Remove the finalmask configuration or switch security to tls/none.")
  565. }
  566. var xmcProfileUsernamePattern = regexp.MustCompile(`^[A-Za-z0-9_]{3,16}$`)
  567. // xmcMaskProfilesComplete reports whether an xmc finalmask carries the signed
  568. // Minecraft session profiles xray-core has required since v26.7.28 (#6487).
  569. // The core replaced the old `usernames` string list with `profiles` objects
  570. // and removed the "default to Dream when empty" fallback, so a mask still on
  571. // the legacy shape — or one whose profiles are incomplete — now fails
  572. // conf.XMC.Build() and takes the entire config down with it rather than
  573. // degrading that one inbound.
  574. //
  575. // The texture fields are a signed blob only Mojang's session server can issue
  576. // (resolve the UUID by username, then fetch the profile with unsigned=false),
  577. // so the panel cannot synthesize a valid profile from a legacy username; an
  578. // incomplete mask can only be reported or dropped.
  579. func xmcMaskProfilesComplete(mask map[string]any) bool {
  580. settings, ok := mask["settings"].(map[string]any)
  581. if !ok {
  582. return false
  583. }
  584. profiles, _ := settings["profiles"].([]any)
  585. if len(profiles) == 0 {
  586. return false
  587. }
  588. for _, entry := range profiles {
  589. profile, ok := entry.(map[string]any)
  590. if !ok {
  591. return false
  592. }
  593. username, _ := profile["username"].(string)
  594. if !xmcProfileUsernamePattern.MatchString(username) {
  595. return false
  596. }
  597. id, _ := profile["uuid"].(string)
  598. if _, err := uuid.Parse(id); err != nil {
  599. return false
  600. }
  601. if value, _ := profile["texturesValue"].(string); value == "" {
  602. return false
  603. }
  604. if signature, _ := profile["texturesSignature"].(string); signature == "" {
  605. return false
  606. }
  607. }
  608. return true
  609. }
  610. // isIncompleteXmcMask reports whether a finalmask.tcp entry is an xmc mask
  611. // xray-core would refuse to build.
  612. func isIncompleteXmcMask(entry any) bool {
  613. mask, ok := entry.(map[string]any)
  614. if !ok {
  615. return false
  616. }
  617. if maskType, _ := mask["type"].(string); maskType != "xmc" {
  618. return false
  619. }
  620. return !xmcMaskProfilesComplete(mask)
  621. }
  622. // incompleteXmcMaskCount counts the stream's xmc finalmask entries that
  623. // xray-core would refuse to build.
  624. func incompleteXmcMaskCount(stream map[string]any) int {
  625. finalmask, ok := stream["finalmask"].(map[string]any)
  626. if !ok {
  627. return 0
  628. }
  629. tcp, _ := finalmask["tcp"].([]any)
  630. count := 0
  631. for _, entry := range tcp {
  632. if isIncompleteXmcMask(entry) {
  633. count++
  634. }
  635. }
  636. return count
  637. }
  638. // stripIncompleteXmcMasks removes every xmc finalmask entry xray-core would
  639. // refuse to build, returning how many were dropped, and clears the finalmask
  640. // object once nothing is left in it.
  641. //
  642. // AddInbound and UpdateInbound reject an incomplete mask at save time, but a
  643. // row that never went through those paths — an upgrade from a panel predating
  644. // v26.7.28, node sync, a restored backup, a direct DB edit — would otherwise
  645. // fail the whole config build and keep every other inbound offline too.
  646. // Dropping only the offending mask degrades that one inbound instead, which
  647. // the accompanying warning tells the admin to reconfigure.
  648. func stripIncompleteXmcMasks(stream map[string]any) int {
  649. finalmask, ok := stream["finalmask"].(map[string]any)
  650. if !ok {
  651. return 0
  652. }
  653. tcp, _ := finalmask["tcp"].([]any)
  654. if len(tcp) == 0 {
  655. return 0
  656. }
  657. kept := make([]any, 0, len(tcp))
  658. dropped := 0
  659. for _, entry := range tcp {
  660. if isIncompleteXmcMask(entry) {
  661. dropped++
  662. continue
  663. }
  664. kept = append(kept, entry)
  665. }
  666. if dropped == 0 {
  667. return 0
  668. }
  669. if len(kept) == 0 {
  670. delete(finalmask, "tcp")
  671. } else {
  672. finalmask["tcp"] = kept
  673. }
  674. if len(finalmask) == 0 {
  675. delete(stream, "finalmask")
  676. }
  677. return dropped
  678. }
  679. // validateFinalMaskXmcProfiles rejects an xmc finalmask without complete
  680. // profiles at save time, so the admin gets a targeted error instead of a core
  681. // that refuses to start (or, after GetXrayConfig heals it, an inbound quietly
  682. // serving without the obfuscation they configured).
  683. func validateFinalMaskXmcProfiles(streamSettings string) error {
  684. if streamSettings == "" {
  685. return nil
  686. }
  687. var stream map[string]any
  688. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  689. return nil
  690. }
  691. if incompleteXmcMaskCount(stream) == 0 {
  692. return nil
  693. }
  694. return common.NewError("XMC finalmask requires at least one complete Minecraft profile — each needs a username (3-16 of A-Z a-z 0-9 _), a UUID, and both texture fields from Mojang's session server (XTLS/Xray-core#6487). Complete the profiles or remove the XMC mask.")
  695. }
  696. // normalizeMtprotoSecret rebuilds every mtproto client's FakeTLS secret so it is
  697. // always valid before the row is persisted, and drops the vestigial inbound-level
  698. // secret and adTag: MTProto is multi-client, so mtg and every share link read
  699. // only the per-client values. Leaving an inbound-level secret behind is what
  700. // produced stale links that failed with "incorrect client random".
  701. func (s *InboundService) normalizeMtprotoSecret(inbound *model.Inbound) {
  702. if inbound.Protocol != model.MTProto {
  703. return
  704. }
  705. if stripped, ok := model.StripMtprotoInboundSecret(inbound.Settings); ok {
  706. inbound.Settings = stripped
  707. }
  708. if stripped, ok := model.StripMtprotoInboundAdTag(inbound.Settings); ok {
  709. inbound.Settings = stripped
  710. }
  711. if healed, ok := model.HealMtprotoClientSecrets(inbound.Settings); ok {
  712. inbound.Settings = healed
  713. }
  714. }
  715. // mtprotoRoutesThroughXray reports whether an mtproto inbound is configured to
  716. // egress through the core's router (the loopback SOCKS bridge in §xray.go).
  717. func mtprotoRoutesThroughXray(inbound *model.Inbound) bool {
  718. if inbound == nil || inbound.Protocol != model.MTProto {
  719. return false
  720. }
  721. var parsed struct {
  722. RouteThroughXray bool `json:"routeThroughXray"`
  723. }
  724. if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil {
  725. return false
  726. }
  727. return parsed.RouteThroughXray
  728. }
  729. func settingsRouteXrayPort(parsed map[string]any) int {
  730. switch v := parsed["routeXrayPort"].(type) {
  731. case float64:
  732. return int(v)
  733. case int:
  734. return v
  735. case json.Number:
  736. if n, err := v.Int64(); err == nil {
  737. return int(n)
  738. }
  739. }
  740. return 0
  741. }
  742. func parseRouteXrayPort(settings string) int {
  743. if settings == "" {
  744. return 0
  745. }
  746. var parsed map[string]any
  747. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  748. return 0
  749. }
  750. return settingsRouteXrayPort(parsed)
  751. }
  752. // normalizeMtprotoXrayPort guarantees a routed mtproto inbound carries a stable
  753. // loopback egress port in its settings, so the generated Xray SOCKS bridge and
  754. // the mtg sidecar agree on where mtg dials out. The port is backend-owned: it is
  755. // allocated once when routing is first enabled and preserved across edits
  756. // (carried over from oldSettings, which wins over any value the client echoed
  757. // back). When routing is off it — together with the now-inert outbound
  758. // selection — is stripped so a disabled bridge leaves nothing stale behind.
  759. //
  760. // It returns an error when an egress port cannot be allocated or persisted, so
  761. // the caller refuses the save rather than storing a routed-but-portless inbound,
  762. // which would otherwise route no traffic and have its mtg metrics skipped (see
  763. // mtproto_job) — silently losing its accounting.
  764. func (s *InboundService) normalizeMtprotoXrayPort(inbound *model.Inbound, oldSettings string) error {
  765. if inbound.Protocol != model.MTProto {
  766. return nil
  767. }
  768. var parsed map[string]any
  769. if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil || parsed == nil {
  770. return nil
  771. }
  772. routed, _ := parsed["routeThroughXray"].(bool)
  773. if !routed {
  774. _, hadPort := parsed["routeXrayPort"]
  775. _, hadTag := parsed["outboundTag"]
  776. if !hadPort && !hadTag {
  777. return nil
  778. }
  779. delete(parsed, "routeXrayPort")
  780. delete(parsed, "outboundTag")
  781. if bs, err := json.MarshalIndent(parsed, "", " "); err == nil {
  782. inbound.Settings = string(bs)
  783. } else {
  784. logger.Warning("mtproto: failed to marshal settings after disabling routing:", err)
  785. }
  786. return nil
  787. }
  788. // Prefer the already-stored port (carried across edits), then any value the
  789. // client sent, then allocate a fresh one.
  790. port := parseRouteXrayPort(oldSettings)
  791. if port <= 0 {
  792. port = settingsRouteXrayPort(parsed)
  793. }
  794. if port <= 0 {
  795. allocated, err := mtproto.FreeLocalPort()
  796. if err != nil {
  797. return common.NewError("mtproto: could not allocate an Xray egress port:", err)
  798. }
  799. port = allocated
  800. }
  801. if settingsRouteXrayPort(parsed) == port {
  802. return nil
  803. }
  804. parsed["routeXrayPort"] = port
  805. bs, err := json.MarshalIndent(parsed, "", " ")
  806. if err != nil {
  807. return common.NewError("mtproto: could not persist the Xray egress port:", err)
  808. }
  809. inbound.Settings = string(bs)
  810. return nil
  811. }
  812. // AddInbound creates a new inbound configuration.
  813. // It validates port uniqueness, client email uniqueness, and required fields,
  814. // then saves the inbound to the database and optionally adds it to the running Xray instance.
  815. // Returns the created inbound, whether Xray needs restart, and any error.
  816. func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  817. inbound.Id = 0
  818. // Normalize streamSettings based on protocol
  819. s.normalizeStreamSettings(inbound)
  820. if err := validateFinalMaskRealityCombo(inbound.StreamSettings); err != nil {
  821. return inbound, false, err
  822. }
  823. if err := validateFinalMaskXmcProfiles(inbound.StreamSettings); err != nil {
  824. return inbound, false, err
  825. }
  826. s.normalizeMtprotoSecret(inbound)
  827. if err := s.normalizeMtprotoXrayPort(inbound, ""); err != nil {
  828. return inbound, false, err
  829. }
  830. inbound.SubSortIndex = normalizeSubSortIndex(inbound.SubSortIndex)
  831. if err := normalizeInboundShareAddressStrict(inbound); err != nil {
  832. return inbound, false, err
  833. }
  834. conflict, err := s.checkPortConflict(inbound, 0)
  835. if err != nil {
  836. return inbound, false, err
  837. }
  838. if conflict != nil {
  839. return inbound, false, common.NewError(conflict.String())
  840. }
  841. inbound.Tag, err = s.resolveInboundTag(inbound, 0)
  842. if err != nil {
  843. return inbound, false, err
  844. }
  845. clients, err := s.GetClients(inbound)
  846. if err != nil {
  847. return inbound, false, err
  848. }
  849. existEmail, err := s.clientService.checkEmailsExistForClients(s, clients, nil)
  850. if err != nil {
  851. return inbound, false, err
  852. }
  853. if existEmail != "" {
  854. return inbound, false, common.NewError("Duplicate email:", existEmail)
  855. }
  856. // Ensure created_at and updated_at on clients in settings
  857. if len(clients) > 0 {
  858. var settings map[string]any
  859. if err2 := json.Unmarshal([]byte(inbound.Settings), &settings); err2 == nil && settings != nil {
  860. now := time.Now().Unix() * 1000
  861. updatedClients := make([]model.Client, 0, len(clients))
  862. for _, c := range clients {
  863. if c.CreatedAt == 0 {
  864. c.CreatedAt = now
  865. }
  866. c.UpdatedAt = now
  867. updatedClients = append(updatedClients, c)
  868. }
  869. settings["clients"] = updatedClients
  870. if bs, err3 := json.MarshalIndent(settings, "", " "); err3 == nil {
  871. inbound.Settings = string(bs)
  872. } else {
  873. logger.Debug("Unable to marshal inbound settings with timestamps:", err3)
  874. }
  875. } else if err2 != nil {
  876. logger.Debug("Unable to parse inbound settings for timestamps:", err2)
  877. }
  878. }
  879. // Defensively fix any Shadowsocks-2022 client PSK whose length doesn't match
  880. // the inbound method (e.g. an API caller supplied a wrong-size key).
  881. if normalized, changed := normalizeShadowsocksClientKeys(inbound.Settings); changed {
  882. inbound.Settings = normalized
  883. }
  884. // Secure client ID
  885. for _, client := range clients {
  886. switch inbound.Protocol {
  887. case "trojan":
  888. if client.Password == "" {
  889. return inbound, false, common.NewError("empty client ID")
  890. }
  891. case "shadowsocks":
  892. if client.Email == "" {
  893. return inbound, false, common.NewError("empty client ID")
  894. }
  895. case "hysteria":
  896. if client.Auth == "" {
  897. return inbound, false, common.NewError("empty client ID")
  898. }
  899. case "wireguard":
  900. if client.PublicKey == "" {
  901. return inbound, false, common.NewError("wireguard client requires a key")
  902. }
  903. case "mtproto":
  904. if client.Secret == "" {
  905. return inbound, false, common.NewError("mtproto client requires a secret")
  906. }
  907. if client.AdTag != "" && !model.ValidMtprotoAdTag(client.AdTag) {
  908. return inbound, false, common.NewError("mtproto client ad tag must be 32 hex characters")
  909. }
  910. default:
  911. if client.ID == "" {
  912. return inbound, false, common.NewError("empty client ID")
  913. }
  914. }
  915. }
  916. db := database.GetDB()
  917. needRestart := false
  918. var postCommitApply func()
  919. err = db.Transaction(func(tx *gorm.DB) error {
  920. markDirty := false
  921. if err := tx.Omit("ClientStats").Save(inbound).Error; err != nil {
  922. return err
  923. }
  924. // Emails seeded here (import's ClientStats, e.g. the controller's forced
  925. // Enable=true on every imported stat row) are authoritative for this call
  926. // and must not be clobbered by the AddClientStat loop below, which derives
  927. // its enable/total/expiry/reset from Settings.clients[] instead — a second,
  928. // possibly-stale source for the same columns on a plain (non-import) create.
  929. statEmails := make(map[string]bool, len(inbound.ClientStats))
  930. for i := range inbound.ClientStats {
  931. if inbound.ClientStats[i].Email == "" {
  932. continue
  933. }
  934. statEmails[inbound.ClientStats[i].Email] = true
  935. inbound.ClientStats[i].Id = 0
  936. inbound.ClientStats[i].InboundId = inbound.Id
  937. if err := tx.Clauses(clause.OnConflict{
  938. Columns: []clause.Column{{Name: "email"}},
  939. DoNothing: true,
  940. }).Create(&inbound.ClientStats[i]).Error; err != nil {
  941. return err
  942. }
  943. }
  944. for _, client := range clients {
  945. if statEmails[client.Email] {
  946. continue
  947. }
  948. if err := s.AddClientStat(tx, inbound.Id, &client); err != nil {
  949. return err
  950. }
  951. }
  952. if err := s.clientService.SyncInbound(tx, inbound.Id, clients); err != nil {
  953. return err
  954. }
  955. if _, err := database.CreateHostsFromExternalProxy(tx, inbound.Id, inbound.StreamSettings); err != nil {
  956. return err
  957. }
  958. if inbound.NodeID != nil {
  959. nodeID := *inbound.NodeID
  960. if err := (&NodeService{}).EnsureInboundTagAllowedTx(tx, nodeID, inbound.Tag); err != nil {
  961. return err
  962. }
  963. }
  964. if inbound.Enable {
  965. if inbound.NodeID != nil {
  966. markDirty = true
  967. } else {
  968. rt, push, _, perr := s.nodePushPlan(inbound)
  969. if perr != nil {
  970. return perr
  971. }
  972. if push {
  973. payload := inbound
  974. pushable := true
  975. if inbound.Protocol == model.MTProto {
  976. if built, bErr := s.buildRuntimeInboundForAPI(tx, inbound); bErr == nil {
  977. payload = built
  978. } else {
  979. logger.Debug("Unable to prepare runtime inbound config:", bErr)
  980. pushable = false
  981. }
  982. }
  983. if pushable {
  984. postCommitApply = func() {
  985. if err1 := rt.AddInbound(context.Background(), payload); err1 == nil {
  986. logger.Debug("New inbound added on", rt.Name(), ":", inbound.Tag)
  987. } else {
  988. logger.Debug("Unable to add inbound on", rt.Name(), ":", err1)
  989. needRestart = true
  990. }
  991. }
  992. }
  993. }
  994. }
  995. }
  996. if markDirty && inbound.NodeID != nil {
  997. return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID)
  998. }
  999. return nil
  1000. })
  1001. if err != nil {
  1002. return inbound, false, err
  1003. }
  1004. if postCommitApply != nil {
  1005. postCommitApply()
  1006. }
  1007. // A routed mtproto inbound is not an Xray inbound itself, so the runtime
  1008. // push above only (re)starts the mtg sidecar. The egress SOCKS bridge lives
  1009. // in the generated config, so force a regen to wire it in.
  1010. if mtprotoRoutesThroughXray(inbound) {
  1011. needRestart = true
  1012. }
  1013. return inbound, needRestart, err
  1014. }
  1015. func (s *InboundService) DelInbound(id int) (bool, error) {
  1016. db := database.GetDB()
  1017. needRestart := false
  1018. var postCommitApply func()
  1019. var ib model.Inbound
  1020. loadErr := db.Model(model.Inbound{}).Where("id = ?", id).First(&ib).Error
  1021. if loadErr == nil {
  1022. shouldPushToRuntime := ib.NodeID != nil || ib.Enable
  1023. if shouldPushToRuntime {
  1024. if ib.NodeID != nil {
  1025. rt, push, _, perr := s.nodePushPlan(&ib)
  1026. if perr != nil {
  1027. logger.Warning("DelInbound: node runtime lookup failed, deleting central row anyway:", perr)
  1028. } else if push {
  1029. postCommitApply = func() {
  1030. if err1 := rt.DelInbound(context.Background(), &ib); err1 == nil {
  1031. logger.Debug("Inbound deleted on", rt.Name(), ":", ib.Tag)
  1032. } else {
  1033. logger.Warning("DelInbound on", rt.Name(), "failed after commit:", err1)
  1034. }
  1035. }
  1036. }
  1037. } else {
  1038. rt, push, _, perr := s.nodePushPlan(&ib)
  1039. if perr != nil {
  1040. logger.Warning("DelInbound: runtime lookup failed, deleting central row anyway:", perr)
  1041. } else if push {
  1042. postCommitApply = func() {
  1043. if err1 := rt.DelInbound(context.Background(), &ib); err1 == nil {
  1044. logger.Debug("Inbound deleted on", rt.Name(), ":", ib.Tag)
  1045. } else {
  1046. logger.Warning("DelInbound on", rt.Name(), "failed after commit:", err1)
  1047. needRestart = true
  1048. }
  1049. }
  1050. } else {
  1051. needRestart = true
  1052. }
  1053. }
  1054. } else {
  1055. logger.Debug("DelInbound: skipping runtime push for disabled local inbound id:", id)
  1056. }
  1057. } else {
  1058. logger.Debug("DelInbound: inbound not found, id:", id)
  1059. }
  1060. if err := db.Transaction(func(tx *gorm.DB) error {
  1061. if err := s.clientService.DetachInbound(tx, id); err != nil {
  1062. return err
  1063. }
  1064. if err := tx.Delete(model.Inbound{}, id).Error; err != nil {
  1065. return err
  1066. }
  1067. if err := tx.Where("inbound_id = ?", id).Delete(&model.Host{}).Error; err != nil {
  1068. return err
  1069. }
  1070. if loadErr == nil && ib.NodeID != nil {
  1071. return (&NodeService{}).MarkNodeDirtyTx(tx, *ib.NodeID)
  1072. }
  1073. return nil
  1074. }); err != nil {
  1075. return needRestart, err
  1076. }
  1077. if postCommitApply != nil {
  1078. postCommitApply()
  1079. }
  1080. if loadErr == nil && ib.Tag != "" {
  1081. if routingChanged, syncErr := (&XraySettingService{}).RemoveInboundTagReferences(ib.Tag); syncErr != nil {
  1082. logger.Warning("DelInbound: sync routing on inbound delete failed:", syncErr)
  1083. } else if routingChanged {
  1084. needRestart = true
  1085. }
  1086. }
  1087. if !database.IsPostgres() {
  1088. var count int64
  1089. if err := db.Model(&model.Inbound{}).Count(&count).Error; err != nil {
  1090. return needRestart, err
  1091. }
  1092. if count == 0 {
  1093. if err := db.Exec("DELETE FROM sqlite_sequence WHERE name = ?", "inbounds").Error; err != nil {
  1094. return needRestart, err
  1095. }
  1096. }
  1097. }
  1098. // Drop the egress SOCKS bridge a routed mtproto inbound left in the config.
  1099. if mtprotoRoutesThroughXray(&ib) {
  1100. needRestart = true
  1101. }
  1102. return needRestart, nil
  1103. }
  1104. type BulkDelInboundResult struct {
  1105. Deleted int `json:"deleted"`
  1106. Skipped []BulkDelInboundReport `json:"skipped,omitempty"`
  1107. }
  1108. type BulkDelInboundReport struct {
  1109. Id int `json:"id"`
  1110. Reason string `json:"reason"`
  1111. }
  1112. // DelInbounds removes every inbound in the list, reusing the single-delete
  1113. // path per id. Failures are recorded in Skipped and processing continues for
  1114. // the rest; the aggregated needRestart is returned so the caller restarts
  1115. // xray at most once.
  1116. func (s *InboundService) DelInbounds(ids []int) (BulkDelInboundResult, bool, error) {
  1117. result := BulkDelInboundResult{}
  1118. needRestart := false
  1119. for _, id := range ids {
  1120. r, err := s.DelInbound(id)
  1121. if err != nil {
  1122. result.Skipped = append(result.Skipped, BulkDelInboundReport{Id: id, Reason: err.Error()})
  1123. continue
  1124. }
  1125. result.Deleted++
  1126. if r {
  1127. needRestart = true
  1128. }
  1129. }
  1130. return result, needRestart, nil
  1131. }
  1132. func (s *InboundService) GetInbound(id int) (*model.Inbound, error) {
  1133. db := database.GetDB()
  1134. inbound := &model.Inbound{}
  1135. err := db.Model(model.Inbound{}).First(inbound, id).Error
  1136. if err != nil {
  1137. return nil, err
  1138. }
  1139. return inbound, nil
  1140. }
  1141. func (s *InboundService) GetInboundDetail(id int) (*model.Inbound, error) {
  1142. db := database.GetDB()
  1143. inbound := &model.Inbound{}
  1144. err := db.Model(model.Inbound{}).Preload("ClientStats").First(inbound, id).Error
  1145. if err != nil {
  1146. return nil, err
  1147. }
  1148. s.enrichClientStats(db, []*model.Inbound{inbound})
  1149. s.overlayInboundsClientStats(db, []*model.Inbound{inbound})
  1150. return inbound, nil
  1151. }
  1152. func (s *InboundService) SetInboundEnable(id int, enable bool) (bool, error) {
  1153. inbound, err := s.GetInbound(id)
  1154. if err != nil {
  1155. return false, err
  1156. }
  1157. if inbound.Enable == enable {
  1158. return false, nil
  1159. }
  1160. db := database.GetDB()
  1161. if err := db.Transaction(func(tx *gorm.DB) error {
  1162. if err := tx.Model(model.Inbound{}).Where("id = ?", id).
  1163. Update("enable", enable).Error; err != nil {
  1164. return err
  1165. }
  1166. if inbound.NodeID != nil {
  1167. return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID)
  1168. }
  1169. return nil
  1170. }); err != nil {
  1171. return false, err
  1172. }
  1173. inbound.Enable = enable
  1174. needRestart := false
  1175. rt, push, _, perr := s.nodePushPlan(inbound)
  1176. if perr != nil {
  1177. return false, perr
  1178. }
  1179. // Remote nodes interpret DelInbound as a real row delete (it hits
  1180. // panel/api/inbounds/del/:id on the remote), so toggling the enable
  1181. // switch on a remote inbound used to wipe the row entirely (#4402).
  1182. // PATCH the remote row via UpdateInbound instead — preserves the
  1183. // settings/client history and just flips the enable flag.
  1184. if inbound.NodeID != nil {
  1185. if push {
  1186. if err := rt.UpdateInbound(context.Background(), inbound, inbound); err != nil {
  1187. logger.Warning("SetInboundEnable: remote UpdateInbound on", rt.Name(), "failed:", err)
  1188. }
  1189. }
  1190. return false, nil
  1191. }
  1192. if mtprotoRoutesThroughXray(inbound) {
  1193. needRestart = true
  1194. }
  1195. if !push {
  1196. return true, nil
  1197. }
  1198. if err := rt.DelInbound(context.Background(), inbound); err != nil &&
  1199. !strings.Contains(err.Error(), "not found") {
  1200. logger.Debug("SetInboundEnable: DelInbound on", rt.Name(), "failed:", err)
  1201. needRestart = true
  1202. }
  1203. if !enable {
  1204. return needRestart, nil
  1205. }
  1206. runtimeInbound, err := s.buildRuntimeInboundForAPI(db, inbound)
  1207. if err != nil {
  1208. logger.Debug("SetInboundEnable: build runtime config failed:", err)
  1209. return true, nil
  1210. }
  1211. if err := rt.AddInbound(context.Background(), runtimeInbound); err != nil {
  1212. logger.Debug("SetInboundEnable: AddInbound on", rt.Name(), "failed:", err)
  1213. needRestart = true
  1214. }
  1215. return needRestart, nil
  1216. }
  1217. func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  1218. // Normalize streamSettings based on protocol
  1219. s.normalizeStreamSettings(inbound)
  1220. if err := validateFinalMaskRealityCombo(inbound.StreamSettings); err != nil {
  1221. return inbound, false, err
  1222. }
  1223. if err := validateFinalMaskXmcProfiles(inbound.StreamSettings); err != nil {
  1224. return inbound, false, err
  1225. }
  1226. s.normalizeMtprotoSecret(inbound)
  1227. inbound.SubSortIndex = normalizeSubSortIndex(inbound.SubSortIndex)
  1228. oldInbound, err := s.GetInbound(inbound.Id)
  1229. if err != nil {
  1230. return inbound, false, err
  1231. }
  1232. // Restore the stored NodeID before the port-conflict check so a node inbound
  1233. // stays scoped to its own node (the payload's nodeId is unreliable, often absent).
  1234. inbound.NodeID = oldInbound.NodeID
  1235. conflict, err := s.checkPortConflict(inbound, inbound.Id)
  1236. if err != nil {
  1237. return inbound, false, err
  1238. }
  1239. if conflict != nil {
  1240. return inbound, false, common.NewError(conflict.String())
  1241. }
  1242. // Capture the pre-edit protocol and routing state before oldInbound is
  1243. // overwritten with the new values further down, then ensure a routed
  1244. // inbound keeps a stable egress port (reusing the one already stored).
  1245. oldProtocol := oldInbound.Protocol
  1246. oldRoutedMtproto := mtprotoRoutesThroughXray(oldInbound)
  1247. if err := s.normalizeMtprotoXrayPort(inbound, oldInbound.Settings); err != nil {
  1248. return inbound, false, err
  1249. }
  1250. tag := oldInbound.Tag
  1251. oldBits := inboundTransports(oldInbound.Protocol, oldInbound.StreamSettings, oldInbound.Settings)
  1252. oldTagWasAuto := isAutoGeneratedTag(tag, oldInbound.Port, oldInbound.NodeID, oldBits)
  1253. needRestart := false
  1254. var postCommitApply func()
  1255. txErr := runSerializedTx(func(tx *gorm.DB) error {
  1256. if err := s.updateClientTraffics(tx, oldInbound, inbound); err != nil {
  1257. return err
  1258. }
  1259. // Ensure created_at and updated_at exist in inbound.Settings clients
  1260. {
  1261. var oldSettings map[string]any
  1262. _ = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  1263. emailToCreated := map[string]int64{}
  1264. emailToUpdated := map[string]int64{}
  1265. if oldSettings != nil {
  1266. if oc, ok := oldSettings["clients"].([]any); ok {
  1267. for _, it := range oc {
  1268. if m, ok2 := it.(map[string]any); ok2 {
  1269. if email, ok3 := m["email"].(string); ok3 {
  1270. switch v := m["created_at"].(type) {
  1271. case float64:
  1272. emailToCreated[email] = int64(v)
  1273. case int64:
  1274. emailToCreated[email] = v
  1275. }
  1276. switch v := m["updated_at"].(type) {
  1277. case float64:
  1278. emailToUpdated[email] = int64(v)
  1279. case int64:
  1280. emailToUpdated[email] = v
  1281. }
  1282. }
  1283. }
  1284. }
  1285. }
  1286. }
  1287. var newSettings map[string]any
  1288. if err2 := json.Unmarshal([]byte(inbound.Settings), &newSettings); err2 == nil && newSettings != nil {
  1289. now := time.Now().Unix() * 1000
  1290. if nSlice, ok := newSettings["clients"].([]any); ok {
  1291. for i := range nSlice {
  1292. if m, ok2 := nSlice[i].(map[string]any); ok2 {
  1293. email, _ := m["email"].(string)
  1294. if _, ok3 := m["created_at"]; !ok3 {
  1295. if v, ok4 := emailToCreated[email]; ok4 && v > 0 {
  1296. m["created_at"] = v
  1297. } else {
  1298. m["created_at"] = now
  1299. }
  1300. }
  1301. // Preserve client's updated_at if present; do not bump on parent inbound update
  1302. if _, hasUpdated := m["updated_at"]; !hasUpdated {
  1303. if v, ok4 := emailToUpdated[email]; ok4 && v > 0 {
  1304. m["updated_at"] = v
  1305. }
  1306. }
  1307. nSlice[i] = m
  1308. }
  1309. }
  1310. newSettings["clients"] = nSlice
  1311. if bs, err3 := json.MarshalIndent(newSettings, "", " "); err3 == nil {
  1312. inbound.Settings = string(bs)
  1313. }
  1314. }
  1315. }
  1316. }
  1317. // A Shadowsocks-2022 method change resizes the key, but existing client PSKs
  1318. // keep their old length and would be rejected by xray. Regenerate mismatched
  1319. // client keys so the inbound stays connectable.
  1320. if normalized, changed := normalizeShadowsocksClientKeys(inbound.Settings); changed {
  1321. inbound.Settings = normalized
  1322. logger.Warning("Shadowsocks inbound", inbound.Id, "method change resized keys; regenerated mismatched client PSK(s)")
  1323. }
  1324. // Re-gate Vision flow now that the new stream/encryption is known: if this
  1325. // VLESS inbound just became flow-eligible (e.g. vlessenc was enabled on an
  1326. // XHTTP inbound), restore Vision for clients whose intended flow is Vision
  1327. // but was stripped while the inbound was ineligible.
  1328. if restored, changed := s.restoreVisionFlowForEligibleInbound(tx, inbound.Settings, inbound.StreamSettings, inbound.Protocol); changed {
  1329. inbound.Settings = restored
  1330. }
  1331. oldInbound.Total = inbound.Total
  1332. oldInbound.Remark = inbound.Remark
  1333. oldInbound.SubSortIndex = inbound.SubSortIndex
  1334. oldInbound.Enable = inbound.Enable
  1335. oldInbound.ExpiryTime = inbound.ExpiryTime
  1336. oldInbound.TrafficReset = inbound.TrafficReset
  1337. oldInbound.Listen = inbound.Listen
  1338. oldInbound.Port = inbound.Port
  1339. oldInbound.Protocol = inbound.Protocol
  1340. oldInbound.Settings = inbound.Settings
  1341. oldInbound.StreamSettings = inbound.StreamSettings
  1342. oldInbound.Sniffing = inbound.Sniffing
  1343. if strings.TrimSpace(inbound.ShareAddrStrategy) == "" {
  1344. normalizeInboundShareAddress(oldInbound)
  1345. inbound.ShareAddrStrategy = oldInbound.ShareAddrStrategy
  1346. inbound.ShareAddr = oldInbound.ShareAddr
  1347. } else {
  1348. if err := normalizeInboundShareAddressStrict(inbound); err != nil {
  1349. return err
  1350. }
  1351. oldInbound.ShareAddrStrategy = inbound.ShareAddrStrategy
  1352. oldInbound.ShareAddr = inbound.ShareAddr
  1353. }
  1354. if oldTagWasAuto && inbound.Tag == tag {
  1355. inbound.Tag = ""
  1356. }
  1357. resolvedTag, err := s.resolveInboundTag(inbound, inbound.Id)
  1358. if err != nil {
  1359. return err
  1360. }
  1361. oldInbound.Tag = resolvedTag
  1362. inbound.Tag = oldInbound.Tag
  1363. if oldInbound.NodeID == nil {
  1364. rt, push, _, perr := s.nodePushPlan(oldInbound)
  1365. if perr != nil {
  1366. return perr
  1367. }
  1368. if !push {
  1369. needRestart = true
  1370. } else if oldProtocol == model.MTProto || oldInbound.Protocol == model.MTProto {
  1371. oldSnapshot := *oldInbound
  1372. oldSnapshot.Tag = tag
  1373. oldSnapshot.Protocol = oldProtocol
  1374. payload := oldInbound
  1375. pushable := true
  1376. if inbound.Enable {
  1377. if built, err2 := s.buildRuntimeInboundForAPI(tx, oldInbound); err2 == nil {
  1378. payload = built
  1379. } else {
  1380. logger.Debug("Unable to prepare runtime inbound config:", err2)
  1381. pushable = false
  1382. }
  1383. }
  1384. newProtocolIsMtproto := oldInbound.Protocol == model.MTProto
  1385. if pushable {
  1386. postCommitApply = func() {
  1387. if err2 := rt.UpdateInbound(context.Background(), &oldSnapshot, payload); err2 == nil {
  1388. logger.Debug("Updated inbound applied on", rt.Name(), ":", oldInbound.Tag)
  1389. } else {
  1390. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  1391. if !newProtocolIsMtproto {
  1392. needRestart = true
  1393. }
  1394. }
  1395. }
  1396. }
  1397. } else {
  1398. oldSnapshot := *oldInbound
  1399. oldSnapshot.Tag = tag
  1400. var runtimeInbound *model.Inbound
  1401. if inbound.Enable {
  1402. var err2 error
  1403. runtimeInbound, err2 = s.buildRuntimeInboundForAPI(tx, oldInbound)
  1404. if err2 != nil {
  1405. logger.Debug("Unable to prepare runtime inbound config:", err2)
  1406. needRestart = true
  1407. }
  1408. }
  1409. postCommitApply = func() {
  1410. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 == nil {
  1411. logger.Debug("Old inbound deleted on", rt.Name(), ":", tag)
  1412. }
  1413. if runtimeInbound == nil {
  1414. return
  1415. }
  1416. if err2 := rt.AddInbound(context.Background(), runtimeInbound); err2 == nil {
  1417. logger.Debug("Updated inbound added on", rt.Name(), ":", oldInbound.Tag)
  1418. } else {
  1419. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  1420. needRestart = true
  1421. }
  1422. }
  1423. }
  1424. } else {
  1425. nodeID := *oldInbound.NodeID
  1426. if err := (&NodeService{}).EnsureInboundTagAllowedTx(tx, nodeID, oldInbound.Tag); err != nil {
  1427. return err
  1428. }
  1429. }
  1430. if err := tx.Save(oldInbound).Error; err != nil {
  1431. return err
  1432. }
  1433. newClients, gcErr := s.GetClients(oldInbound)
  1434. if gcErr != nil {
  1435. return gcErr
  1436. }
  1437. if err := s.clientService.SyncInbound(tx, oldInbound.Id, newClients); err != nil {
  1438. return err
  1439. }
  1440. if oldInbound.NodeID != nil {
  1441. if err := (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID); err != nil {
  1442. return err
  1443. }
  1444. }
  1445. // (Re)generate the Xray config whenever routing was or is now enabled, so
  1446. // the egress SOCKS bridge is added, moved, or dropped to match the new
  1447. // settings.
  1448. if mtprotoRoutesThroughXray(inbound) || oldRoutedMtproto {
  1449. needRestart = true
  1450. }
  1451. return nil
  1452. })
  1453. if txErr != nil {
  1454. return inbound, false, txErr
  1455. }
  1456. if postCommitApply != nil {
  1457. postCommitApply()
  1458. }
  1459. // After the rename is committed, point any routing rules / loopback outbounds
  1460. // in xrayTemplateConfig at the new tag (oldInbound.Tag now holds the resolved
  1461. // new tag; tag holds the pre-edit one). Done post-commit so a sync failure
  1462. // can't roll back the inbound edit.
  1463. if tag != oldInbound.Tag {
  1464. if routingChanged, syncErr := (&XraySettingService{}).PropagateInboundTagRename(tag, oldInbound.Tag); syncErr != nil {
  1465. logger.Warning("UpdateInbound: sync routing on tag rename failed:", syncErr)
  1466. } else if routingChanged {
  1467. needRestart = true
  1468. }
  1469. }
  1470. return inbound, needRestart, nil
  1471. }
  1472. func (s *InboundService) buildRuntimeInboundForAPI(tx *gorm.DB, inbound *model.Inbound) (*model.Inbound, error) {
  1473. if inbound == nil {
  1474. return nil, fmt.Errorf("inbound is nil")
  1475. }
  1476. runtimeInbound := *inbound
  1477. settings := map[string]any{}
  1478. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1479. return nil, err
  1480. }
  1481. mutated := false
  1482. if clients, ok := settings["clients"].([]any); ok {
  1483. var clientStats []xray.ClientTraffic
  1484. err := tx.Model(xray.ClientTraffic{}).
  1485. Where("inbound_id = ?", inbound.Id).
  1486. Select("email", "enable").
  1487. Find(&clientStats).Error
  1488. if err != nil {
  1489. return nil, err
  1490. }
  1491. enableMap := make(map[string]bool, len(clientStats))
  1492. for _, clientTraffic := range clientStats {
  1493. enableMap[clientTraffic.Email] = clientTraffic.Enable
  1494. }
  1495. finalClients := make([]any, 0, len(clients))
  1496. for _, client := range clients {
  1497. c, ok := client.(map[string]any)
  1498. if !ok {
  1499. continue
  1500. }
  1501. email, _ := c["email"].(string)
  1502. if enable, exists := enableMap[email]; exists && !enable {
  1503. continue
  1504. }
  1505. if manualEnable, ok := c["enable"].(bool); ok && !manualEnable {
  1506. continue
  1507. }
  1508. finalClients = append(finalClients, c)
  1509. }
  1510. settings["clients"] = finalClients
  1511. mutated = true
  1512. }
  1513. if inboundCanHostFallbacks(inbound) {
  1514. fallbacks, fbErr := s.fallbackService.BuildFallbacksJSON(tx, inbound.Id)
  1515. if fbErr != nil {
  1516. return nil, fbErr
  1517. }
  1518. if len(fallbacks) > 0 {
  1519. generic := make([]any, 0, len(fallbacks))
  1520. for _, f := range fallbacks {
  1521. generic = append(generic, f)
  1522. }
  1523. settings["fallbacks"] = generic
  1524. mutated = true
  1525. }
  1526. }
  1527. if !mutated {
  1528. return &runtimeInbound, nil
  1529. }
  1530. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1531. if err != nil {
  1532. return nil, err
  1533. }
  1534. runtimeInbound.Settings = string(modifiedSettings)
  1535. return &runtimeInbound, nil
  1536. }
  1537. // updateClientTraffics syncs the ClientTraffic rows with the inbound's clients
  1538. // list: removes rows for emails that disappeared, inserts rows for newly-added
  1539. // emails. Uses sets for O(N) lookup — the previous nested-loop implementation
  1540. // was O(N²) and degraded into multi-second pauses on inbounds with thousands
  1541. // of clients (toggling, saving, or deleting any such inbound felt frozen).
  1542. func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inbound, newInbound *model.Inbound) error {
  1543. oldClients, err := s.GetClients(oldInbound)
  1544. if err != nil {
  1545. return err
  1546. }
  1547. newClients, err := s.GetClients(newInbound)
  1548. if err != nil {
  1549. return err
  1550. }
  1551. // Email is the unique key for ClientTraffic rows. Clients without an
  1552. // email have no stats row to sync — skip them on both sides instead of
  1553. // risking a unique-constraint hit or accidental delete of an unrelated row.
  1554. oldEmails := make(map[string]struct{}, len(oldClients))
  1555. for i := range oldClients {
  1556. if oldClients[i].Email == "" {
  1557. continue
  1558. }
  1559. oldEmails[oldClients[i].Email] = struct{}{}
  1560. }
  1561. newEmails := make(map[string]struct{}, len(newClients))
  1562. for i := range newClients {
  1563. if newClients[i].Email == "" {
  1564. continue
  1565. }
  1566. newEmails[newClients[i].Email] = struct{}{}
  1567. }
  1568. // Drop stats rows for removed emails — but not when a sibling inbound
  1569. // still references the email, since the row is the shared accumulator.
  1570. for i := range oldClients {
  1571. email := oldClients[i].Email
  1572. if email == "" {
  1573. continue
  1574. }
  1575. if _, kept := newEmails[email]; kept {
  1576. continue
  1577. }
  1578. stillUsed, err := s.emailUsedByOtherInbounds(email, oldInbound.Id)
  1579. if err != nil {
  1580. return err
  1581. }
  1582. if stillUsed {
  1583. continue
  1584. }
  1585. if err := s.DelClientStat(tx, email); err != nil {
  1586. return err
  1587. }
  1588. // Keep inbound_client_ips in sync when the inbound edit drops an
  1589. // email, so the IP-limit job doesn't keep a ghost tracking row (#4963).
  1590. if err := s.DelClientIPs(tx, email); err != nil {
  1591. return err
  1592. }
  1593. }
  1594. for i := range newClients {
  1595. email := newClients[i].Email
  1596. if email == "" {
  1597. continue
  1598. }
  1599. if _, existed := oldEmails[email]; existed {
  1600. if err := s.UpdateClientStat(tx, email, &newClients[i]); err != nil {
  1601. return err
  1602. }
  1603. continue
  1604. }
  1605. if err := s.AddClientStat(tx, oldInbound.Id, &newClients[i]); err != nil {
  1606. return err
  1607. }
  1608. }
  1609. return nil
  1610. }
  1611. func (s *InboundService) GetInboundTags() (string, error) {
  1612. db := database.GetDB()
  1613. var inboundTags []string
  1614. err := db.Model(model.Inbound{}).Select("tag").Find(&inboundTags).Error
  1615. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1616. return "", err
  1617. }
  1618. tags, _ := json.Marshal(inboundTags)
  1619. return string(tags), nil
  1620. }
  1621. func (s *InboundService) GetClientReverseTags() (string, error) {
  1622. db := database.GetDB()
  1623. var inbounds []model.Inbound
  1624. err := db.Model(model.Inbound{}).Select("settings").Where("protocol = ?", "vless").Find(&inbounds).Error
  1625. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1626. return "[]", err
  1627. }
  1628. tagSet := make(map[string]struct{})
  1629. for _, inbound := range inbounds {
  1630. var settings map[string]any
  1631. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1632. continue
  1633. }
  1634. clients, ok := settings["clients"].([]any)
  1635. if !ok {
  1636. continue
  1637. }
  1638. for _, client := range clients {
  1639. clientMap, ok := client.(map[string]any)
  1640. if !ok {
  1641. continue
  1642. }
  1643. reverse, ok := clientMap["reverse"].(map[string]any)
  1644. if !ok {
  1645. continue
  1646. }
  1647. tag, _ := reverse["tag"].(string)
  1648. tag = strings.TrimSpace(tag)
  1649. if tag != "" {
  1650. tagSet[tag] = struct{}{}
  1651. }
  1652. }
  1653. }
  1654. rawTags := make([]string, 0, len(tagSet))
  1655. for tag := range tagSet {
  1656. rawTags = append(rawTags, tag)
  1657. }
  1658. sort.Strings(rawTags)
  1659. result, _ := json.Marshal(rawTags)
  1660. return string(result), nil
  1661. }
  1662. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  1663. db := database.GetDB()
  1664. var inbounds []*model.Inbound
  1665. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  1666. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1667. return nil, err
  1668. }
  1669. return inbounds, nil
  1670. }