inbound.go 61 KB

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