inbound.go 74 KB

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